Tuesday, April 8, 2008

Map networt port to PID in Python for Linux.

Cheap and dirty. It's not suppose to be perfect, just an idea. I hate to run external programs (i.e. netstat -lpn) from Python. The batteries included!!! The root privileges and procfs is necessary to run, sorry there is no miracles in this world.


1 #!/usr/bin/python2.4
2 #
3 """Map port to PID.
4
5 """
6
7 __author__ = 'amishchenko(at)gmail.com'
8
9 import glob
10 import os
11
12 _NET_STAT = ['/proc/net/tcp','/proc/net/udp']
13
14 inode2port = {}
15 port2pid = {}
16
17 for file in _NET_STAT:
18 try:
19 for line in open(file).readlines()[1:]:
20 d = line.split()
21 inode2port[long(d[9])] = int(d[1].split(':')[1], 16)
22 except:
23 pass
24
25 fdlist = glob.glob('/proc/*/fd/*')
26 for fd in fdlist:
27 try:
28 pid = int(fd.split('/')[2])
29 inode = long(os.stat(fd)[1])
30 if inode in inode2port:
31 port2pid[inode2port[inode]] = pid
32 except:
33 pass
34
35 print port2pid

No comments: