michael@0: #!/usr/bin/env python michael@0: michael@0: # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. michael@0: # Use of this source code is governed by a BSD-style license that can be michael@0: # found in the LICENSE file. michael@0: michael@0: """ michael@0: A clone of 'netstat'. michael@0: """ michael@0: michael@0: import socket michael@0: from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM michael@0: michael@0: import psutil michael@0: from psutil._compat import print_ michael@0: michael@0: michael@0: AD = "-" michael@0: AF_INET6 = getattr(socket, 'AF_INET6', object()) michael@0: proto_map = {(AF_INET, SOCK_STREAM) : 'tcp', michael@0: (AF_INET6, SOCK_STREAM) : 'tcp6', michael@0: (AF_INET, SOCK_DGRAM) : 'udp', michael@0: (AF_INET6, SOCK_DGRAM) : 'udp6'} michael@0: michael@0: def main(): michael@0: templ = "%-5s %-22s %-22s %-13s %-6s %s" michael@0: print_(templ % ("Proto", "Local addr", "Remote addr", "Status", "PID", michael@0: "Program name")) michael@0: for p in psutil.process_iter(): michael@0: name = '?' michael@0: try: michael@0: name = p.name michael@0: cons = p.get_connections(kind='inet') michael@0: except psutil.AccessDenied: michael@0: print_(templ % (AD, AD, AD, AD, p.pid, name)) michael@0: except psutil.NoSuchProcess: michael@0: continue michael@0: else: michael@0: for c in cons: michael@0: raddr = "" michael@0: laddr = "%s:%s" % (c.laddr) michael@0: if c.raddr: michael@0: raddr = "%s:%s" % (c.raddr) michael@0: print_(templ % (proto_map[(c.family, c.type)], michael@0: laddr, michael@0: raddr, michael@0: str(c.status), michael@0: p.pid, michael@0: name[:15])) michael@0: michael@0: if __name__ == '__main__': michael@0: main()