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):
            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))

 上面的例子也可用改为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):
            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

猜你喜欢

转载自www.cnblogs.com/mmyy-blog/p/9566212.html