欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在Python中调用Ping命令,批量IP的方法

程序员文章站 2023-11-03 21:34:52
如下所示: #!/usr/bin/env python #coding:utf-8 ''''''' author: jefferchen@163.com...

如下所示:

#!/usr/bin/env python
#coding:utf-8
'''''''
 author: jefferchen@163.com
 可在命令行直接带目的ip,也可将ip列表在文本文件中。
 pingip.py -d destip 
 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多行存储
'''''''
import argparse
import os
import platform
import time,datetime

def pingcmd():
  cmdstr = ''
  if platform.system()=='linux':
    cmdstr = 'ping -c 1 %s > /dev/null'
  else:
    cmdstr = 'ping -n 1 %s > nul'
  return cmdstr

def ipv4seglist(alist):
  ipseg = alist[0].split('.')
  ip4begin = int(ipseg[3])
  ip4end  = int(alist[1])
  seglist = []
  if ip4end<=ip4begin:
    ip4end += ip4begin
  else:
    ip4end +=1
  for ip in range(ip4begin,ip4end):
    aip = ipseg[0]+'.'+ipseg[1]+'.'+ipseg[2]+'.'+str(ip)
    seglist += [aip]
  return seglist

def parseseg(aseg):
  seglist = []
  alist = aseg.split('-')
  if len(alist)==2:
    seglist = ipv4seglist(alist)
  else:
    seglist = alist
  return seglist

def addlineip(iplist,aline):
  linelist = aline.split(';')
  for aseg in linelist:
    seglist = parseseg(aseg)
    iplist += seglist
  return iplist

def getiplistfromfile(filename):
  iplist = []
  f = open(filename)
  lines = f.readlines()
  for line in lines:
    line = line.strip()
    line = line.replace('\n','')
    iplist = addlineip(iplist,line)
  return iplist

def notifyadmin(failureip):
  print('network error at ',failureip)

def reportsummary(success,failure):
  print('----done! total: %s nodes. %s ---'%(success+failure,timefmt()))

def pinglist(alist):
  sucess,failure = 0,0
  failureip = []
  print('trying...')
  for ip in alist:
    cmdstr = pingcmd()%ip.replace('\n','')
    res = os.system(cmdstr)
    if res < 1 :
      sucess += 1
    else:
      failure += 1
      failureip += [ip]
    time.sleep(1)
  if failure :
     notifyadmin(failureip)
  else:
    reportsummary(sucess,failure);


def timefmt():
  return time.strftime('%y-%m-%d %h:%m:%s', time.localtime(time.time()))

def writelog(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='batch ping utility.')
  parse.add_argument('-f','--filename',default='ip.txt',help='ip file name(default ip.txt)')
  parse.add_argument('-d','--destip',type=str,default='',help='destination ips ');
  args = parse.parse_args()
  if args.destip!='':
    iplist = addlineip([],args.destip)
  else:
    if args.filename!='':
      ipfile = args.filename
    else:
      ipfile = 'ip.txt'
    iplist = getiplistfromfile(ipfile)
  pinglist(iplist)

以上这篇在python中调用ping命令,批量ip的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。