-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsocket-mon.py
69 lines (59 loc) · 1.8 KB
/
socket-mon.py
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import collections
from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
import psutil
AD = '-'
AF_INET6 = getattr(socket, 'AF_INET6', object())
proto_map = {
(AF_INET, SOCK_STREAM): 'tcp',
(AF_INET6, SOCK_STREAM): 'tcp6',
(AF_INET, SOCK_DGRAM): 'udp',
(AF_INET6, SOCK_DGRAM): 'udp6',
}
def main():
pid_num_of_connections_map = {}
pid_connections_map = {}
templ = '%-5s %-30s %-30s %-13s %-6s %s'
print templ % (
'Proto',
'Local address',
'Remote address',
'Status',
'PID',
'Program name',
)
proc_names = {}
for p in psutil.process_iter():
try:
proc_names[p.pid] = p.name()
except psutil.Error:
pass
for c in psutil.net_connections(kind='inet'):
print c
if pid_num_of_connections_map.get(c.pid):
connections = pid_num_of_connections_map[c.pid] + 1
pid_num_of_connections_map[c.pid] = connections
else:
pid_num_of_connections_map[c.pid] = 1
pid_connections_map.setdefault(c.pid, []).append(c)
pid_connections_descending = \
collections.OrderedDict(sorted(pid_num_of_connections_map.items(),
key=lambda (k, v): v, reverse=True))
for pid in pid_connections_descending:
for c in pid_connections_map[pid]:
laddr = '%s:%s' % c.laddr
raddr = ''
if c.raddr:
raddr = '%s:%s' % c.raddr
print templ % (
proto_map[(c.family, c.type)],
laddr,
raddr or AD,
c.status,
c.pid or AD,
proc_names.get(c.pid, '?')[:15],
)
if __name__ == '__main__':
main()