You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多网卡系统下识别默认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

脚本逻辑说明

  1. 启用延迟变量扩展:解决循环内变量赋值与读取的同步问题
  2. 关联网卡信息:通过WMIC NICConfig获取启用网卡的Index(网卡ID)、IPAddress、DefaultIPGateway,以Index为键绑定IP和网关
  3. 过滤有效地址:仅保留IPv4格式的IP和网关,剔除IPv6地址与多余引号
  4. 分支处理逻辑:
    • 网关数量>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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 00:48:27