python/psutil/examples/netstat.py

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rwxr-xr-x

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

     1 #!/usr/bin/env python
     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.
     7 """
     8 A clone of 'netstat'.
     9 """
    11 import socket
    12 from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
    14 import psutil
    15 from psutil._compat import print_
    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'}
    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]))
    51 if __name__ == '__main__':
    52     main()

mercurial