[背景]用来对IDC状态测试的程序
[脚本如下:]
#!/usr/bin/env python
#Create by badboy
#2009/11/22

'''multithreading ping for checking IDC status!'''

import threading
import os
import time

size = ('20','2000')
conf_file="data.ini"
log_file ="result.log"
lineip=[]
linemn=[]

class MyThread(threading.Thread):
    def __init__(self, func, dip):
        threading.Thread.__init__(self)
        self.func = func
        self.args = dip

    def run(self):
        apply(self.func, self.args)

def OpenFile():
    fp=file(conf_file)
    for line in fp:
         lines=line.split("=")
         linemn.append(lines[0].strip())
         lineip.append(lines[1].strip())
    return lineip,linemn
    fp.close()

def ToLog(*results):
    result=""
    for lineresult in results:
        result=result+lineresult+","
    result=result[0:-1]+"\n"
    fp=file(log_file,'a')
    fp.write(result)
    fp.close()

def Getime():
    return time.strftime("%Y/%m/%d %X")

def Ping(psize,dip,idcname):
        pingstr="ping -c 10 -s "+psize+" "+dip
        Process(pingstr,idcname,dip,psize)

def Process(pingstr,idcname,dip,psize):
    strping = pingstr
    idc = idcname
    idcip = dip
    packsz = psize
    result = os.popen(pingstr).readlines()
    cur_time=Getime()
    result2=str(result[-1].strip())
    if not result2.endswith('loss'):
        totalloss=result[-2].split(",")[2].split('%')[0]
        result3=result[-1].split("=")[1].split('/')
        ToLog(idc,idcip,cur_time,packsz,result3[0],result3[1],result3[2],totalloss)
    else:
        cur_time=Getime()
        ToLog(idc,idcip,cur_time,packsz,'0','0','0','100')
def main():
    threads = []
    ipmn=OpenFile()
    ip=ipmn[0]
    idcname=ipmn[1]
    nloops = range(len(ip))

    for i in nloops:
        for psize in size:
            t = MyThread(Ping,(psize,ip[i],idcname[i]))
            threads.append(t)

    threadnum=range(len(threads))
    for i in threadnum:
        threads[i].start()

    for i in threadnum:
        threads[i].join()


if __name__ == '__main__':
    main()


如果想了解更多,请关注我们的公众号
公众号ID:opdevos
扫码关注

多线程ping_职场