Python:MultiPing.py

最近接到一个需求,拿到一批IP列表做PING的操作,当然可以利用fping,自己也用多线程写了一个,还不错,6w条IP在15分钟内PING完,记录一下代码吧。

#!/usr/bin/python
import os,sys,time
import threading
import re
import subprocess

lifeline = re.compile(r"[0-9]+\.\d*")
deadline = re.compile(r"100% packet loss")

def ping(ip):
    pingaling = subprocess.Popen(["ping","-q", "-c 3", ip], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    while 1:
        pingaling.stdout.flush()
        line = pingaling.stdout.readline()
        tmp=re.sub(ip,"",line)
        if not line: break
        igot = re.findall(lifeline,tmp)
        deadping = re.findall(deadline,tmp)
        if len(igot)==4:
            #print ip,igot[2]
            pingoutput=str(ip.strip())+','+str(igot[2])
        if deadping:
            #print ip,deadping
            pingoutput=str(ip.strip())+','+'200000'
    output = open('/home/abc/upload/ip_list.txt.output', 'a+')
    output.write(pingoutput+'\n')

def main():
    iplist=open("/home/abc/upload/ip_list.txt", "r")
    print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    for i in iplist:
        ip=i
        while threading.activeCount()>300:
            time.sleep(0.1)
        t=threading.Thread(target=ping,args=([ip,]))
        t.start()
    print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

if __name__=='__main__':
    main()

你可能感兴趣的:(Python:MultiPing.py)