21

I'm trying to need to access/parse all outgoing connections on a particular port number on a Linux machine using a Python script. The simplest implementation seems to be to open a subprocess for netstat and parse its stdout.

I imagine someone somewhere has had this problem before, and am surprised not to find any netstat parsers online. Is this just not big enough of a problem for people to feel the need to share?

Andrey Fedorov
  • 9,148
  • 20
  • 67
  • 99

1 Answers1

38

If you want to control the connection opened by a certain process you can use 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')]

Internally psutil uses /proc. If you're interested in connections to/from a particular port number at system level you might take a look at how psutil implements it.

Edit: starting from psutil 2.1.0 you can also gather system-wide connections using 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)
 ...]
guettli
  • 25,042
  • 81
  • 346
  • 663
Giampaolo Rodolà
  • 12,488
  • 6
  • 68
  • 60
  • psutil is really nice! I have started to use it recently and its a life saver! Kudos to the authors! – fccoelho May 08 '12 at 12:15
  • 3
    Update: new 2.1.0 version is able to list system-wide socket connections: http://grodola.blogspot.com/2014/04/reimplementing-netstat-in-cpython.html – Giampaolo Rodolà Apr 08 '14 at 22:55
  • I cannot get NFS connections using `psutil.net_connections()` on FreeBSD. I will report this case if my next debugs confirm that. ```python 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 Dec 15 '22 at 10:24