|
1 #!/usr/bin/env python |
|
2 |
|
3 # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. |
|
4 # Use of this source code is governed by a BSD-style license that can be |
|
5 # found in the LICENSE file. |
|
6 |
|
7 """ |
|
8 A clone of 'netstat'. |
|
9 """ |
|
10 |
|
11 import socket |
|
12 from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM |
|
13 |
|
14 import psutil |
|
15 from psutil._compat import print_ |
|
16 |
|
17 |
|
18 AD = "-" |
|
19 AF_INET6 = getattr(socket, 'AF_INET6', object()) |
|
20 proto_map = {(AF_INET, SOCK_STREAM) : 'tcp', |
|
21 (AF_INET6, SOCK_STREAM) : 'tcp6', |
|
22 (AF_INET, SOCK_DGRAM) : 'udp', |
|
23 (AF_INET6, SOCK_DGRAM) : 'udp6'} |
|
24 |
|
25 def main(): |
|
26 templ = "%-5s %-22s %-22s %-13s %-6s %s" |
|
27 print_(templ % ("Proto", "Local addr", "Remote addr", "Status", "PID", |
|
28 "Program name")) |
|
29 for p in psutil.process_iter(): |
|
30 name = '?' |
|
31 try: |
|
32 name = p.name |
|
33 cons = p.get_connections(kind='inet') |
|
34 except psutil.AccessDenied: |
|
35 print_(templ % (AD, AD, AD, AD, p.pid, name)) |
|
36 except psutil.NoSuchProcess: |
|
37 continue |
|
38 else: |
|
39 for c in cons: |
|
40 raddr = "" |
|
41 laddr = "%s:%s" % (c.laddr) |
|
42 if c.raddr: |
|
43 raddr = "%s:%s" % (c.raddr) |
|
44 print_(templ % (proto_map[(c.family, c.type)], |
|
45 laddr, |
|
46 raddr, |
|
47 str(c.status), |
|
48 p.pid, |
|
49 name[:15])) |
|
50 |
|
51 if __name__ == '__main__': |
|
52 main() |