bat脚本 强制杀死占用端口的进程

对bat脚本只会点点皮毛,勉强在其他脚本的基础上写了这个脚本,用于强制杀死占用端口的进程,因为else( 导致的错误差点吐血
语法那么严格好歹说明下啊.

脚本有几个地方说明下
1. for循环的数据来源 使用端口查找命令. 查找端口find ":%port% " 在匹配字符串前面加上: 端口后面加上空格,保证查询结果正确
2. 查找结果按顺序 %%b是本机被占用的端口 %%c是占用者,防止前面查询出的是占用者这里进行了二次判断 @echo %%b|findstr /c":%port%" >nul
3.再排除掉一些链接等待关闭时候会显示pid为0的情况 if not “%%d” == "0"
4.新修改了脚本之前会判定到远程端口去,第2条说的二次判断是无效的,新的二次判断方法是切割%%b 拿到%%b 下的端口 拿端口去和输入的端口比较.

@echo off
rem open var delay
setlocal enabledelayedexpansion
rem recev var 
set port=%1%
if "%port%" == "" (
    echo Please enter port
    goto end
)
echo ---------------start find who is using port %port%----------------------- 
rem Add colon before port and space after port to ensure no mistake
for /f "tokens=1-5" %%a in ('netstat -ano ^| find ":%port% "') do (
    rem a is protocol,b is local ip:port, c is remote ip:port,d is state or pid,e is pid or null 
    echo %%a %%b %%c %%d %%e
    rem Cut the %%b with the : to get the port
    for /f "delims=:, tokens=1-2" %%j in ("%%b") do (set destport=%%k)
    rem Delay variable in for loop must use! Symbol instead of% symbol
    echo The port found here is !destport!. What we need is %port%  
    rem If %%b cuts the same port as the target port
    if "!destport!" equ "%port%" (
        if "%%e" == "" (
            rem sometimes e is empty pid in d
            if not "%%d" == "0" (
                echo get d col pid %%d
                set pid=%%d
            )
        ) else (
            if not "%%e" == "0" (
               echo get e col pid %%e
               set pid=%%e
            )
        )
    ) else (
        echo this row local not use port %port% 
    )
)
echo ---------------end find who is using port %port%----------------------- 
if "%pid%"=="" (
 echo Port %port% is not in use 
) else (
 echo used port %port% the process %pid%
 taskkill /f /pid %pid%
)


:end
echo ---------------end----------------------------------------------------
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值