多网卡服务器里对插网线的网卡设置IP的批处理bat命令

迅恒数据中心

服务器有多个网卡其中只有一个或以上的网卡插了网线,只需要对其中一个插了网线的网卡自动设置IP(网关和子网掩码、DNS)。需要这样做是因为机房的服务器有多个网卡,有时候其中一个网卡插了网线或是2个网卡插了网线,如果是2个或以上网卡插了网线,也只用对其中一个插了网线的网卡设置IP就可以了。如果能实现对其中一个插了网线的网卡配置IP(需要判断哪些网卡插了网线,并过滤掉没插网线的网卡),我就可以封装一个自己常用的系统(如WIN2012R2,将批处理文件打包到GHO文件中去,并设置自动任务登陆时自动执行,达到对插了网线的网卡自动设置公网IP的目的),这样对服务器安装新系统我不需要去机房现场操作,只用远程登陆原服务器GHOST还原新封装的系统,就可以对服务器插了网线的网卡自动设置我自己想要的公网IP,服务器就可以直接连通网络了。

 

@echo off
set "newip=192.168.16.139"
set "netmask=255.255.255.0"
set "gateway=192.168.16.1"
set "dnsserver1=8.8.8.8"
set "dnsserver2=8.8.4.4"
for /f "tokens=*" %%A in ('wmic nic where "NetConnectionStatus='2'" get NetConnectionID /value^|find "="') do set %%A
echo NetConnectionID="%NetConnectionID%"
echo 开始设置IP...
netsh interface ip set address name="%NetConnectionID%" static "%newip%" "%netmask%" "%gateway%" 0
echo 设置IP完成
echo 开始设置DNS1...
netsh interface ip set dns name="%NetConnectionID%" static "%dnsserver1%" primary
echo 设置DNS1完成
echo 开始设置DNS2...
netsh interface ip add dns name="%NetConnectionID%" "%dnsserver2%" index=2
echo 设置DNS2完成
for /f "tokens=*" %%A in ('wmic nic where "NetConnectionID='%NetConnectionID%'" get index  /value^|find "="') do set %%A
echo index="%index%"
wmic nicconfig where index="%index%" call SetTcpipNetbios 2
@echo on
del %0
END

 

 

后面发现一个问题,有的服务器netsh interface ip 不生效,可能是服务器做有优化或一些权限设置引起的,改进为如下批处理:

@echo off
set "newip=192.168.16.139"
set "netmask=255.255.255.0"
set "gateway=192.168.16.1"
set "dns1=8.8.8.8"
set "dns2=8.8.4.4"
for /f "tokens=*" %%A in ('wmic nic where "NetConnectionStatus='2'" get NetConnectionID /value^|find "="') do set %%A
echo NetConnectionID="%NetConnectionID%"
for /f "tokens=*" %%A in ('wmic nic where "NetConnectionID='%NetConnectionID%'" get index  /value^|find "="') do set %%A
echo index="%index%"
wmic nicconfig where index="%index%" call enablestatic("%newip%"),("%netmask%")
wmic nicconfig where index="%index%" call setgateways("%gateway%"),(1)
wmic nicconfig where index="%index%" call SetDNSServerSearchOrder("%dns1%","%dns2%")
wmic nicconfig where index="%index%" call SetTcpipNetbios 2
@echo on
END
如果需要在执行时修改系统管理员administrator的密码,只用在END前加一行:
net user administrator mima
将上面mima替换为你需要设置的密码
如果需要在执行后自动删除此bat只用在END前加一行:
del %0

分类:教程帮助 百度收录 必应收录