5 def get_connections(conn_type
='tcp'):
7 returns the connections from /proc/net/tcp indexed by their id (first
10 f
= open('/proc/net/%s' % conn_type
, 'r')
13 #documentation for /proc/net/tcp in
14 #http://lkml.indiana.edu/hypermail/linux/kernel/0409.1/2166.html
16 for line
in f
.readlines():
20 if line
.startswith('s'):
23 parts
= filter(lambda x
: x
, line
.split(' '))
24 index
= parts
[0].strip()[:-1]
25 local_addr
= ip_repr(parts
[1])
26 rem_addr
= ip_repr(parts
[2])
29 connections
[index
] = {
40 returns the dotted-decimal representation of an IP addresse when given
41 the formated used in /proc/net/tcp
43 >>> ip_repr('C8BCED82:1A0B')
44 '130.237.188.200:6667'
48 ip
, port
= ip
.split(':')
52 s
= '.'.join([ repr(int(ip
[x
-2:x
], 16)) for x
in range(8, 0, -2) ])
54 s
+= ':%d' % int(port
, 16)
60 """ returns a dictionary mapping filedescriptors to process information"""
65 socket_regex
= r
'socket:\[(\d+)\]'
69 for pid
in os
.listdir(proc
):
72 d
= os
.path
.join(proc
, pid
)
73 if not os
.path
.isdir(d
):
76 if not re
.match(pid_dir
, pid
):
79 fd_dir
= os
.path
.join(d
, fd
)
80 for x
in os
.listdir(fd_dir
):
81 path
= os
.path
.join(fd_dir
, x
)
83 f_desc
= os
.readlink(path
)
87 # search for socket file-descriptors
88 match
= re
.match(socket_regex
, f_desc
)
90 inode
= int(match
.group(1))
94 cmd_file
= open(os
.path
.join(d
, cmdline
), 'r')
97 m
[inode
] = {'inode': inode
, 'cmd': cmd
, 'pid': int(pid
)}
102 def parse_ip_conntrack():
106 f
= open('/proc/net/ip_conntrack', 'r')
107 for line
in f
.readlines():
111 parts
= filter(lambda x
: x
, line
.split(' '))
115 key
, value
= p
.split('=')
117 # lines often contain src and dest reversed (for returning traffic)
118 # we are just interested in one-way traffic
124 src
= '%s:%s' % (values
['src'], values
['sport'])
125 dst
= '%s:%s' % (values
['dst'], values
['dport'])
126 key
= ip_hash(src
, dst
)
127 connections
[key
] = values
131 def ip_hash(src_ip
, dest_ip
):
132 return '%s-%s' % (src_ip
, dest_ip
)