python批量ping内网ip

来源:互联网 发布:录制电脑屏幕视频软件 编辑:程序博客网 时间:2024/04/25 08:01

1.单线程ping所知道的ip地址

 在脚本所在目录下新建ip_list.txt和ip_False.txt 其中ip_list.txt是存放所已知的ip地址(每行只写一个ip,最后一个ip也需要换行)脚本未做兼容处理,只使用于window系统 
#!/usr/bin/env/python#_*_coding:utf-8_*_#Data:17-05-15#Auther:苏莫#Link:http://blog.csdn.net/lingluofengzang/#PythonVersion:python2.7#filename:ping_ips.pyimport sysimport subprocessimport osimport time'''    检测设备运行是否正常    待检测IP添加在ip_list.txt    每次不正常IP追加在文件ip_False.txt'''reload(sys)sys.setdefaultencoding('utf-8')#获取当前工作路径def getCurrendPath():    return os.getcwd()#调用ping命令,判断IP是否正常def subPing():    ip_list = []    _path = getCurrendPath()    ip_lists = _path + r'\ip_list.txt'    ip_False = _path + r'\ip_False.txt'    for line in open(ip_lists):        ret = subprocess.call("ping %s -n 3" % line,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE)        if ret == 1:            ip = '%s is not alive, there have some problem' % line[:-1]            ip_list.append(ip)    if ip_list:        nowTime = getDataTime()        errorFile = open(ip_False,'a')        errorFile.write(u"时间"+nowTime+'\n')        for errorIP in ip_list:            errorFile.write(errorIP+'\n')        errorFile.close()        print '''        ===============================        Problems with device operation!        Please check the equipment!!!        ===============================        '''    else:        print '''        ===============================              Everything is OK !!!        ===============================        '''#获取当前时间,格式XXXX-XX-XXdef getDataTime():    return time.strftime('%Y-%m-%d',time.localtime(time.time()))if __name__ == '__main__':    subPing()

2.多线程扫描内网存活主机

运行脚本格式: python IPscanner.py [本机ip]脚本可用在所有系统上
#!/usr/bin/env/python#_*_coding:utf-8_*_#Data:17-09-03#Auther:苏莫#Link:http://blog.csdn.net/lingluofengzang/#PythonVersion:python2.7#filename:IPscanner.pyimport osimport sysimport timeimport threadingreload(sys)sys.setdefaultencoding("utf-8")# 获取脚本运行的系统def get_system():    if os.name == 'nt':        return 'n'    else:        return 'c'def ping_ip(ip_str):    shell = ['ping','-{op}'.format(op=get_system()),'1',ip_str]    output = os.popen(' '.join(shell)).readlines()    for line in list(output):        if not line:            continue        if str(line).upper().find('TTL') >= 0:            print "ip: %s is ok " % ip_str            breakdef find_ip(ip_prefix):    for i in xrange(1,256):        ip = '%s.%s' % (ip_prefix,i)        threading.Thread(target = ping_ip , args = (ip , )).start()        time.sleep(0.3)if __name__ == '__main__':    cmd = sys.argv[1:]    args = ''.join(cmd)    ip_prefix = '.'.join(args.split('.')[:-1])    find_ip(ip_prefix)