Skip to content

Instantly share code, notes, and snippets.

@DaCurse
Last active July 3, 2018 19:02
Show Gist options
  • Save DaCurse/f9065023ba1bd2aed25eb765173feb7b to your computer and use it in GitHub Desktop.
Save DaCurse/f9065023ba1bd2aed25eb765173feb7b to your computer and use it in GitHub Desktop.
Python script that parses netstat -nb command in windows, getting current connnections & from which programs
from ctypes import windll
from sys import executable
from os import popen
def is_admin():
try:
return windll.shell32.IsUserAnAdmin()
except:
return False
def clean_split(to_split, delim):
return list(filter(''.__ne__, to_split.split(delim)))
def process_lines(lines):
current_programs = []
for line in lines:
next_index = lines.index(line) + 1
# Getting the parts of the current line
line_arr = clean_split(line.strip(), ' ')
line_data = {
'protocol': '',
'local_ip': '',
'local_port': 0,
'remote_ip': '',
'remote_port': 0,
'program': 'Unknown'
}
# Checking if its a connection line
if len(line_arr) == 4:
# Collecting data into dict
line_arr.pop()
local_addr = line_arr[1].split(':')
remote_addr = line_arr[2].split(':')
line_data['protocol'] = line_arr[0]
line_data['local_ip'], line_data['local_port'] = local_addr[0], int(local_addr[1])
line_data['remote_ip'], line_data['remote_port'] = remote_addr[0], int(remote_addr[1])
# Checking if the next line has the program name, if so getting it
if next_index < len(lines) and len(clean_split(lines[next_index], ' ')) == 1:
if lines[next_index].strip().startswith('['):
line_data['program'] = lines[next_index].strip()[1:-1]
elif next_index + 1 < len(lines) and lines[next_index + 1].strip().startswith('['):
line_data['program'] = lines[next_index + 1].strip()[1:-1]
# Adding it to the array of connections
current_programs.append(line_data)
else:
continue
return current_programs
if not is_admin():
windll.shell32.ShellExecuteW(None, "runas", executable, __file__, None, 1)
out = popen('netstat -nb').read()
lines = out.strip().splitlines()[3:]
data = process_lines(lines)
print(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment