2

I am using the following script to kill a process in CLOSE_WAIT state that listens to a certain ip and to a certain port.

FOR /F "tokens=5 delims= " %%I IN (
    'netstat -ano ^| find "127.0.0.1:5900" ^| find "CLOSE_WAIT"'
) DO (
    taskkill /PID %%I
)

The script does it's job but I am looking for a small modification.

I would like the process to be killed only if there are more than 10 connections into CLOSE_WAIT state. If let's say there are only 3 connections in CLOSE_WAIT then the process shouldn't be killed.

Chris
  • 107

1 Answers1

0

Here is my attempt.

I used a few tricks from this post: https://stackoverflow.com/questions/2913231/how-do-i-increment-a-dos-variable-in-a-for-f-loop

echo off

set /a c=1
setlocal ENABLEDELAYEDEXPANSION

FOR /F "tokens=5 delims= " %%I IN (
    'netstat -ano ^| find "127.0.0.1:5900" ^| find "CLOSE_WAIT"'
) DO (
    set /a c=c+1
    set /a last=%%I
)
if %c% geq 10 (
   taskkill /PID !last!
)

endlocal

Basically, during the cycle I just increment a variable. In the end, if the count is greater than 10, I kill the task.

Limitation: this only counts lines returned by the netstat and finds, and uses the last PID counted for the taskkill. It assumes all the lines are from the same PID, but this is only true in some cases (like your case, where you search for address and port).

pgr
  • 429