python实现netstat命令的代码

python实现netstat命令的代码

python实现netstat命令的代码
#!/usr/bin/python

import pwd
import os
import re
import glob

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():
    ''' Read thetable of tcp connections & remove header '''
    withopen(PROC_TCP,'r') as f:
       content = f.readlines()
       content.pop(0)
    returncontent

def _hex2dec(s):
    returnstr(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 [xfor x in array if x !='']

def _convert_ip_port(array):
    host,port =array.split(':')
    return_ip(host),_hex2dec(port)

def netstat():
    '''
    Function toreturn a list with status of tcp connections at linux systems
    To get pidof all network process running on system, you must run thisscript
    assuperuser
    '''

   content=_load()
    result =[]
    for line incontent:
       line_array = _remove_empty(line.split(''))    # Split lines and remove empty spaces.
       l_host,l_port = _convert_ip_port(line_array[1]) # Convert ipaddressand 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')
       except:
           exe = None

       nline = [tcp_id, uid, l_host+':'+l_port, r_host+':'+r_port, state,pid, exe]
       result.append(nline)
    returnresult

def _get_pid_of_inode(inode):
    '''
    To retrievethe process pid, check every running process and look for oneusing
    the giveninode.
    '''
    for item inglob.glob('/proc/[0-9]*/fd/[0-9]*'):
       try:
           if re.search(inode,os.readlink(item)):
               return item.split('/')[2]
       except:
           pass
    returnNone

if __name__ == '__main__':
    for conn innetstat():
       print conn
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值