About Me

My name is Ricardo Pascal, I'm a developer and sysadmin who lives in Florianopolis/Brazil. I enjoy work with projects related to Linux, Python, Science, Web, Django and Network.

g+ A Russian scientist who was struck by a particle accelerator beam | I pictured professor Smith from PHD Comics! | | A kickstarter for the next version of Django Rest Framework. | A empresa Neoprospecta está contratando 2 desenvolvedores python para trabalhar em projetos de bioinformática... | A empresa Neoway está contratando desenvolvedor Python para trabalhar num projeto web com Django em ... | I wrote a small article showing how to display a form, and create objects from them using views in five... | | A Pixeon está com várias vagas abertas. (Inclusive programador Python). | "When deciding which server architecture to use for your environment, there are many factors to consider... | | Segue uma proposta de lei feita pelo DEPUTADO Missionário José Olimpio. É uma lei que visa nos proteger... | By +Ruben Bolling    http://gocomics.typepad.com/tomthedancingbugblog/ THU MAY 29, 2014 AT 06:50 AM ... | Let's send also some cancer, radioactive material, ebola, Justin Bieber and Brazilian Funk  ¬¬ | "The most extreme case is David Whitlock, the M.I.T.-trained chemical engineer who invented AO+. He ... | If I had 8k euros to spare, I would definitely buy one :) | | Esse link eu salvei nos favoritos. Vale a pena! | Estamos procurando Jedi Back-end Engineer We are looking for a engaged and dedicated software engineer... | django-auth-imap is a package that let you use a IMAP server as backend for authentication in your django... |

A python netstat in less than 100 lines of code

Do a python netstat in linux is not really hard, if you know where to look for information and how to use it. Here goes the tip: basically any information you could need to clone a system tool, can be retrieved from the system itself. At this particular case what I did was follow these six steps:

  • type ‘man netstat’
  • Read
  • type ‘man proc’
  • Read
  • Code
  • Back to step one

Here is the result:


import pwd
import os
import re
import glob

PROC_TCP = "/proc/net/tcp"

def _load():
    ''' Read the table of tcp connections & remove header  '''
    with open(PROC_TCP,'r') as f:
        content = f.readlines()
    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():
    Function to return a list with status of tcp connections at linux systems
    To get pid of all network process running on system, you must run this script
    as superuser

    result = []
    for line in content:
        line_array = _remove_empty(line.split(' '))     # Split lines and remove empty spaces.
        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]
        state = STATE[line_array[3]]
        uid = pwd.getpwuid(int(line_array[7]))[0]       # Get user from UID.
        inode = line_array[9]                           # Need the inode to get process pid.
        pid = _get_pid_of_inode(inode)                  # Get pid prom inode.
        try:                                            # try read the process name.
            exe = os.readlink('/proc/'+pid+'/exe')
            exe = None

        nline = [tcp_id, uid, l_host+':'+l_port, r_host+':'+r_port, state, pid, exe]
    return result

def _get_pid_of_inode(inode):
    To retrieve the process pid, check every running process and look for one using
    the given inode.
    for item in glob.glob('/proc/[0-9]*/fd/[0-9]*'):
            if re.search(inode,os.readlink(item)):
                return item.split('/')[2]
    return None

if __name__ == '__main__':
    for conn in netstat():
        print conn

by Ricardo Pascal on Jun 27, 2011

comments powered by Disqus