解析netstat命令以获取端口

时间:2014-11-18 19:58:58

标签: bash parsing

当我运行netstat时,我有以下的outpout:

$ netstat -lnp --inet                                                                 
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State        PID/Program name    
tcp        0      0 0.0.0.0:51413           0.0.0.0:*               LISTEN       6155/transmission-g 
tcp        0      0 127.0.0.1:56424         0.0.0.0:*               LISTEN       450/weechat         
netstat: no support for `AF INET (sctp)' on this system.

我希望只使用bash的端口列表(使用python会更容易)。我有这个:

$ netstat -lnp --inet | cut -d' ' -f45-50 | sed 's/[^0-9]*//g'                
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
netstat: no support for `AF INET (sctp)' on this system.


6155
450

但我无法摆脱文本。有什么帮助吗?

3 个答案:

答案 0 :(得分:3)

使用更加强大:

netstat -lnp --inet | awk -F'LISTEN *|/' '/^(tcp|udp)/{print $2}' file
6155
450

答案 1 :(得分:1)

行:

(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)

发送到stderr而不是stdout,这样你就可以通过将stderr发送到/ dev / null而不是让它在控制台中打印来摆脱它们。

如:

$ netstat -lnp --inet 2>/dev/null| cut -d' ' -f45-50 | sed 's/[^0-9]*//g'
顺便说一句,通过egrep“\ w”的管道将摆脱空行。

$ netstat -lnp --inet 2>/dev/null| cut -d' ' -f45-50 | sed 's/[^0-9]*//g' | egrep "\w"

答案 2 :(得分:0)

尝试:

netstat -lnp --inet | grep -E 'tcp|udp' | cut -d' ' -f45-50 | sed 's/[^0-9]*//g'