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"""
8A clone of 'netstat -antp' on Linux.
9
10$ python examples/netstat.py
11Proto Local address      Remote address   Status        PID    Program name
12tcp   127.0.0.1:48256    127.0.0.1:45884  ESTABLISHED   13646  chrome
13tcp   127.0.0.1:47073    127.0.0.1:45884  ESTABLISHED   13646  chrome
14tcp   127.0.0.1:47072    127.0.0.1:45884  ESTABLISHED   13646  chrome
15tcp   127.0.0.1:45884    -                LISTEN        13651  GoogleTalkPlugi
16tcp   127.0.0.1:60948    -                LISTEN        13651  GoogleTalkPlugi
17tcp   172.17.42.1:49102  127.0.0.1:19305  CLOSE_WAIT    13651  GoogleTalkPlugi
18tcp   172.17.42.1:55797  127.0.0.1:443    CLOSE_WAIT    13651  GoogleTalkPlugi
19...
20"""
21
22import socket
23from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
24
25import psutil
26
27
28AD = "-"
29AF_INET6 = getattr(socket, 'AF_INET6', object())
30proto_map = {
31    (AF_INET, SOCK_STREAM): 'tcp',
32    (AF_INET6, SOCK_STREAM): 'tcp6',
33    (AF_INET, SOCK_DGRAM): 'udp',
34    (AF_INET6, SOCK_DGRAM): 'udp6',
35}
36
37
38def main():
39    templ = "%-5s %-30s %-30s %-13s %-6s %s"
40    print(templ % (
41        "Proto", "Local address", "Remote address", "Status", "PID",
42        "Program name"))
43    proc_names = {}
44    for p in psutil.process_iter():
45        try:
46            proc_names[p.pid] = p.name()
47        except psutil.Error:
48            pass
49    for c in psutil.net_connections(kind='inet'):
50        laddr = "%s:%s" % (c.laddr)
51        raddr = ""
52        if c.raddr:
53            raddr = "%s:%s" % (c.raddr)
54        print(templ % (
55            proto_map[(c.family, c.type)],
56            laddr,
57            raddr or AD,
58            c.status,
59            c.pid or AD,
60            proc_names.get(c.pid, '?')[:15],
61        ))
62
63if __name__ == '__main__':
64    main()
65