【原创】 linux Python&…

有时候需要监视网络状况,有个工具挺不错的, slurm -i wlan0
但是这些值都无法获取,外部也无法调用,所幸自己造一个,直接贴代码:
-----------------------------------------------------------------------------------------
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import division
import subprocess
import time
import re 

TIME = 1 #监视网速的时间间隔
DEVICE = 'wlan0' #网卡名字
LOCAL = 'zh' #本地语言(有的是英文
ALL = False #是否或许所有网卡的网络状态

class NetSpeed():
    def __init__(self):
        self.device = DEVICE
        self.local = LOCAL
    #p_rint 参数意为是否只是打印结果,False - 返回一个列表
    def start(self, p_rint = True):
        if not ALL:
            all_net = [self.device]
        else:
            all_net = self.get_net_name()

        if   p_rint:
            for i in all_net:
                print i,self.get_rx_tx(device = i)
        else:
            result = []
            for j in all_net:
                res = self.get_rx_tx(device = j)
                result.append({'name':j,'rx':res[0],'tx':res[1]})
            return result

    #获取所有网卡名字
    def get_net_name(self):
        with file('/etc/udev/rules.d/70-persistent-net.rules','r')as f:
            r = f.read()
            return re.findall(r'NAME="(.+?)"',r)

    #调用系统命令ifconfig获取指定网卡名 已上传或者下载的字节大小,转换为kb
    def ifconfig(self, device = 'wlan0', local = 'en'):
        output = subprocess.Popen(['ifconfig', device], stdout=subprocess.PIPE).communicate()[0]
        if local == 'zh':
            rx_bytes = re.findall('接收字节:([0-9]*) ', output)[0]
            tx_bytes = re.findall('发送字节:([0-9]*) ', output)[0]
        else:
            rx_bytes = re.findall('RX bytes:([0-9]*) ', output)[0]
            tx_bytes = re.findall('TX bytes:([0-9]*) ', output)[0]
        return float('%.3f' % (int(rx_bytes) / 1024)), float('%.3f' % (int(tx_bytes) / 1024))

    #获取指定网卡的网速
    def get_rx_tx(self,device = 'wlan0',local = LOCAL):
        try:
            while True:
                rx_bytes, tx_bytes = self.ifconfig(device= device,local = self.local)
                time.sleep(TIME)
                rx_bytes_new,tx_bytes_new = self.ifconfig(device= device,local = self.local)

                col_rx = (rx_bytes_new - rx_bytes) / TIME
                col_tx = (tx_bytes_new - tx_bytes) / TIME

                col_rx = '%.3f' % col_rx
                col_tx = '%.3f' % col_tx
                return col_rx, col_tx
        except Exception, e:
            raise e

if __name__ == '__main__':
    Speedp = NetSpeed()
    print Speedp.get_rx_tx(device = 'wlan0', local = 'zh')
-----------------------------------------------------------------------------------------

代码写的比较杂,有冗余。
逻辑就是这样:
一。获取所有网卡名(可选)
二。调用subprocess.Popen函数获取系统输出的内容,获取到指定网卡的上传 下载字节
三。休眠指定时间
四。重复二
五。四-二 将字节转换为kb 即为当前网速。(上一秒的)
完结。


也看过别的文章,各种的写文件,各种的纠结:
------------------------------------------------------------------
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import os
import time

# import utils

def sortedDictValues3(adict):
    keys = adict.keys()
    keys.sort()
    return map(adict.get, keys)

def run():
    # if utils.isLinux() == False:
    #     return [('ifconfig_collect os type error','this is windows')]
    #not first run
    if os.path.isfile('./oldifconfig'):
        fileold = open('./oldifconfig', 'r')
        fileold.seek(0)
        #读入上次记录的临时流量数据文件,和时间戳
        (oldtime, fileoldcontent) = fileold.read().split('#')
        fileold.close;
        netcard = {}
        tempstr = ''
        key = ''
        for strline in fileoldcontent.split('/n'):
            reobj = re.compile('^lo*.')
            if reobj.search(strline):
                break;
            reobj = re.compile('^eth*.')
            if reobj.search(strline):
                key = strline.split()[0]
            tempstr = tempstr + strline + '/n'
            netcard[key] = tempstr
        RXold = {}
        TXold = {}
        for key,value in netcard.items():
            tempsplit = value.split('/n')
            netcard[key] = ''
            for item in tempsplit:
                item = item + '
'
                netcard[key] = netcard[key] + item
                tempcount = 1
                for match in re.finditer("(字节:)(.*?)( ())", item):
                    if tempcount == 1:
                        RXold[key] = match.group(2)
                        tempcount = tempcount + 1
                    elif tempcount == 2:
                        TXold[key] = match.group(2)
                        netcard[key] = netcard[key] + 'net io percent(bytes/s): 0
