@@ -0,0 +1,2531 @@
+#!/usr/bin/python%0A# Inspired by: http://voorloopnul.com/blog/a-python-netstat-in-less-than-100-lines-of-code/%0A%0Aimport pwd%0Aimport os%0Aimport re%0Aimport glob%0A%0A%0Aclass netstat():%0A  def __init__(self):%0A%09self.PROC_TCP = %22/proc/net/tcp%22%0A%09self.STATE = %7B%0A      '01':'ESTABLISHED',%0A      '02':'SYN_SENT',%0A      '03':'SYN_RECV',%0A      '04':'FIN_WAIT1',%0A      '05':'FIN_WAIT2',%0A      '06':'TIME_WAIT',%0A      '07':'CLOSE',%0A      '08':'CLOSE_WAIT',%0A      '09':'LAST_ACK',%0A      '0A':'LISTEN',%0A      '0B':'CLOSING'%0A    %7D%0A%0A  def _load(self):%0A    # Read the table of tcp connections & remove header %0A    with open(self.PROC_TCP,'r') as f:%0A      content = f.readlines()%0A      content.pop(0)%0A    return content%0A%0A  def _hex2dec(self, s):%0A    return str(int(s,16))%0A%0A  def _ip(self, s):%0A    ip = %5B(self._hex2dec(s%5B6:8%5D)),(self._hex2dec(s%5B4:6%5D)),(self._hex2dec(s%5B2:4%5D)),(self._hex2dec(s%5B0:2%5D))%5D%0A    return '.'.join(ip)%0A%0A  def _remove_empty(self, array):%0A    return %5Bx for x in array if x !=''%5D%0A%0A  def _convert_ip_port(self, array):%0A    host,port = array.split(':')%0A    return self._ip(host),self._hex2dec(port)%0A%09%0A  def _get_pid_of_inode(inode):%0A   # Check every running process and look for one using the given inode, to find the pid%0A    for item in glob.glob('/proc/%5B0-9%5D*/fd/%5B0-9%5D*'):%0A      try:%0A        if re.search(inode,os.readlink(item)):%0A          return item.split('/')%5B2%5D%0A      except:%0A        pass%0A    return None%0A%0A  def list(self):%0A    # List all TCP connections%0A    # Root can get the pid of networking processes%0A    content=self._load()%0A    result = %5B%5D%0A    for line in content:%0A      line_array = self._remove_empty(line.split(' '))     # Split lines and remove empty spaces.%0A      l_host,l_port = self._convert_ip_port(line_array%5B1%5D) # Convert ipaddress and port from hex to decimal.%0A      r_host,r_port = self._convert_ip_port(line_array%5B2%5D) %0A      tcp_id = line_array%5B0%5D%0A      state = self.STATE%5Bline_array%5B3%5D%5D%0A      uid = pwd.getpwuid(int(line_array%5B7%5D))%5B0%5D       # Get user from UID.%0A      inode = line_array%5B9%5D                           # Need the inode to get process pid.%0A      pid = self._get_pid_of_inode(inode)                  # Get pid prom inode.%0A      try:                                            # try read the process name.%0A        exe = os.readlink('/proc/'+pid+'/exe')%0A      except:%0A        exe = None%0A%0A      nline = %5Btcp_id, uid, l_host+':'+l_port, r_host+':'+r_port, state, pid, exe%5D%0A      result.append(nline)%0A    return result%0A%0A%0Aif __name__ == '__main__':%0A  netstats = netstat()%0A  print c for conn in netstats.list()%0A

Create linux_netstat.py