操作系统使用批处理文件更改网络配置

经常在公司里面的实验室和办公室之间奔波,IP换来换去需要有耐心,索性参考别人写个脚本来缓解痛苦。

搜罗了一下发现大家貌似都在用netsh,根据百度百科:NetSH 是windows系统本身提供的功能强大的网络配置命令行工具。

发现果然参数巨多,但是如果只是配置IP地址和DNS,用interface ip就够了:
 
//设置IP
netsh interface ip set address name=链接名 source=static addr=IP地址 mask=掩码 gateway=网关 gwmetric=1 
 //设置主DNS
netsh interface ip set dns name=链接名 source=static addr=主DNS地址
 //设置备DNS
netsh interface ip add dns name=链接名 addr= 备DNS地址 2
//设置动态IP
netsh interface ip set address 链接名 dhcp
//设置动态DNS 
netsh interface ip set dns 链接名 dhcp
 
注:
1 - 一个参数后面可以接的参数都可以通过help或/?查询,比如netsh interface ip /?
2 - 链接名需要用双引号,比如"本地连接1"
3 - 添加备用DNS用add dns而不是set dns,并且最后需要DNS的编号,本例中为2
 
脚本如下:
LAB.BAT:

@rem echo OFF 
SETLOCAL 
set lan_name="Local Area Connection 2" 
rem define all the network addresses here  
set subnet=172.24
set lan_ip=%subnet%.178.135 
set sub_net_mask=255.255.255.0  
set gateway_addr=%subnet%.178.1  
::set pri_dns_addr=8.8.8.8  
set pri_dns_addr=%subnet%.222.90  
set sec_dns_addr=%subnet%.12.253
rem set the ip address  
@netsh interface ip set address name=%lan_name% source=static addr=%lan_ip% mask=%sub_net_mask% gateway=%gateway_addr% gwmetric=1  
rem set the DNS  
@netsh interface ip set dns name=%lan_name% source=static addr=%pri_dns_addr%  
rem add an alternative DNS (optional) 
@netsh interface ip add dns name=%lan_name% addr=%sec_dns_addr% 2  
ENDLOCAL

OFFICE.BAT:
@rem echo OFF  
set lan_name="Local Area Connection 2" 
netsh interface ip set address %lan_name% dhcp
netsh interface ip set dns %lan_name% dhcp
原文地址:https://www.cnblogs.com/dracohan/p/2988751.html