【问题标题】:Create batch script to edit host file by network connection创建批处理脚本以通过网络连接编辑主机文件
【发布时间】:2015-06-12 08:11:51
【问题描述】:

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

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

@echo off

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

exit

感谢您的帮助

【问题讨论】:

  • 如果您多次运行,这将多次添加该条目。您还希望在不在该网络时删除该条目。您不想自己编写脚本。以superuser.com/questions/663183/… 为例。

标签: windows batch-file cmd network-programming


【解决方案1】:

您可以使用以下批处理文件获取当前连接的无线网络的网络名称(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 /FNETSH (Network Shell)

【讨论】:

    【解决方案2】:

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

    @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%
    

    【讨论】:

    • 首先想到的是根据错误级别是否为 1,将脚本复制 2 个不同版本的 hostsfile 中的 1 个。这为您节省了主机文件中格式问题的麻烦,并且需要在之后清除它。
    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多