直接上代码,主要是用正则和多线程实现的
#!/usr/bin/env python
#coding:utf-8
import subprocess
import re
import sys
import os
import threading
mlock = threading.Lock()
def getPING(ip,item):
regLost = r'(\d+)%' #定义获取丢包率的正则
regSec = r'min/avg/max/mdev = ([0-9.]+)/([0-9.]+)/([0-9.]+)/([0-9.]+)\sms' #定义获取网络时延的正则
mlock.acquire() #加锁
try:
p = subprocess.Popen("ping -c 30 -i 0.5 %s" %ip, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)
out = p.stdout.read().decode('utf-8')
lost = re.search(regLost,out)
sec = re.search(regSec,out)
reglost = lost.group().split("%")[0]
avgsec = sec.groups()[1]
except Exception as e:
pass
mlock.release() #释放锁
if __name__ == '__main__':
threads = []
fr = open("ip.list","r")
while True:
line = fr.readline()
if line:
ip = line.strip("\n").split(",")
t = threading.Thread(target=getPING,args=ip) #args=是放参数的,target=后面跟的是需要执行的函数
threads.append(t) #执行一次函数往列表里添加一次,在下面的迭代中需要用到
else:
break
for t in threads:
try:
t.start()
except Exception as e:
continue
for t in threads:
t.join()