#!/usr/bin/env python
#coding:utf-8

import subprocess
import re
import sys
import os
import threading

count = 100  # PING 次数
wait  = 0.1  # 等待时间
width = 10   # 显示长度

mlock = threading.Lock()
#def getPING(ip,item):
def getPING(ip):  
    regLost = r'(\d+)%'   #定义获取丢包率的正则
    #regSec = r'min/avg/max/mdev = ([0-9.]+)/([0-9.]+)/([0-9.]+)/([0-9.]+)\sms'  #定义获取网络时延的正则
    regSec = r'min/avg/max/[a-zA-Z]+ = ([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)  
        command = "ping -c %s -i %s %s" %(count, wait, ip)
        p = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell = True)  
        #p = subprocess.Popen("ping -c " + count + " -i " + wait + " %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)
        loss  = lost.group().split("%")[0]
        min = sec.groups()[0]
        avg = sec.groups()[1]
        max = sec.groups()[2]
        print "|" + ip.center(30,' ') + "|" + min.center(width, ' ') + "|" + avg.center(width,' ') + "|" + max.center(width,' ') + "|" + loss.center(width,' ') + "|"
    except Exception as e:
        pass
    #mlock.release()   #释放锁

if __name__ == '__main__':
   threads = []
   fr = open("ip.list","r")

   print ""
   print "|" + "host".center(30, ' ') + "|" + "min(ms)".center(width,' ') + "|" + "avg(ms)".center(width, ' ') +  "|" + "max(ms)".center(width,' ') + "|" + "loss(%)".center(width, ' ') + "|" 
   print "|" + "".center(30, '-') + "|" + "".center(width,'-') + "|" + "".center(width, '-') +  "|" + "".center(width,'-') + "|" + "".center(width, '-') + "|" 

   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()

   print ""

