我使用的方法是直接運行ping程序,從結果中正則匹配出想要的數據。python
不一樣的系統中,匹配過程可能有差異。shell
# -*- coding:utf8 -*- #!/usr/bin/python import subprocess import re class LinkState(object): def __init__(self,ip): self.ip = ip self.getLinkState(self.ip) # 獲取鏈路狀態 def getLinkState(self,ip): #運行ping程序 p = subprocess.Popen(["ping.exe", ip], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True) #獲得ping的結果 out = p.stdout.read() # print out #找出丟包率,這裏經過‘%’匹配 regex = re.compile(r'\w*%\w*') packetLossRateList = regex.findall(out) self.packetLossRate = packetLossRateList[0] #找出往返時間,這裏經過‘ms’匹配 regex = re.compile(r'\w*ms') timeList = regex.findall(out) self.minTime = timeList[-3] self.maxTime = timeList[-2] self.averageTime = timeList[-1] self.showResult() #輸出結果 def showResult(self): result = {'packetLossRate':self.packetLossRate,'minTime':self.minTime,'maxTime':self.maxTime,'averageTime':self.averageTime} print result if __name__ == '__main__': ip = 'baidu.com' #要ping的主機 LinkState(ip)