2012-09-19 11:20:16 -07:00
|
|
|
#!/usr/bin/env python
|
2013-05-09 15:39:30 -07:00
|
|
|
|
2013-08-22 23:36:57 -07:00
|
|
|
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
2012-09-19 11:20:16 -07:00
|
|
|
# Use of this source code is governed by a BSD-style license that can be
|
|
|
|
# found in the LICENSE file.
|
|
|
|
|
|
|
|
"""
|
2014-12-23 10:45:15 -08:00
|
|
|
A clone of 'netstat -antp' on Linux.
|
|
|
|
|
|
|
|
$ python examples/netstat.py
|
|
|
|
Proto Local address Remote address Status PID Program name
|
|
|
|
tcp 127.0.0.1:48256 127.0.0.1:45884 ESTABLISHED 13646 chrome
|
|
|
|
tcp 127.0.0.1:47073 127.0.0.1:45884 ESTABLISHED 13646 chrome
|
|
|
|
tcp 127.0.0.1:47072 127.0.0.1:45884 ESTABLISHED 13646 chrome
|
|
|
|
tcp 127.0.0.1:45884 - LISTEN 13651 GoogleTalkPlugi
|
|
|
|
tcp 127.0.0.1:60948 - LISTEN 13651 GoogleTalkPlugi
|
|
|
|
tcp 172.17.42.1:49102 127.0.0.1:19305 CLOSE_WAIT 13651 GoogleTalkPlugi
|
|
|
|
tcp 172.17.42.1:55797 127.0.0.1:443 CLOSE_WAIT 13651 GoogleTalkPlugi
|
|
|
|
...
|
2012-09-19 11:20:16 -07:00
|
|
|
"""
|
|
|
|
|
|
|
|
import socket
|
|
|
|
from socket import AF_INET, SOCK_STREAM, SOCK_DGRAM
|
|
|
|
|
|
|
|
import psutil
|
|
|
|
from psutil._compat import print_
|
|
|
|
|
|
|
|
|
|
|
|
AD = "-"
|
|
|
|
AF_INET6 = getattr(socket, 'AF_INET6', object())
|
2014-12-23 10:45:15 -08:00
|
|
|
proto_map = {
|
|
|
|
(AF_INET, SOCK_STREAM): 'tcp',
|
|
|
|
(AF_INET6, SOCK_STREAM): 'tcp6',
|
|
|
|
(AF_INET, SOCK_DGRAM): 'udp',
|
|
|
|
(AF_INET6, SOCK_DGRAM): 'udp6',
|
|
|
|
}
|
|
|
|
|
2012-09-19 11:20:16 -07:00
|
|
|
|
|
|
|
def main():
|
2014-12-23 10:45:15 -08:00
|
|
|
templ = "%-5s %-30s %-30s %-13s %-6s %s"
|
|
|
|
print_(templ % (
|
|
|
|
"Proto", "Local address", "Remote address", "Status", "PID",
|
|
|
|
"Program name"))
|
|
|
|
proc_names = {}
|
2012-09-19 11:20:16 -07:00
|
|
|
for p in psutil.process_iter():
|
|
|
|
try:
|
2014-12-23 10:45:15 -08:00
|
|
|
proc_names[p.pid] = p.name()
|
|
|
|
except psutil.Error:
|
|
|
|
pass
|
|
|
|
for c in psutil.net_connections(kind='inet'):
|
|
|
|
laddr = "%s:%s" % (c.laddr)
|
|
|
|
raddr = ""
|
|
|
|
if c.raddr:
|
|
|
|
raddr = "%s:%s" % (c.raddr)
|
|
|
|
print_(templ % (
|
|
|
|
proto_map[(c.family, c.type)],
|
|
|
|
laddr,
|
|
|
|
raddr or AD,
|
|
|
|
c.status,
|
|
|
|
c.pid or AD,
|
|
|
|
proc_names.get(c.pid, '?')[:15],
|
|
|
|
))
|
2012-09-19 11:20:16 -07:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|