python客户端网络延时检测

#!/usr/bin/python3
# -*- coding:utf-8 -*-
import subprocess
import re
import time

class LinkState(object):
    def __init__(self):
        self.ipaddr()

    # 获取当前时间
    def get_time(self):
        return str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))

    #获取IP
    def ipaddr(self):
        comand="netstat -ntp | awk -F '[ :]+' '{if($9 == "'"19200/sshd"'" && $6 != "'"127.0.0.1"'"){print $6}}'"
        res=subprocess.Popen(comand,shell=True,stdout=subprocess.PIPE)
        IP=res.stdout.read().decode('utf-8')
        if IP:
            self.getLinkState(100,IP)

    # 获取网络延时
    def getLinkState(self,count,ip):
        #运行ping程序
        p = subprocess.Popen(("ping -c %s %s" %(count,ip)),
             stdin = subprocess.PIPE,
             stdout = subprocess.PIPE,
             stderr = subprocess.PIPE,
             shell = True)

        #得到ping的结果
        out = p.stdout.read().decode('utf-8')

        #找出丢包率,这里通过‘%’匹配
        regex = re.compile(r'\w*%\w*')
        packetLossRateList = regex.findall(out)
        self.packetLossRate = packetLossRateList[0]

        #找出找出延时最大值,最小值,平均值
        regex = re.compile(r'\d+\.\d+\/')
        timeList = regex.findall(out)
        self.minTime = timeList[-3].replace('/','ms')
        self.maxTime = timeList[-1].replace('/','ms')
        self.averageTime = timeList[-2].replace('/','ms')
        result = {'Loss':self.packetLossRate,'min':self.minTime,'max':self.maxTime,'avg':self.averageTime}
        print(result)

if __name__ == '__main__':
    LinkState()

猜你喜欢

转载自www.cnblogs.com/xwupiaomiao/p/11928149.html