我正在尝试使用 Python 脚本访问/解析 Linux 机器上特定端口号上的所有传出连接。最简单的实现似乎是为 netstat 打开一个子进程并解析其标准输出。
我想以前有人在某个地方遇到过这个问题,并且很惊讶没有在网上找到任何 netstat 解析器。这只是一个大到让人们觉得有必要分享的问题吗?
如果要控制某个进程打开的连接,可以使用 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)
...]