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

编写Batch脚本:关闭指定IP的除最后一条外的所有网络连接

嘿,我来帮你完善这个Batch脚本!你的需求是关闭来自192.168.10.2的所有网络连接但保留最后一条,结合你提到的cports工具,下面是完整的解决方案,我会一步步给你解释清楚:

完整Batch脚本实现
@echo off
setlocal enabledelayedexpansion

:: 定义目标参数,按需修改
set "target_ip=192.168.10.2"
set "local_port=2299"
set "temp_file=%temp%\connections.txt"

:: 把符合条件的连接输出到临时文件
netstat -ano | find "%target_ip%" | find "%local_port%" > "%temp_file%"

:: 统计连接的总条数
set "line_count=0"
for /f %%a in ('type "%temp_file%" ^| find /c /v ""') do set "line_count=%%a"

:: 如果只有1条连接,直接退出,不用关闭任何连接
if %line_count% leq 1 (
    echo 只有1条符合条件的连接,无需执行关闭操作。
    del "%temp_file%"
    exit /b
)

:: 循环处理每一条连接,跳过最后一条
set "current_line=0"
for /f "tokens=2" %%b in ('type "%temp_file%"') do (
    set /a current_line+=1
    :: 拆分远程IP和端口(格式是IP:PORT)
    for /f "tokens=1,2 delims=:" %%c in ("%%b") do (
        set "remote_ip=%%c"
        set "remote_port=%%d"
    )
    :: 只处理最后一行之外的连接
    if !current_line! lss %line_count% (
        echo 正在关闭连接:!remote_ip!:!remote_port!
        C:\cports\cports.exe /close * * !remote_ip! !remote_port!
    )
)

:: 清理临时文件
del "%temp_file%"
echo 操作完成,已保留最后一条目标连接。
endlocal

脚本关键部分说明

  • @echo off:关闭命令行的默认指令输出,让脚本运行过程更简洁。
  • setlocal enabledelayedexpansion:启用延迟变量扩展,这样在循环里能正确更新和读取变量值(比如!current_line!这种写法)。
  • 临时文件temp_file:用来暂存netstat的结果,方便后续统计行数和逐行处理。
  • 行数统计:用find /c /v ""计算文件里的总行数,避免在只有1条连接时做无用操作。
  • 提取远程IP和端口:通过tokens=2拿到netstat输出里的远程地址部分,再用delims=:拆分出IP和端口。
  • 跳过最后一行:通过当前行号和总行数对比,只关闭前line_count-1条连接。

注意事项

  • 确保cports.exe的路径和你实际存放的位置一致(脚本里是C:\cports\cports.exe),如果路径不同记得修改。
  • 脚本需要以管理员权限运行,因为关闭网络连接需要系统权限。
  • 测试阶段可以先把C:\cports\cports.exe /close...这一行改成echo 准备关闭:!remote_ip!:!remote_port!,确认要关闭的连接正确后,再换成实际的关闭指令。

内容的提问来源于stack exchange,提问作者LimpTeaM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:20:38