window切换hosts域名DNS

1、windows脚本

1.1、启动域名映射

判断:如果该域名映射未启动,则启动

@echo off
setlocal enabledelayedexpansion
 
:: 设置要替换的文件路径

set FILE_PATH=C:\Windows\System32\drivers\etc\hosts

set search_text=#192.168.1.240

findstr /C:"%search_text%" "%FILE_PATH%" >nul 2>&1

if %errorlevel% equ 0 (
	goto zhixing
) else (
    echo=
    echo ---------------------
    echo already home network!
    echo ---------------------
    echo=  
    goto end
)


:zhixing
set OLD_STRING=#192.168.1.240
set NEW_STRING=192.168.1.240

:: 使用PowerShell替换文件中的字符串
(for /f "delims=" %%i in ('type "%FILE_PATH%"') do (
 	set "str=%%i"
 	set "str=!str:%OLD_STRING%=%NEW_STRING%!"
 	echo !str!
)) > "%FILE_PATH%"_tmp.txt

move /y "%FILE_PATH%"_tmp.txt "%FILE_PATH%"

ipconfig /flushdns

echo= 
echo ----------------------------------
echo switch to home network successfull!
echo ----------------------------------
echo= 

:end
timeout /t 3
exit

endlocal

 

1.2、关闭域名映射

判断:如果该域名映射已经启动,则关闭(注释掉)

@echo off
setlocal enabledelayedexpansion
 
:: 设置要替换的文件路径

set FILE_PATH=C:\Windows\System32\drivers\etc\hosts

set search_text=#192.168.1.240

findstr /C:"%search_text%" "%FILE_PATH%" >nul 2>&1

if %errorlevel% equ 0 (
    echo=
    echo --------------------  
    echo already out network!
    echo --------------------
    echo=  
    goto end
) else (
    goto zhixing
)


:zhixing
set OLD_STRING=192.168.1.240
set NEW_STRING=#192.168.1.240

:: 使用PowerShell替换文件中的字符串
(for /f "delims=" %%i in ('type "%FILE_PATH%"') do (
 	set "str=%%i"
 	set "str=!str:%OLD_STRING%=%NEW_STRING%!"
 	echo !str!
)) > "%FILE_PATH%"_tmp.txt

move /y "%FILE_PATH%"_tmp.txt "%FILE_PATH%"

ipconfig /flushdns

echo=  
echo ----------------------------------
echo switch to out network successfull!
echo ----------------------------------
echo=  

:end
timeout /t 3
exit

endlocal

 

2、mac脚本

2.1、启动域名映射

#!/bin/bash
if grep -q '#192.168.31.240' /etc/hosts; then
    sudo sed -i '' 's/#192.168.31.240/192.168.31.240/g' /etc/hosts
    sudo killall -HUP mDNSResponder
else
    echo "已经是家庭网络"
fi

2.2、关闭域名映射

#!/bin/bash
if grep -q '#192.168.31.240' /etc/hosts; then
    echo "已经是外部网络"
else
    sudo sed -i '' 's/192.168.31.240/#192.168.31.240/g' /etc/hosts
    sudo killall -HUP mDNSResponder
fi