Tue 12 Jun 2007
Find Process ID by Port Number
Posted by admin under bash , linux , process , programming , shell[4] Comments
In linux you can use some shell scripting to find a running server process by port number. I came up with this example using awk (watch out for backticks `):
ps aux | grep --regexp="`netstat -nlept | awk '/:8079 / || /:8080 / {split($9,t,"/"); print t[1]}'`"
where you suspect the server ports to be 8079 or 8080. Problem here – if nothing is found then all processes will be listed. For automation you might prefer:
ps u --no-heading -p `netstat -nlept | awk '/[:]8080 / {split($9,t,"/"); print t[1]}'` 2>/dev/null
… last part will redirect error/help message in case there is no process.
Or put it into a function:
myserver_info() { ps aux | grep --regexp="`netstat -nlept | awk '/8079/ || /8080/ {split($9,t,"/"); print t[1]}'`"; }
this definition you can add to your .bashrc .
Usage:
myserver_info
or pass it within a pipe to “kill <pid>” command for example.
You can extend it further by passing the ports as function arguments … (see Advanced Bash-Scripting Guide: Functions)
Do you know a shorter way to do the same?
August 9th, 2007 at 2:22 pm
Just in case someone needs the same
for the windows shell (a.k.a cmd.exe),
here’s a small batch that finds the process using a specified port.
Call with port number as the parameter, e.g. findport 1433
@echo off
for /F “usebackq tokens=5″ %%f in (`netstat -b -n ^| find “:%1″`) do call :process %%f
goto :eof
:process
tasklist /FI “PID eq %1″ /NH
August 9th, 2007 at 2:23 pm
Regarding my previous comment: please check line breaks,
the ” :process %%f ” is part of line 3,
thanks.
August 11th, 2007 at 1:14 am
you can also try fuser
May 9th, 2008 at 9:31 pm
The above command works well in XP, 2003. Doesnt work in Windows 2000.