netstat -an | grep LISTEN tcp 0 0 :::80 :::* LISTEN tcp 0 0 :::22 :::* LISTENActually you get a lot of other stuff too, but the above two lines show you that some process is serving on ports 80 and 22 (httpd and sshd).
How can we learn more?
[root@cholla linux]# lsof -i :22 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME sshd 1753 root 3u IPv4 6197 0t0 TCP *:ssh (LISTEN) sshd 1753 root 4u IPv6 6199 0t0 TCP *:ssh (LISTEN)Again here we get other stuff also, but the above shows you that sshd is running as PID 1753. Unlike netstat, which can be run by any old user, this command will quietly return nothing if run as a regular user, you must be root when you run this command to get anything useful.
The netstat and lsof commands both have zillions of options and lots of other uses. The above lsof command defaults to looking for TCP sockets, if you had wanted UDP sockets, you might try:
lsof -i UDP:22
#!/bin/sh # Map LISTENing TCP ports to their PIDs using lsof LSOF=/usr/sbin/lsof printf "%-6s %-10s %-6s %-8s\n" "Port" "Command" "PID" "User" printf "%-6s %-10s %-6s %-8s\n" "----" "-------" "---" "----" for PORT in `netstat -an | grep LISTEN | \ perl -ne 'print "$1\n" if /.*\.(\d+)\s+\*\.\*/' | sort -n | uniq` do $LSOF -i :${PORT} 2>/dev/null | grep LISTEN | tail -1 | while read line do set $line COMMAND=$1 PID=$2 LSOF_USER=$3 printf "%-6d %-10s %-6d %-8s\n" "$PORT" "$COMMAND" "$PID" "$LSOF_USER" done done
Have any comments? Questions? Drop me a line!
Adventures in Computing / [email protected]