• Linux中使用python测试主机存活 Linux系统CentOS Linux release 7.3.1611 (Core) py版本Python 2.7.5


    
    

     下面是最初的情况

    #/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import os
    import time
    import subprocess
    import threading
    from threadpool import ThreadPool
    import threadpool
    import re
    from Queue import Queue
    
    def ping_call():
        while not IP_QUEUE.empty():
            ip=IP_QUEUE.get()
            command='ping -c 2 -W 1 %s'%ip
            print(command)
            result=subprocess.Popen(command,
                           shell=True,stdout=subprocess.PIPE) //A
            s=result.stdout.read()
            e = "ttl" in s
            if e:
                print('ip地址:{} ping ok'.format(ip))
            else:
                print('ip地址:{} ping fall'.format(ip))      //B
    
    
    if __name__ == '__main__':
        network=input('请输入网段>>>').strip()
        host=input('请输入主机范围以空格隔开>>>').strip().split()
        a,b=host[0],host[1]
        print(network.split('.'))
        if len(network.split('.'))==3 and a.isdigit() and b.isdigit() and re.match('d{1,3}.d{1,3}.d{1,3}',network):
            a=int(a)
            b=int(b)
            start_time = time.time()
            IP_QUEUE=Queue()
        threads=[]
        for i in range(a,b+1):
                IP_QUEUE.put(network+'.'+str(i))
        for i in range(50):
            thread=threading.Thread(target=ping_call)
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()
            print("程序耗时{:.2f}".format(time.time() - start_time))
    View Code

    上面的例子也可用改为subprocess.call,在linux系统中命令结果成功为真就时0 ,失败则为假,windows系统上面只关心命令本身是不是可用执行,不关心结果,所以只能用在Linux系统上面

    修改标注A到B的代码结果为:

    #/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import os
    import time
    import subprocess
    import threading
    import re
    from Queue import Queue
    
    def ping_call():
        while not IP_QUEUE.empty():
            ip=IP_QUEUE.get()
            command='ping -c 2 -W 1 %s'%ip
            print(command)
            result=subprocess.call(command,
                           shell=True,stdout=subprocess.PIPE)
    
            if result:
                print('ip地址:{} ping fail'.format(ip))
            else:
                        print('ip地址:{} ping ok'.format(ip))
    
    
    if __name__ == '__main__':
        network=input('请输入网段>>>').strip()
        host=input('请输入主机范围以空格隔开>>>').strip().split()
        a,b=host[0],host[1]
        print(network.split('.'))
        if len(network.split('.'))==3 and a.isdigit() and b.isdigit() and re.match('d{1,3}.d{1,3}.d{1,3}',network):
            a=int(a)
            b=int(b)
            start_time = time.time()
            IP_QUEUE=Queue()
        threads=[]
        for i in range(a,b+1):
                IP_QUEUE.put(network+'.'+str(i))
        for i in range(50):
            thread=threading.Thread(target=ping_call)
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()
            print("程序耗时{:.2f}".format(time.time() - start_time))

     进一步改版为:

    #/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import os
    import time
    import subprocess
    import threading
    from threadpool import ThreadPool
    import threadpool
    import re
    from Queue import Queue
    
    def ping_call():
        while not IP_QUEUE.empty():
            ip=IP_QUEUE.get()
            command='ping -c 2 -W 1 %s'%ip
            file=open('/dev/null','w')
            result=subprocess.call(command,
                           shell=True,stdout=file,stderr=file)
            if result:
                print('ip地址:{} ping fail'.format(ip))
            else:
                        print('ip地址:{} ping ok'.format(ip))
                success.append(ip.split('.')[-1])
            file.close()
    
    if __name__ == '__main__':
        network=input('请输入网段>>>').strip()
        host=input('请输入主机范围以空格隔开>>>').strip().split()
        a,b=host[0],host[1]
        print(network.split('.'))
        if len(network.split('.'))==3 and a.isdigit() and b.isdigit() and re.match('d{1,3}.d{1,3}.d{1,3}',network):
            a=int(a)
            b=int(b)
            start_time = time.time()
            IP_QUEUE=Queue()
        threads=[]
        success=[]
        for i in range(a,b+1):
                IP_QUEUE.put(network+'.'+str(i))
        for i in range(50):
            thread=threading.Thread(target=ping_call)
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()
            print("程序耗时{:.2f}".format(time.time() - start_time))
        print("成功主机有:")
        for i in success:
            print(i)

     那么上面的几个脚本如何执行呢,这里也是碰到了很多坑,主要是输入的数据要打引号

    [root@centos7 ~]# python ping_host.py 
    请输入网段>>>'192.168.0'
    请输入主机范围以空格隔开>>>'1 10'
    ['192', '168', '0']
    ip地址:192.168.0.1 ping ok
    ip地址:192.168.0.4 ping fail
    ip地址:192.168.0.3 ping fail
    ip地址:192.168.0.5 ping fail
    ip地址:192.168.0.9 ping fail
    ip地址:192.168.0.6 ping fail
    ip地址:192.168.0.8 ping fail
    ip地址:192.168.0.2 ping fail
    ip地址:192.168.0.7 ping fail
    程序耗时2.16
    成功主机有:
    1
    View Code
  • 相关阅读:
    Linux Shell常用技巧(一)
    使用Native API 创建进程
    Windows操作系统下创建进程的过程
    Windows操作系统下创建进程的过程
    windows运行打开服务命令
    windows运行打开服务命令
    出错提示:“Could not flush the DNS Resolver Cache: 执行期间,函数出了问题”的解决方法
    出错提示:“Could not flush the DNS Resolver Cache: 执行期间,函数出了问题”的解决方法
    对XP上的KiFastSystemCall进行浅析
    对XP上的KiFastSystemCall进行浅析
  • 原文地址:https://www.cnblogs.com/mmyy-blog/p/9566212.html
Copyright © 2020-2023  润新知