【问题标题】:IP based 'hosts' file基于 IP 的“主机”文件
【发布时间】:2014-02-09 20:05:46
【问题描述】:

我是新手,所以请耐心等待。

我想编写一个可以替换 etc/hosts 文件的批处理文件,具体取决于我登录时所在的 VLAN。 即:当我登录并获得 xxx.xxx.102.xxx 本地 IP 时,我想使用 hosts1 文件。当我登录并获得 xxx.xxx.103.xxx 本地 IP 后,我想使用 hosts2 文件。

所以基本上基于 ipconfig 的输出,扫描它以查找“102”和“103”,当输出中出现该数字时,它可以替换 Windows 目录中的 hosts 文件。

想法?

【问题讨论】:

  • 你不能在路由器配置中为你的 MAC 地址分配一个静态本地 IP 吗?

标签: windows batch-file dns ip hosts


【解决方案1】:
for %%a in (102 102 103) do (

  ipconfig | find "xxx.xxx.%%a.xxx" >nul 2>&1 && copy /y hosts%%a "%SystemRoot%\system32\drivers\etc\hosts"
)

如果您有管理员权限并且您的主机文件是 anemd hosts101 hosts102 ...

【讨论】:

    【解决方案2】:

    你可以试试这个。我在这里使用findstr 的正则表达式功能:

    ipconfig | findstr /er "[0-9][0-9]*.[0-9][0-9]*.102.[0-9][0-9]*" && copy hosts1 "%windir%\system32\drivers\etc\hosts"
    ipconfig | findstr /er "[0-9][0-9]*.[0-9][0-9]*.103.[0-9][0-9]*" && copy hosts2 "%windir%\system32\drivers\etc\hosts"
    

    【讨论】:

    • 我不确定正则表达式是否会处理 IP 地址中的单个数字。
    • @foxidrive 这个正则表达式显然不能测试 IPv4 的有效性。但是imo它可以在输出中find一个(有效的)IPv4。你为什么认为,它不会处理单个数字? [0-9][0-9]* 与 ERE 中的 [0-9]+ 相同,即 one or more
    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 2017-07-05
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多