Tuesday, 20 November 2018

macOS - Finding and nuking processes by listening port

When I'm trying to find/kill a process on a Linux box, I tend to use my muscle memory of: -

netstat -aonp|grep 9043

(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp6       0      0 :::9043                 :::*                    LISTEN      52647/java           off (0.00/0/0)


Note that, even though I'm not running as root, I can still see the process ID ( PID ).

However, on macOS Mojave, this is subtly different: -

netstat -an|grep 8080

tcp6       0      0  ::1.8080               ::1.56360              FIN_WAIT_2 
tcp6       0      0  ::1.8080               ::1.56359              FIN_WAIT_2 
tcp6       0      0  ::1.56360              ::1.8080               CLOSE_WAIT 
tcp6       0      0  ::1.56359              ::1.8080               CLOSE_WAIT 
tcp46      0      0  *.8080                 *.*                    LISTEN     

which doesn't show the PID.

Thankfully, this had the answer: -


On macOS High Sierra, use this command:

lsof -nP -i4TCP:$PORT | grep LISTEN

So, for me, the command translates as: -

lsof -nP -i4tcp:8080 | grep LISTEN

java    60700 davidhay   65u  IPv6 0x628378e95c8f30d1      0t0  TCP *:8080 (LISTEN)

which then allowed me to kill the process ( a JVM "owned" by Apache Tomcat ) : -

kill -9 60700

meaning that : -

netstat -an|grep 8080

and: -

lsof -nP -i4tcp:8080 | grep LISTEN

now return nothing :-)

No comments: