How to parse netstat command in order to get proce

2019-02-03 01:03发布

I'm trying to determine what application is using certain port and get netstat -tlnp | grep <port> for Linux.

This command return the following output:

(Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.)  
tcp  0  0 0.0.0.0:<port>  0.0.0.0:*  LISTEN  3591/java

I need to get in result only name of the process and PID, i.e java 3591.

What is best way to do it?

Thank you.

7条回答
甜甜的少女心
2楼-- · 2019-02-03 01:40

... | awk '{print $7;}'| sed 's/\// /g'

查看更多
够拽才男人
3楼-- · 2019-02-03 01:41

(Detracting slightly from your original question), to find out which process listens to a certain port number, I usually use the lsof command. For example:

lsof -i tcp:80

To show only the process name and PID, parse the output using:

lsof | tail -n +2 | awk '{print $1 " " $2}'

The tail command skips the output header while awk prints out the required columns.

Why lsof

Trying to grep the output of netstat can be messy as you'll need to make sure you're matching against the correct column. A robust solution can be rather long winded and difficult (for me anyway) to produce on-demand.

lsof saves you the trouble of matching the right ports, and has lots of other uses too, e.g. the inverse of what we're doing now (find out which ports are being used by a process), or determining which process is using a file / mount point (or the inverse). See lsof manpage for more examples.

查看更多
唯我独甜
4楼-- · 2019-02-03 01:46

awk + sed:

awk '{print $7}' | sed "s/\// /g"
查看更多
冷血范
5楼-- · 2019-02-03 01:57

Try netstat -p

-p, --program Show the PID and name of the program to which each socket belongs.

查看更多
神经病院院长
6楼-- · 2019-02-03 01:59
netstat -tlnp 2>/dev/null | awk '/\.[0-9]:X/ {print $7}' | sed 's/\//\s/g'

where X in the awk bit is the port you're looking at.

查看更多
Ridiculous、
7楼-- · 2019-02-03 02:01

Also you can get rid of that "you have to be root" message by redirecting stderr to /dev/null

netstat -tlnp 2>/dev/null | grep ...
查看更多
登录 后发表回答