[windows] Kill a Process by Looking up the Port being used by it from a .BAT

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

This question is related to windows batch-file process kill-process

The answer is


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.


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.


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.
)

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


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"):

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


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

x:> net stop http /y


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

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 

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


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


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


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


Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH CanĀ“t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)

Examples related to process

Fork() function in C How to kill a nodejs process in Linux? Xcode process launch failed: Security Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes Linux Script to check if process is running and act on the result CreateProcess error=2, The system cannot find the file specified How to make parent wait for all child processes to finish? How to use [DllImport("")] in C#? Visual Studio "Could not copy" .... during build How to terminate process from Python using pid?

Examples related to kill-process

How to find MySQL process list and to kill those processes? Kill tomcat service running on any port, Windows Closing Excel Application Process in C# after Data Access linux script to kill java process How to kill a process running on particular port in Linux? Kill a Process by Looking up the Port being used by it from a .BAT How to terminate a python subprocess launched with shell=True Kill some processes by .exe file name