4

I'm looking to gather only the PID value outputted when you run this netstat command:

netstat -a -o -n -p tcp | findstr -i "CLOSE_WAIT"

My intention is to use the PIDs and create a script that will run taskkill /PID pidfoundhere to remove any sockets with CLOSE_WAIT state.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user3459799
  • 345
  • 6
  • 16

1 Answers1

5
@echo off
    for /f "tokens=5" %%a in ('
        netstat -noa -p tcp ^| find /i "CLOSE_WAIT"
    ') do if not "%%a"=="0" echo taskkill /pid %%a

Use for command to split the line using the spaces as delimiters, get the 5th token in the line and if there is PID, kill the process

The taskkill commands are only echoed to console. If the output is correct, remove the echo command

MC ND
  • 69,615
  • 8
  • 84
  • 126
  • I modified it a little bit to be a little more specific but I have another question. Any clue how to execute this command in Java? I'm having some issues running it as: String command = "@echo off for /f \"tokens=5\" %%a in ('netstat -noa -p tcp ^| find /i \"CLOSE_WAIT\" ^| find /i \""+ip+":443\" ') do if not \"%%a\"==\"0\" echo taskkill /pid %%a"; Process runCommand = Runtime.getRuntime().exec(command); Currently getting an error: Cannot run program "@echo": CreateProcess error=2, The system cannot find the file specified – user3459799 Sep 25 '14 at 16:46
  • Also tried it as passing a String[] to the exec() method and getting a cannot run program error. – user3459799 Sep 25 '14 at 16:50
  • @user3459799, sorry, java is not my area, but the code, as is, is intended to be executed inside a batch file. If you want to run it from java, and not use a batch file, you will need to use `cmd /c "the command"` as `cmd` is who knows how to execute it, remove the `@echo off`, place all the command in one line and replace all the `%%a` (the percent is escaped inside batch files) with `%a` for command line version. – MC ND Sep 25 '14 at 16:52