Skip to content

Instantly share code, notes, and snippets.

@cato-
Created March 26, 2012 13:31
Show Gist options
  • Save cato-/2205066 to your computer and use it in GitHub Desktop.
Save cato-/2205066 to your computer and use it in GitHub Desktop.
Visualize netstat -l output as tables
#!/usr/bin/env python
# Reads output of "netstat -tulpenW" out of "netstat.txt" and writes
# tables with ips as columns and ports as rows to "netstat_tcp.csv",
# "netstat_udp.csv", "netstat_tcp6.csv" and "netstat_udp6.csv"
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <github -at- robertweidlich -dot- de> wrote this file. As long as you retain
# this notice you can do whatever you want with this stuff. If we meet some
# day, and you think this stuff is worth it, you can buy me a beer in return
# ----------------------------------------------------------------------------
import csv
f = open("netstat.txt")
lines = f.readlines()
data = []
for line in lines:
sline = line.strip().split(None, 8)
if "tcp" in sline[0]:
data.append((sline[0], sline[3], sline[8]))
elif "udp" in sline[0]:
data.append((sline[0], sline[3], sline[7]))
def filter_ports_ip(tag):
ports = []
ips = []
for d in data:
if d[0] == tag:
ip, port = d[1].rsplit(':',1)
ports.append(int(port))
ips.append(ip)
ips = list(set(ips))
ips.sort()
ports = list(set(ports))
ports.sort()
return (ips, ports)
def find_entry(data, ip, port):
tag = "%s:%s" % (ip, port)
for d in data:
if d[1] == tag:
return d[2]
return ""
def write_csv(file_name, tag, ips, ports):
f = open(file_name, "w")
header = ['Port',] + ips
writer = csv.DictWriter(f, header)
writer.writerow(dict([(i,i) for i in header]))
for port in ports:
line = {'Port': port}
for ip in ips:
line[ip] = find_entry(data, ip, port)
writer.writerow(line)
def normalize_data(data):
ip6 = []
ip4 = []
for l in data:
ip = l[1].rsplit(":" ,1)[0]
if "6" in l[0]:
if ip != "::":
ip6.append(ip)
else:
if ip != "0.0.0.0":
ip4.append(ip)
ip6 = list(set(ip6))
ip4 = list(set(ip4))
print data
new_data=[]
for line in data:
print "norm", line
ip, port = line[1].rsplit(":", 1)
if "6" in line[0] and "::" == ip:
for i in ip6:
new_data.append((line[0], "%s:%s" % (i, port), line[2]))
elif "0.0.0.0" == ip:
for i in ip4:
new_data.append((line[0], "%s:%s" % (i, port), line[2]))
else:
new_data.append(line)
return new_data
ndata = normalize_data(data)
data = ndata
for proto in ("tcp", "udp", "tcp6", "udp6"):
ips, ports = filter_ports_ip(proto)
write_csv("netstat_%s.csv" % proto, proto, ips, ports)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment