如何在Python中访问netstat数据?

21

我需要用Python脚本访问/解析Linux机器上特定端口号的所有出站连接。最简单的实现似乎是打开一个netstat的子进程并解析它的stdout。

我想象有人曾经遇到过这个问题,但惊讶地没有在网上找到任何netstat解析器。这只是不够重要,以至于人们不觉得有必要分享吗?

1个回答

38
如果您想控制由特定进程打开的连接,可以使用psutil:
>>> p = psutil.Process(1694)
>>> p.name()
'firefox'
>>> p.connections()
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776), remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
 connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761), remote_address=('72.14.234.100', 80), status='CLOSING'),
 connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759), remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
 connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314), remote_address=('72.14.234.83', 443), status='SYN_SENT')]

在内部,psutil使用/proc。 如果您对系统级别上与特定端口号的连接感兴趣,可以查看psutil如何实现它。

编辑:从psutil 2.1.0开始,您还可以使用net_connections()收集系统范围内的连接

>>> import psutil
>>> psutil.net_connections()
[pconn(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776), raddr=('93.186.135.91', 80), status='ESTABLISHED', pid=1254),
 pconn(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761), raddr=('72.14.234.100', 80), status='CLOSING', pid=2987),
 pconn(fd=-1, family=2, type=1, laddr=('10.0.0.1', 60759), raddr=('72.14.234.104', 80), status='ESTABLISHED', pid=None),
 pconn(fd=-1, family=2, type=1, laddr=('10.0.0.1', 51314), raddr=('72.14.234.83', 443), status='SYN_SENT', pid=None)
 ...]

psutil真的很好用!我最近开始使用它,它真是救命稻草!向作者致敬! - fccoelho
3
更新:新版本2.1.0能够列出系统范围内的套接字连接: http://grodola.blogspot.com/2014/04/reimplementing-netstat-in-cpython.html - Giampaolo Rodolà
我在FreeBSD上使用psutil.net_connections()无法获取NFS连接。如果我的下一个调试确认了这个问题,我会报告这个情况。 Python 3.8.12 (default, Nov 5 2021, 16:04:17) [Clang 10.0.1 (git@github.com:llvm/llvm-project.git llvmorg-10.0.1-0-gef32c611a on freebsd12 >>> import psutil >>> len([(sconn.laddr, sconn.raddr) for sconn in psutil.net_connections(kind="tcp4") if sconn.status == "ESTABLISHED" and sconn.laddr.port == 2049]) 0 - freezed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接