Shell – How to get only the PID, without any extra information, of a process running on port 3000

linuxportprocessshell-script

I'm using CentOS 7. I want to get the PID (if one exists) of the process running on port 3000. I would like to get this PID for the purposes of saving it to a variable in a shell script. So far I have

[rails@server proddir]$ sudo ss -lptn 'sport = :3000'
State      Recv-Q Send-Q                           Local Address:Port                                          Peer Address:Port
Cannot open netlink socket: Protocol not supported
LISTEN     0      0                                            *:3000                                                     *:*                   users:(("ruby",pid=4861,fd=7),("ruby",pid=4857,fd=7),("ruby",pid=4855,fd=7),("ruby",pid=4851,fd=7),("ruby",pid=4843,fd=7))

but I can't figure out how to isolate the PID all by itself without all this extra information.

Best Answer

Another possible solution:

lsof -t -i :<port> -s <PROTO>:LISTEN

For example:

# lsof -i :22 -s TCP:LISTEN
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    1392 root    3u  IPv4  19944      0t0  TCP *:ssh (LISTEN)
sshd    1392 root    4u  IPv6  19946      0t0  TCP *:ssh (LISTEN)
# lsof -t -i :22 -s TCP:LISTEN
1392
Related Question