First draft of a script that will parse the output of netstat to simulate the
[vsys.git] / factory / portsummary
1 #!/usr/bin/python
2
3 import os
4 import sys
5
6 ns = os.popen("vcontext --xid 1 --migrate -- netstat -apnlut", 'r')
7 port_summary = {}
8 for line in ns:
9         try:
10                 ns_fields = line.split()
11                 if ns_fields[0] == "tcp" or ns_fields[0] == "udp":
12                         (src_ip, src_port) = ns_fields[3].split(':')
13                         if src_ip is not "0.0.0.0" and src_port in port_summary:
14                                 # skip INADDR_ANY addresses and ports we've already seen.
15                                 continue
16                         (dst_ip, dst_port) = ns_fields[4].split(':')
17                         conn_state = ns_fields[5]
18                         if ns_fields[0] == "tcp":
19                                 proc_field = ns_fields[6]
20                         else:
21                                 if conn_state == "ESTABLISHED":
22                                         proc_field = ns_fields[6]
23                                 else:
24                                         proc_field = ns_fields[5]
25
26                         if proc_field != "-":
27                                 (pid,procname)= proc_field.split('/')
28                         else:
29                                 # TODO: ephemeral sockets in TIME_WAIT
30                                 # TODO: XXX: THIS IS FALSE.  Need an actual way of finding the
31                                 #                       XID associated with a socket in TIME_WAIT
32                                 (pid,procname)= ("1","")
33
34                         if ( ns_fields[0] == "tcp" and src_ip == "0.0.0.0" and conn_state == "LISTEN" ) or \
35                            ( ns_fields[0] == "udp" and src_ip == "0.0.0.0" ):
36                                 type='C'
37                         elif src_ip == "127.0.0.1":
38                                 type='l'
39                         elif src_ip != "0.0.0.0" and src_ip != "127.0.0.1":
40                                 type='c'
41                         else:
42                                 type='?'
43
44                         xid_stream = os.popen("vserver-info %s XID" % pid)
45                         xid = xid_stream.read()
46
47                         port_summary[src_port] = {'prot' : ns_fields[0], 'port' : src_port, 'slice' : xid[:-1], 'type': type}
48         except:
49                 import traceback; traceback.print_exc()
50                 print line
51
52 ports = port_summary.keys()
53 ports.sort()
54 for port in ports:
55         print "%(prot)4s\t%(port)6s\t%(slice)5s\t%(type)s" % port_summary[port]
56