Tag Archives: cmd

简单用批处理实现不同网段自动切换

在学校,自己拉了一根电信的网线,但是偶尔也需要享受一下教育网的飞速下载。所以,自己用路由器同时接入两个网络,并且利用下面这段代码来实现自动切换网络的功能。

核心代码是使用netsh函数来修改ip和dns配置。

  1. @echo off 
  2. ipconfig|find "192.168.137.100">nul&&goto :schoolnet&&goto :adsl 
  3. :adsl 
  4. netsh interface ip set address 本地连接 static 192.168.137.100 255.255.255.0 192.168.137.1 
  5. netsh interface ip set dns 本地连接 static 202.103.44.150 
  6.  
  7. CLS 
  8. echo "你现在是电信网了!" 
  9. goto :end 
  10. :schoolnet 
  11. netsh interface ip set address 本地连接 dhcp 
  12. netsh interface ip set dns 本地连接 dhcp 
  13. tasklist|find "DigitalChinaSupplicant">nul&& goto :last 
  14. explorer "D:Program FilesDigitalChinaDigitalChinaSupplicantDigitalChinaSupplicant.exe" 
  15. :last 
  16. CLS 
  17. echo "你现在是校园网了!" 
  18. :end 
  19. pause 

逐行来解释一下这段代码

@echo off //关闭输出,这样可以不要看到一些不需要的输出
ipconfig|find "192.168.137.100">nul&&goto :schoolnet&&goto :adsl
//ipconfig用来查看当前ip配置,其输出结果传递到find函数,在输出结果中查找192.168.137.100这个地址,这个是我电信时的ip地址,如果找到了,就用goto跳转到:schoolnet的位置,否则,就跳转到:adsl
:adsl  
netsh interface ip set address 本地连接 static 192.168.137.100 255.255.255.0 192.168.137.1
//通过netsh interface命令,修改本地连接的ip为192.168.137.100,子网掩码修改为255.255.255.0,网关修改为192.168.137.1
netsh interface ip set dns 本地连接 static 202.103.44.150
//利用netsh interface函数,修改dns为202.103.44.150,我没有使用备用dns

CLS   // 清屏
echo "你现在是电信网了!"   //输出提示
goto :end  //跳转到结束位置
:schoolnet
netsh interface ip set address 本地连接 dhcp
//校园网开启了dhcp,自动分配ip和dns的功能,所以,我就把本地连接的ip设置改为dhcp分配
netsh interface ip set dns 本地连接 dhcp
//同上,修改dns为dhcp分配
tasklist|find "DigitalChinaSupplicant">nul&& goto :last
//这里是检查我的校园网客户端是否启动
explorer "D:Program FilesDigitalChinaDigitalChinaSupplicantDigitalChinaSupplicant.exe"
//用explorer这个shell来启动客户端,如果不通过shell来运行,会由于客户端没有结束,导致这个cmd窗口不关闭的。
:last
CLS
echo "你现在是校园网了!" //输出提示
:end
pause //暂停一下,按任意键结束

需要注意的地方

由于是利用路由器来接入两个网段,因此,路由器的dhcp功能不能够开启。

这段代码的使用方法是,新建一个txt文档,然后把我提供的代码粘贴进去,保存,最后把这个文件的后缀修改为.bat。

在vista下,可能需要管理员权限来运行这段代码。

如果还有什么问题,可以留言,我会尽快给你回复的!