'
         
        #记录当前网卡信息到临时文件中
        os.system('ifconfig > ifconfigtemp')
        file = open('./ifconfigtemp','r');
        fileold = open('./oldifconfig', 'w')
        temptimestr = str(int(time.time()));
        fileold.write(temptimestr)
        fileold.write('#')
        file.seek(0)
        fileold.write(file.read())
        fileold.close()
        returnkeys = []
        returnvalues = []
        netcard = {}
        tempcountcard = 0
        file.seek(0)
        key = ''
        for strline in file.readlines():
            reobj = re.compile('^lo*.')
            if reobj.search(strline):
                break;
            reobj = re.compile('^eth*.')
            if reobj.search(strline):
                key = strline.split()[0]
                netcard[key] = ''
            netcard[key] = netcard[key] + strline
        newnetcard = {}
        file.seek(0)
        key = ''
        for strline in file.readlines():
            reobj = re.compile('^lo*.')
            if reobj.search(strline):
                break;
            if re.search("^eth", strline):
                templist = strline.split()
                key = templist[0]
                newnetcard[key] = ''
                newnetcard[key] = templist[4] + newnetcard[key] + ' '
            if re.search("^ *inet ", strline):
                templist = strline.split()
                newnetcard[key] = templist[1][5:] + ' ' + newnetcard[key] + ' '
        for key,value in newnetcard.items():
            #记录每张网卡是否工作状态信息到临时文件
            os.system('ethtool %s > ethtooltemp'%(key))
            file = open('./ethtooltemp','r');
            tempethtooltemplist = file.read().split('/n/t')
            file.close
            if re.search("yes", tempethtooltemplist[-1]):
                templist = newnetcard[key].split()
                newnetcard[key] = templist[0] + ' runing! ' + templist[1]
            else:
                templist = newnetcard[key].split()
                if len(templist) > 1:
                    newnetcard[key] = templist[0] + ' stop! ' + templist[1]
                else:
                    newnetcard[key] =   'stop! ' + templist[0]
        file.close()
        RX = {}
        TX = {}
        for key,value in netcard.items():
            tempsplit = value.split('/n')
            netcard[key] = ''
            for item in tempsplit:
                item = item + '
'
                netcard[key] = netcard[key] + item
                tempcount = 1
                for match in re.finditer("(bytes:)(.*?)( ())", item):
                    if tempcount == 1:
                        RX[key] = str(int(match.group(2)) - int(RXold[key]))
                        tempcount = tempcount + 1
                    elif tempcount == 2:
                        TX[key] = str(int(match.group(2)) - int(TXold[key]))
                        divtime = float(int(time.time()) - int(oldtime))
                        if divtime == 0:
                            rate = (float(TX[key]) + float(RX[key]))
                        else:
                            rate = (float(TX[key]) + float(RX[key]))/(divtime)
                        if rate == 0:
                            newnetcard[key] = '0' + ' ' + newnetcard[key]
                        else:
                            newnetcard[key] = '%.2f'%rate + ' ' + newnetcard[key]
        return zip(['order'], ['48']) + newnetcard.items();
    else:
        os.system('ifconfig > ifconfigtemp')
        file = open('./ifconfigtemp','r');
        fileold = open('./oldifconfig', 'w')
        temptimestr = str(int(time.time()));
        fileold.write(temptimestr)
        fileold.write('#')
        file.seek(0)
        fileold.write(file.read())
        fileold.close()

        netcard = {}
        file.seek(0)
        key = ''
        for strline in file.readlines():
            reobj = re.compile('^lo*.')
            if reobj.search(strline):
                break;
            reobj = re.compile('^eth*.')
            if reobj.search(strline):
                key = strline.split()[0]
                netcard[key] = ''
            netcard[key] = netcard[key] + strline
        RX = {}
        TX = {}
         
        key = ''
        newnetcard = {}
        file.seek(0)
        for strline in file.readlines():
            reobj = re.compile('^lo*.')
            if reobj.search(strline):
                break;
            if re.search("^eth", strline):
                templist = strline.split()
                key = templist[0]
                newnetcard[key] = templist[4] + ' '
            if re.search("^ *inet ", strline):
                templist = strline.split()
                newnetcard[key] = newnetcard[key] + templist[1][5:] + ' '
        for key,value in newnetcard.items():
            os.system('ethtool %s > ethtooltemp'%(key))
            file = open('./ethtooltemp','r');
            tempethtooltemplist = file.read().split('/n')
            file.close
            if re.search("yes", tempethtooltemplist[-1]):
                newnetcard[key] = newnetcard[key] + 'runing!'
            else:
                newnetcard[key] = newnetcard[key] + 'stop!'
        file.close()
        for key,value in netcard.items():
            tempsplit = value.split('/n')
            netcard[key] = ''
            for item in tempsplit:
                item = item + '
'
                print item
                netcard[key] = netcard[key] + item
                tempcount = 1
                for match in re.finditer("(字节:)(.*?)( ())", item):
                    if tempcount == 1:
                        RX[key] = match.group(2)
                        tempcount = tempcount + 1
                    elif tempcount == 2:
                        TX[key] = match.group(2)
                        netcard[key] = netcard[key] + 'net io percent(bytes/s): 0
'
                        newnetcard[key] = newnetcard[key] + ' ' + '0
'
        return zip(['order'], ['48']) + newnetcard.items();

if __name__ == '__main__':
    print run()

------------------------------------------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值