多网卡系统下识别默认IP与网关的批处理脚本优化需求
批处理脚本优化方案
需求说明
优化原有批处理脚本,实现以下逻辑:
- 遍历启用的网卡,通过NIC ID关联默认网关与对应IP地址
- 检测到多个默认网关时,列出所有网关后直接退出
- 仅存在单个默认网关时,显示该网关对应的IP地址与网关信息
优化后的批处理脚本
@echo off setlocal enabledelayedexpansion :: 初始化变量 set "gateway_count=0" set "last_index=" set "last_gw=" :: 获取所有启用网卡的Index、IP地址、默认网关,按Index关联 for /f "tokens=1,2,3 delims==," %%a in ('wmic nicconfig where IPEnabled^="True" get Index^,IPAddress^,DefaultIPGateway /value ^| findstr /r "Index IPAddress DefaultIPGateway"') do ( if "%%a"=="Index" ( set "current_index=%%b" ) else if "%%a"=="IPAddress" ( :: 提取IPv4地址(过滤IPv6和引号) for /f "tokens=2 delims={}" %%d in ("%%b") do ( echo %%d | findstr /r "^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$" >nul && set "ip_!current_index!=%%d" ) ) else if "%%a"=="DefaultIPGateway" ( if not "%%b"=="" ( :: 提取网关地址 for /f "tokens=2 delims={}" %%d in ("%%b") do ( set "gw_!current_index!=%%d" set /a gateway_count+=1 set "last_gw=%%d" set "last_index=!current_index!" ) ) ) ) :: 根据网关数量执行对应逻辑 if !gateway_count! gtr 1 ( echo Multiple gateway found :: 遍历输出所有网关 for /f "tokens=2 delims==" %%a in ('set gw_') do ( echo %%a ) ) else if !gateway_count! equ 1 ( set "target_ip=!ip_!last_index!!" echo Default IP Address !target_ip! echo Default Gateway !last_gw! ) else ( echo No default gateway found ) endlocal
脚本逻辑说明
- 启用延迟变量扩展:解决循环内变量赋值与读取的同步问题
- 关联网卡信息:通过
WMIC NICConfig获取启用网卡的Index(网卡ID)、IPAddress、DefaultIPGateway,以Index为键绑定IP和网关 - 过滤有效地址:仅保留IPv4格式的IP和网关,剔除IPv6地址与多余引号
- 分支处理逻辑:
- 网关数量>1:输出所有网关后退出
- 网关数量=1:通过关联的
Index取出对应IP,格式化输出IP与网关 - 网关数量=0:提示无默认网关
场景测试验证
场景一:单网关双网卡
服务器两张网卡仅NIC1配置默认网关:
- NIC1:IP=10.10.0.2,网关=10.10.0.1
- NIC2:IP=172.16.0.2,无网关
脚本输出:
Default IP Address 10.10.0.2 Default Gateway 10.10.0.1
场景二:多网关双网卡
服务器两张网卡均配置默认网关:
- NIC1:IP=10.10.0.2,网关=10.10.0.1
- NIC2:IP=172.16.0.2,网关=172.16.0.1
脚本输出:
Multiple gateway found 10.10.0.1 172.16.0.1
内容的提问来源于stack exchange,提问作者Port folio
相关产品推荐
相关产品推荐

