usr bin python encoding utf-8 from subprocess import Popen PIPE from t

 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
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from subprocess import Popen, PIPE
from time import sleep
import GeoIP
def pidof(command):
p = Popen(['pidof', command], stdout=PIPE)
line = p.communicate()[0]
return [int(pid) for pid in line.split()]
if __name__ == '__main__':
connections = set()
geoip = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
try:
while True:
pids = pidof('skype')
if pids:
cmd = ['lsof']
for pid in pids:
cmd.extend(['-p', '%i' % pid])
cmd.extend(['-a', '-i', '-n', '+r', '1'])
p = Popen(cmd, stdout=PIPE)
for line in iter(p.stdout.readline, ''):
if line.startswith('COMMAND') or line.startswith('======='):
continue
line = line.rstrip()
conn = line.split(None, 6)[6]
if not conn in connections:
try:
dst = conn.split('->', 1)[1].split(':', 1)[0]
country = "%s (%s)" % (
geoip.country_code_by_addr(dst),
geoip.country_name_by_addr(dst))
except IndexError:
country = ""
print conn, country
connections.add(conn)
p.wait()
sleep(1.0)
except:
print "\nSummary:"
for conn in connections:
print conn
print ""
raise