1 # -*- coding: utf-8 -*-
3 from __future__
import absolute_import
14 class Monitor(object):
18 self
.last_conntrack
= {}
21 self
.include_filter
= []
22 self
.exclude_filter
= []
25 self
.fd_map
.update(proc
.get_fd_map())
26 self
.last_conntrack
= copy
.deepcopy(self
.conntrack
)
27 self
.conntrack
.update(proc
.parse_ip_conntrack())
28 self
.connections
.update(proc
.get_connections())
30 def set_filter(self
, include_filter
, exclude_filter
):
31 self
.include_filter
= [re
.compile(f
) for f
in include_filter
] if include_filter
else []
32 self
.exclude_filter
= [re
.compile(f
) for f
in exclude_filter
] if exclude_filter
else []
35 for con
in self
.connections
.itervalues():
36 inode
= con
.get('inode', None)
37 process
= self
.fd_map
.get(inode
, None)
42 if self
.include_filter
and not any([f
.search(process
['cmd']) for f
in self
.include_filter
]):
45 if self
.exclude_filter
and any([f
.search(process
['cmd']) for f
in self
.exclude_filter
]):
48 key_in
= proc
.ip_hash(con
['remote'], con
['local'])
49 key_out
= proc
.ip_hash(con
['local'], con
['remote'])
50 keys
= {'in': key_in
, 'out': key_out
}
51 new_byte
= {'in': 0, 'out': 0}
53 for direction
in ('in', 'out'):
55 if k
in self
.conntrack
:
56 if key_in
in self
.last_conntrack
:
57 new_byte
[direction
] = int(self
.conntrack
[k
]['bytes']) - int(self
.last_conntrack
[k
]['bytes'])
59 new_byte
[direction
] = int(self
.conntrack
[k
]['bytes'])
61 if process
['cmd'] in self
.tracking
:
62 old_in
, old_out
= self
.tracking
[process
['cmd']]
67 self
.tracking
[process
['cmd']] = (old_in
+ new_byte
['in'], old_out
+ new_byte
['out'])
71 return cmp(a
[1], b
[1])
74 for cmd
, bytes
in sorted(self
.tracking
.iteritems(), cmp=compare
):
76 cmd
= cmd
[:57] + '...'
77 print '%10d / %10d -- %s' % (bytes
[0], bytes
[1], cmd
)