Pages

Tuesday, July 9, 2013

How do I access netstat data in Python?

How do I access netstat data in Python?

I searched the forums for finding answer for this question.
At last I came across this link,

http://stackoverflow.com/questions/3993731/how-do-i-access-netstat-data-in-python


I had already used psutils python API.

I gone through the answer specified in that link.
By using basic information from /proc, NETSTAT is done by the python code.

Number of lines  of code in that Python Program -> 86 [ GEDIT  -> Refer Screenshot ]


Then I tried to achieve the same with psutils Python API.
Surprisingly no. of lines of code in my program -> 50 [Refer Screen Shot]



Here is my code :

Again I am not sure about whether my source code is w.r.t Python Source code guidelines ( : ) )howsoever I tried to do same thing.

import psutil
ESTABLISHED=0
SYN_SENT=0
SYN_RECV=0
FIN_WAIT1=0
FIN_WAIT2=0
TIME_WAIT=0
CLOSE=0
CLOSE_WAIT=0
LAST_ACK=0
LISTEN=0
CLOSING=0
for i in psutil.get_pid_list():
    p = psutil.Process(i)
    c= p.get_connections()
    for j in c:
        if(j.status=="ESTABLISHED"):
            ESTABLISHED=ESTABLISHED+1
                if(j.status=="SYN_SENT"):
                        SYN_SENT=SYN_SENT+1
                if(j.status=="SYN_RECV"):
                        SYN_RECV=SYN_RECV+1
                if(j.status=="FIN_WAIT1"):
                        FIN_WAIT1=FIN_WAIT1+1
                if(j.status=="FIN_WAIT2"):
                        FIN_WAIT2=FIN_WAIT2+1
                if(j.status=="TIME_WAIT"):
                        TIME_WAIT=TIME_WAIT+1
        if(j.status=="CLOSE"):
                        CLOSE=CLOSE+1
                if(j.status=="CLOSE_WAIT"):
            CLOSE_WAIT=CLOSE_WAIT+1
                if(j.status=="LAST_ACK"):
                        LAST_ACK=LAST_ACK+1
                if(j.status=="LISTEN"):
                        LISTEN=LISTEN+1
                if(j.status=="CLOSING"):
                        CLOSING=CLOSING+1
print " ESTABLISHED->"+str(ESTABLISHED)
print " SYN_SENT->"+str(SYN_SENT)
print " SYN_RECV->"+str(SYN_RECV)
print " FIN_WAIT1->"+str(FIN_WAIT1)
print " FIN_WAIT2->"+str(FIN_WAIT2)
print " TIME_WAIT->"+str(TIME_WAIT)
print " CLOSE->"+str(CLOSE)
print " CLOSE_WAIT->"+str(CLOSE_WAIT)
print " LAST_ACK->"+str(LAST_ACK)
print " LISTEN->"+str(LISTEN)
print " CLOSING->"+str(CLOSING)

You  shall download the code from here.

http://onlineexaminationsysteminjava.googlecode.com/files/netstat.py

I  tried to compare the time taken by the both programs to execute.
Time taken by that Python Code  ->
0:00:07.744696
Refer screenshot below.


Time Taken by my Code ->0:00:04.172799
 Refer screenshot below.



I am sure that still this code shall be optimized in terms of line and time.


Thanks to the stackoverflow community, which helps in solving my doubts :).

No comments:

Post a Comment