131

In Windows what can look for port 8080 and try to kill the process it is using through a .BAT file?

Premraj
  • 56,385
  • 22
  • 212
  • 157
Mike Flynn
  • 21,905
  • 50
  • 167
  • 308
  • I can get you part of the way there... from the command prompt use the command 'netstat -a -n -o' and you will see a list of processes and which ports they are listening on (as well as ip and whether they are connected to another IP or not..) Invaluable. There'll almost certainly be nicer switches to refine the results, but I can't remember them off hand... Hopefully someone can build on this? – Dave Jun 01 '11 at 15:52
  • In linux you can. if you install cygwin you would be able to in bat aswell – Dani Jun 01 '11 at 15:53
  • @Dani, Mike: Cygwin is a huge dependency and not required to solve this problem. If you've already got it, though, use it - linux command line tools are much better. – Merlyn Morgan-Graham Jun 01 '11 at 15:58

14 Answers14

198

Open command prompt and run the following commands

 C:\Users\username>netstat -o -n -a | findstr 0.0:3000
   TCP    0.0.0.0:3000      0.0.0.0:0              LISTENING       3116

C:\Users\username>taskkill /F /PID 3116

, here 3116 is the process ID

ssc-hrep3
  • 10,806
  • 4
  • 35
  • 77
Mohit Singh
  • 5,163
  • 2
  • 19
  • 24
147

Here's a command to get you started:

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO @ECHO TaskKill.exe /PID %%P

When you're confident in your batch file, remove @ECHO.

FOR /F "tokens=4 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %%P

Note that you might need to change this slightly for different OS's. For example, on Windows 7 you might need tokens=5 instead of tokens=4.

How this works

FOR /F ... %variable IN ('command') DO otherCommand %variable...

This lets you execute command, and loop over its output. Each line will be stuffed into %variable, and can be expanded out in otherCommand as many times as you like, wherever you like. %variable in actual use can only have a single-letter name, e.g. %V.

"tokens=4 delims= "

This lets you split up each line by whitespace, and take the 4th chunk in that line, and stuffs it into %variable (in our case, %%P). delims looks empty, but that extra space is actually significant.

netstat -a -n -o

Just run it and find out. According to the command line help, it "Displays all connections and listening ports.", "Displays addresses and port numbers in numerical form.", and "Displays the owning process ID associated with each connection.". I just used these options since someone else suggested it, and it happened to work :)

^|

This takes the output of the first command or program (netstat) and passes it onto a second command program (findstr). If you were using this directly on the command line, instead of inside a command string, you would use | instead of ^|.

findstr :8080

This filters any output that is passed into it, returning only lines that contain :8080.

TaskKill.exe /PID <value>

This kills a running task, using the process ID.

%%P instead of %P

This is required in batch files. If you did this on the command prompt, you would use %P instead.

