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

 

posted on 2018-08-31 15:50 dawn-liu 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/mmyy-blog/p/9566212.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值