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