Merlyn Morgan-Graham
  • 54,918
  • 14
  • 119
  • 174
  • You may need to play with tokens, delims, etc. Check `HELP FOR` on the command line to see a lot of other options that `FOR` will give you, and check `netstat -?`, `findstr /?`, and `TaskKill /?` for even more help. – Merlyn Morgan-Graham Jun 01 '11 at 16:15
  • I will try it out and get back to you. – Mike Flynn Jun 01 '11 at 16:28
  • 6
    FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /F /PID %%P – Mike Flynn Jun 01 '11 at 16:45
  • @Mike: Weird. tokens=4 works for me and 5 doesn't. I am thinking there is system or environment dependent stuff going on here, so be sure to watch out for that. – Merlyn Morgan-Graham Jun 02 '11 at 03:02
  • 10
    This is great. `tokens=4` is Windows XP I think and `tokens=5` Windows 7. Also a good idea to `/F` force the kill. – Strelok Dec 01 '11 at 01:13
  • you helped solving my problem too, thanks for really taking time to describe each of the step. two thumbs up. – Mohsin Javed Cheema Dec 04 '13 at 12:51
  • For windows server 2008, you should set tokens=5 to get the PID – Javatar Oct 05 '14 at 14:26
  • Hi, What is the token to be set for Windows 8 and Windows 8.1? – Dinesh Kumar P Dec 17 '14 at 11:37
  • For Windows 8, tokens=5 – Dinesh Kumar P Dec 17 '14 at 12:09
  • I had to run two commands : FOR /F "tokens=5 delims= " %P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %P /t /f and FOR /F "tokens=5 delims= " %P IN ('netstat -a -n -o ^| findstr :8080') DO TaskKill.exe /PID %P /f The parent were never really killed – Sebastien Dionne Apr 22 '15 at 14:33
  • @MerlynMorgan-Graham when I am trying this command I am getting an error - 'netstat -a -n -o ^| findstr :8080' is not recognized as an internal or external command. Here is what i have tried to troubleshoot: (1) The command netstat -a -n -o ^| findstr :8080 gives the result (2) I have tried replacing single quote ' with a backtick ` , but that doesn't seem to work as well. Could you please tell me what could be the problem. I am running the command on windows 7 cmd.exe – nishantv Nov 03 '15 at 13:37
  • @nishantv: Back tick isn't a Windows thing, so it of course won't work. Try typing `netstat` and try typing `findstr` separately. If either of them don't work you've found your culprit. Either way, I have no idea why you don't have such executables on your box - those, as far as I know, come with Windows. You'd need to google or ask a separate question on super user to solve such a problem. If both of them work, then you either have some sort of strange escaping options configured on your terminal/prompt (enable delayed expansion? I'm not sure here) or you have a typo in your command somewhere – Merlyn Morgan-Graham Nov 03 '15 at 17:45
  • `Cannot run program "FOR": CreateProcess error=2, The system cannot find the file specified` – Hooli Dec 15 '16 at 11:10
  • @Hooli This is not a typical error to have inside a DOS Batch file. You may want to open a separate question. – Merlyn Morgan-Graham Dec 15 '16 at 17:54
  • 1
    @MerlynMorgan-Graham as this is an accepted answer, please consider adding points from https://stackoverflow.com/a/20637662/5243762 this answer as well – IAmSurajBobade Oct 10 '19 at 06:58
  • I had to remove %%P with %P or else was gettin this error: "%%P was unexpected at this time." – saurabh.in Dec 03 '19 at 21:19
  • @saurabh.in I already stated this at the very bottom of my answer, so make sure to read the entire answer before commenting. – Merlyn Morgan-Graham Dec 05 '19 at 23:47
54

To find specific process on command line use below command here 8080 is port used by process

netstat -ano | findstr 8080

to kill process use below command here 21424 is process id

taskkill /pid 21424 /F 
Girdhar Singh Rathore
  • 3,743
  • 4
  • 43
  • 61
21

Using Merlyn's solution caused other applications to be killed like firefox. These processes were using the same port, but not as a listener:

eg:

netstat -a -n -o | findstr :8085
  TCP    0.0.0.0:8085           0.0.0.0:0              LISTENING       6568
  TCP    127.0.0.1:49616        127.0.0.1:8085         TIME_WAIT       0
  TCP    127.0.0.1:49618        127.0.0.1:8085         TIME_WAIT       0

Therefore, can excluded these by adding "LISTENING" to the findstr as follows:

FOR /F "tokens=5 delims= " %%P IN ('netstat -a -n -o ^| findstr :8085.*LISTENING') DO TaskKill.exe /PID %%P
Solubris
  • 3,333
  • 2
  • 17
  • 32
19

To list all the process running on port 8080 do the following.

netstat -ano | find "8080"

TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       10612

TCP    [::]:8080              [::]:0                 LISTENING       10612

Then to kill the process run the following command

taskkill /F /PID 10612

Sardesh Sharma
  • 1,473
  • 10
  • 13
14

Thank you all, just to add that some process wont close unless the /F force switch is also send with TaskKill. Also with /T switch, all secondary threads of the process will be closed.

C:\>FOR /F "tokens=5 delims= " %P IN ('netstat -a -n -o ^|
 findstr :2002') DO TaskKill.exe /PID %P /T /F

For services it will be necessary to get the name of the service and execute:

sc stop ServiceName

xtrm
  • 888
  • 8
  • 21
6

Created a bat file with the below contents, it accepts the input for port number

@ECHO ON
set /p portid=Enter the Port to be killed: 
echo %portid%                                                                              
FOR /F "tokens=5" %%T IN ('netstat -a -n -o ^| findstr %portid% ') DO (
SET /A ProcessId=%%T) &GOTO SkipLine                                                   
:SkipLine                                                                              
echo ProcessId to kill = %ProcessId%
taskkill /f /pid %ProcessId%
PAUSE

Finally click "Enter" to exit.

Sireesh Yarlagadda
  • 10,572
  • 2
  • 65
  • 71
2

Just for completion:

I wanted to kill all processes connected to a specific port but not the process listening

the command (in cmd shell) for the port 9001 is:

FOR /F "tokens=5 delims= " %P IN ('netstat -ano ^| findstr -rc:":9001[ ]*ESTA"') DO TaskKill /F /PID %P

findstr:

  • r is for expressions and c for exact chain to match.
  • [ ]* is for matching spaces

netstat:

  • a -> all
  • n -> don't resolve (faster)
  • o -> pid

It works because netstat prints out the source port then destination port and then ESTABLISHED

Boop
  • 949
  • 12
  • 17
1

If you want to kill the process that's listening on port 8080, you could use PowerShell. Just combine Get-NetTCPConnection cmdlet with Stop-Process.

Tested and should work with PowerShell 5 on Windows 10 or Windows Server 2016. However, I guess that it should also work on older Windows versions that have PowerShell 5 installed.

Here is an example:

PS C:\> Stop-Process -Id (Get-NetTCPConnection -LocalPort 8080).OwningProcess

Confirm
Are you sure you want to perform the Stop-Process operation on the following item: MyTestServer(9408)?
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
bahrep
  • 26,679
  • 12
  • 95
  • 136
0

Similar to Merlyn's response, but this one handles these cases as well:

  • The port number is actually a left substring of another longer port number that you're not looking for. You want to search for an exact port number so that you do not kill a random, innocent process!
  • The script code needs to be able to run more than once and be correct each time, not showing older, incorrect answers.

Here it is:

set serverPid=
for /F "tokens=5 delims= " %%P in ('netstat -a -n -o ^| findstr /E :8080 ') do set serverPid=%%P
if not "%serverPid%" == "" (
  taskkill /PID %serverPid%
) else (
  rem echo Server is not running.
)
Yavin5
  • 648
  • 10
  • 11
0

Steps:

  1. Go to conf folder of your apache tomcat server. In my case,its apache-tomcat-7.0.61\conf as I am using apache-tomcat-7.0.61

  2. Open server.xml and change the port number from 8080 to any other port as your wish. For example:8081,8082,8087 etc

  3. Now go to bin folder and run shutdown.bat

  4. Now restart the server through eclipse.

Now your project will work without any interruption.

shilovk
  • 7,603
  • 15
  • 54
  • 63
0

If anyone is looking for a Powershell Script:

function Search-And-Destroy
{
    param ( [Parameter(Mandatory=$true)][string]$port )
    $lines = netstat -a -o -n | findstr $port
    $ports = @()

    ForEach($line In $lines)
    {
        $res = $($lines -split '\s+')
        $ports += $res[5]
    }

    $ports = $ports | select -uniq

    ForEach($port In $ports)
    {
        echo $(taskkill /F /PID $port)
    }
}

This function basically does what the above functions do, but it is in the Powershell scripting format so you can add it to your Powershell profile. To find your profile's location go to powershell and type echo $profile

watzon
  • 2,179
  • 1
  • 26
  • 56
  • 1
    This is not really a PowerShell script, but a PowerShell-based wrapper around `netstat` tool. – bahrep Nov 02 '16 at 19:27
0

Paste this into command line

FOR /F "tokens=5 delims= " %P IN ('netstat -ano ^| find "LISTENING" ^| find ":8080 "') DO (TASKKILL /PID %P)

If you want to use it in a batch pu %%P instead of %P

Eduard Florinescu
  • 13,721
  • 26
  • 101
  • 164
0

if you by system you cannot end task it. try this command

x:> net stop http /y