在Python中调用Ping命令,批量IP的方法
如下所示:
#!/usr/bin/envpython #coding:UTF-8 ''''''' Author:jefferchen@163.com 可在命令行直接带目的IP,也可将IP列表在文本文件中。 pingip.py-dDestIP DestIP示例:a)单个:192.168.11.1 b)多个:192.168.11.1;172.16.8.1;176.13.18.2 c)网段:192.168.11.1-127 文本文件:ip.txt 目的IP多行存储 ''''''' importargparse importos importplatform importtime,datetime defPingCmd(): cmdStr='' ifplatform.system()=='Linux': cmdStr='ping-c1%s>/dev/null' else: cmdStr='ping-n1%s>nul' returncmdStr defIPV4SegList(aList): IPSeg=aList[0].split('.') IP4Begin=int(IPSeg[3]) IP4End=int(aList[1]) segList=[] ifIP4End<=IP4Begin: IP4End+=IP4Begin else: IP4End+=1 foripinrange(IP4Begin,IP4End): aIP=IPSeg[0]+'.'+IPSeg[1]+'.'+IPSeg[2]+'.'+str(ip) segList+=[aIP] returnsegList defParseSeg(aSeg): segList=[] aList=aSeg.split('-') iflen(aList)==2: segList=IPV4SegList(aList) else: segList=aList returnsegList defAddLineIP(IPList,aLine): LineList=aLine.split(';') foraSeginLineList: segList=ParseSeg(aSeg) IPList+=segList returnIPList defGetIPListFromFile(filename): IPList=[] f=open(filename) lines=f.readlines() forlineinlines: line=line.strip() line=line.replace('\n','') IPList=AddLineIP(IPList,line) returnIPList defNotifyAdmin(failureIP): print('Networkerrorat',failureIP) defReportSummary(success,failure): print('----DONE!Total:%snodes.%s---'%(success+failure,timeFmt())) defPingList(aList): sucess,failure=0,0 failureIP=[] print('Trying...') foripinaList: cmdStr=PingCmd()%ip.replace('\n','') res=os.system(cmdStr) ifres<1: sucess+=1 else: failure+=1 failureIP+=[ip] time.sleep(1) iffailure: NotifyAdmin(failureIP) else: ReportSummary(sucess,failure); deftimeFmt(): returntime.strftime('%Y-%m-%d%H:%M:%S',time.localtime(time.time())) defwriteLog(content): print('[%s]%s'%(timeFmt(),content)) file_object=open('ping.'+time.strftime('%Y-%m-%d',time.localtime(time.time()))+'.log','a') file_object.write('[%s]%s\n'%(timeFmt(),content)); file_object.close() if__name__=='__main__': parse=argparse.ArgumentParser(description='Batchpingutility.') parse.add_argument('-f','--filename',default='ip.txt',help='IPfilename(DefaultIP.txt)') parse.add_argument('-d','--destip',type=str,default='',help='destinationIPs'); args=parse.parse_args() ifargs.destip!='': IPList=AddLineIP([],args.destip) else: ifargs.filename!='': IPFile=args.filename else: IPFile='ip.txt' IPList=GetIPListFromFile(IPFile) PingList(IPList)
以上这篇在Python中调用Ping命令,批量IP的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。