创建批处理脚本以通过网络连接编辑主机文件

Create batch script to edit host file by network connection

我想使用此批处理脚本通过 windows 批处理自动将新条目添加到我的主机文件中。

我只想在办公室时编辑主机文件。我想这样说: if(network name=='OfficeWifi') do changes...

@echo off

set hostspath=%windir%\System32\drivers\etc\hosts
// if(network name=='OfficeWifi')
echo 81.155.145.48 ns1.intranet.de >> %hostspath%

exit

谢谢你的帮助

为了简单起见,您可以添加:

@echo off

set hostspath=%windir%\System32\drivers\etc\hosts
ping "name of office DC" 
if errorlevel 1 quit    
if not errorlevel 1 echo 81.155.145.48 ns1.intranet.de >> %hostspath%

您可以使用以下批处理文件获取当前连接的无线网络的网络名称(SSID):

for /f "tokens=3" %%a in ('netsh wlan show interface ^| findstr /r "^....SSID"' ) do @echo %%a

所以你的批处理文件看起来像:

@echo off
set hostspath=%windir%\System32\drivers\etc\hosts
for /f "tokens=3" %%a in ('netsh wlan show interface ^| findstr /r "^....SSID"' ) do (
  if "%%a"=="OfficeWifi" echo 81.155.145.48 ns1.intranet.de >> %hostspath%
)
exit

来源FOR /F, NETSH (Network Shell)