Created
May 9, 2016 23:48
-
-
Save SierraKomodo/cff22a7e16f3173498fe32cf8ad1f92c to your computer and use it in GitHub Desktop.
Python 3 script for Ubuntu (And possibly other linux distributions - Tested only for Ubuntu) to display a list of active connections, sorted by number of connections per IP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import subprocess | |
# Takes any domain, ipv4, or ipv6 string and removes a trailing port | |
def ip_remove_port(par_string): | |
loc_count = par_string.count(":") | |
if loc_count in [0, 2, 7]: | |
# ipv4 or domain with no port (domain.com, 111.222.333.444 - 0 colons | |
# ipv6 localhost with no port (::1 - 2 colons) | |
# ipv6 with no port (1111:2222:3333:4444:5555:6666:7777:8888 - 7 colons) | |
return par_string | |
elif loc_count in [1, 3, 8]: | |
# ipv4 or domain with port (domain.com:1234, 111.222.333.444:1234 - 1 colon) | |
# ipv6 localhost with port (::1:1234 - 3 colons) | |
# ipv6 with port (1111:2222:3333:4444:5555:6666:7777:8888:1234 - 8 colors | |
loc_split = par_string.split(":") | |
del loc_split[-1] | |
return ":".join(loc_split) | |
else: | |
return "INVALID ADDRESS " + par_string | |
# Used to sort output_list by the count at the beginning of the string | |
def sort_by_count(par_key): | |
loc_split = par_key.split("\t") | |
loc_count = loc_split[0] | |
return int(loc_count) | |
# Extract response from netstat | |
netstat = subprocess.getstatusoutput( | |
"netstat -ntu | tail -n +3 | awk '{print $5}' | cut -d \".\" -f1,2,3,4 | sort | uniq -c | sort -nr") | |
netstat = netstat[1].split("\n") | |
# Remove port from entries, combine connection counts, store data into a temporary dictionary as {"address": int(count)} | |
addresses = {} | |
for par_entry in netstat: | |
while ' ' in par_entry: | |
par_entry = par_entry.replace(' ', ' ') | |
par_entry = par_entry.strip() | |
entry = par_entry.split(" ") | |
count = entry[0] | |
count = int(count) | |
address = ip_remove_port(entry[1]) | |
if address in addresses: | |
count = addresses[address] + count | |
addresses[address] = count | |
# Sort entries in a list | |
output_list = [] | |
for address, count in addresses.items(): | |
output_list.append(str(count) + "\t" + address) | |
output_list.sort(key=lambda key: sort_by_count(key), reverse=True) | |
# Print the list of entries | |
for output in output_list: | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment