I would need a one-line command which, given a port number, returns information on the command which started the process running on that port.
Usually, I get this information by running a sudo netstat
sudo netstat -antpv | grep PORT_NUMBER
which returns the PID_NUMBER
on the 4th column, after the column character (:
), and then I use the PID_NUMBER
as input for a ps aux
ps aux | grep PID_NUMBER
which returns information on the "starting command" on 11th column.
e.g.
# use the port number to get the process id
my_machine:~$ sudo netstat -antpv | grep 30001
tcp 0 0 0.0.0.0:30001 0.0.0.0:* LISTEN 616/python
# use the process id to get info on the command which started the process
my_machine:~$ ps aux | grep 616
my_user 616 0.8 0.5 220112 89596 ? S 01:10 6:59 /usr/bin/python my_program.py --log=INFO
Is it possible to get to this information with a one-line command?
e.g.
my_machine:~$ ps aux | grep get_only_the_number_after_the_column_character_in_the_4th_column_of(sudo netstat -antpv | grep PORT_NUMBER)
/usr/bin/python my_program.py --log=INFO
Update
I am almost doing it.
I get what I want with
my_machine ~$ ps aux | awk '{if ($2 == "616") print $0;}'
my_user 616 0.7 0.5 220112 89596 ? S 01:10 8:11 /usr/bin/python my_program.py --log=INFO
but it does not work when I try to save the PID in a bash variable and then pass it to awk
my_machine:~$ mypid=$(sudo lsof -ti :30001)
my_machine:~$ echo $mypid
616
my_machine:~$ ps aux | awk '{if ($2 == "$mypid") print $0;}'
my_machine:~$
my_machine:~$ ps aux | awk -v mypid="$mypid" '{if ($2 == "mypid") print $0;}'
my_machine:~$
my_machine:~$ ps aux | awk -v mypid="616" '{if ($2 == "mypid") print $0;}'
my_machine:~$
ps aux | awk -v mypid="$mypid" '{if ($2 == mypid) print $0;}'
mypid
and not"mypid"
… don’t quote the variable inside awk or it will not be expanded to its value and will be treated as a literal string instead