python, listen port, inode, pid, process name
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
#!/usr/local/bin/python import glob import os import commands net = commands.getoutput( "grep ' 0A ' /proc/net/tcp" ) if os.path.exists( '/proc/net/tcp6' ): net6 = commands.getoutput( "grep ' 0A ' /proc/net/tcp6" ) if net6: net + = '\n' net + = net6 inode2port = dict () # {inode:port} lines = net.splitlines() for line in lines: buf = line.split() inode2port[ long (buf[ 9 ])] = int (buf[ 1 ].split( ":" )[ 1 ], 16 ) port2pname = {} # {port:process name} fdlist = glob.glob( '/proc/*/fd/*' ) for fd in fdlist: try : pid = fd.split( '/' )[ 2 ] inode = long (os.stat(fd)[ 1 ]) if inode in inode2port: pname = commands.getoutput( 'cat /proc/%s/status | grep Name' % pid).split()[ 1 ] port2pname[inode2port[inode]] = pname except : pass print port2pname |