Skip to content

Instantly share code, notes, and snippets.

@eiginn
Created April 27, 2016 17:11
Show Gist options
  • Save eiginn/66abf9416e91bf0e8750ebee13f518f4 to your computer and use it in GitHub Desktop.
Save eiginn/66abf9416e91bf0e8750ebee13f518f4 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
#GistID:
PROC_TCP = "/proc/net/tcp"
STATE = {
'01': 'ESTABLISHED',
'02': 'SYN_SENT',
'03': 'SYN_RECV',
'04': 'FIN_WAIT1',
'05': 'FIN_WAIT2',
'06': 'TIME_WAIT',
'07': 'CLOSE',
'08': 'CLOSE_WAIT',
'09': 'LAST_ACK',
'0A': 'LISTEN',
'0B': 'CLOSING'
}
def _load():
with open(PROC_TCP, 'r') as f:
content = f.readlines()
content.pop(0)
return content
def _hex2dec(s):
return str(int(s, 16))
def _ip(s):
ip = [(_hex2dec(s[6:8])), (_hex2dec(s[4:6])),
(_hex2dec(s[2:4])), (_hex2dec(s[0:2]))]
return '.'.join(ip)
def _remove_empty(array):
return [x for x in array if x != '']
def _convert_ip_port(array):
host, port = array.split(':')
return _ip(host), _hex2dec(port)
def netstat():
content = _load()
result = []
for line in content:
line_array = _remove_empty(line.split(' ')) # Split lines and remove empty spaces.
retran = int(line_array[6], 16)
if retran < 1:
continue
l_host, l_port = _convert_ip_port(line_array[1]) # Convert ipaddress and port from hex to decimal.
r_host, r_port = _convert_ip_port(line_array[2])
tcp_id = line_array[0]
if line_array[3] == "03":
continue
else:
state = STATE[line_array[3]]
nline = [tcp_id, l_host+':'+l_port, r_host+':'+r_port, retran, state]
result.append(nline)
return result
if __name__ == '__main__':
for conn in netstat():
print conn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment