Python实现快速多线程ping的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python实现快速多线程ping的方法。分享给大家供大家参考。具体如下:

#!/usr/bin/python
#_*_coding:utf-8_*_
#
'''
名称:快速多线程ping程序
开发:gyhong gyh9711
日期:20:51 2011-04-25
'''
import pexpect
import datetime
from threading import Thread
host=["192.168.1.1","192.168.1.123","192.168.2.1",
"192.168.1.1","192.168.1.123","192.168.2.1",
"192.168.1.1","192.168.1.123","192.168.2.1",
"192.168.1.1","192.168.1.123","192.168.2.1",
"192.168.1.1"]
report_ok=[]
report_error=[]
class PING(Thread):
  def __init__(self,ip):
    Thread.__init__(self)
    self.ip=ip
  def run(self):
    Curtime = datetime.datetime.now()  
    #Scrtime = Curtime + datetime.timedelta(0,minute,0) 
    #print("[%s]主机[%s]" % (Curtime,self.ip))
    ping=pexpect.spawn("ping -c1 %s" % (self.ip))
    check=ping.expect([pexpect.TIMEOUT,"1 packets transmitted, 1 received, 0% packet loss"],2)
    if check == 0:
      print("[%s] 超时 %s" % (Curtime,self.ip))
    elif check == 1:
      print ("[%s] %s 可达" % (Curtime,self.ip))
    else:
      print("[%s] 主机%s 不可达" % (Curtime,self.ip))
#多线程同时执行
T_thread=[]
for i in host:
  t=PING(i)
  T_thread.append(t)
for i in range(len(T_thread)):
  T_thread[i].start()
#
#print ("\n=========问题主机情况如下==========\n")
#output(report_error)
#print ("\n=========正常主机情况如下==========\n")
#output(report_ok)

执行结果:

administrator@nagios:/win/pexpect$ ./ping.py
[2011-04-25 21:30:22.126981] 192.168.1.1 可达
[2011-04-25 21:30:22.148376] 192.168.1.1 可达
[2011-04-25 21:30:22.179846] 192.168.1.1 可达
[2011-04-25 21:30:22.203691] 192.168.1.1 可达
[2011-04-25 21:30:22.227696] 192.168.2.1 可达
[2011-04-25 21:30:22.134049] 超时 192.168.1.123
[2011-04-25 21:30:22.145610] 超时 192.168.2.1
[2011-04-25 21:30:22.157558] 超时 192.168.1.123
[2011-04-25 21:30:22.167898] 超时 192.168.2.1
[2011-04-25 21:30:22.197572] 超时 192.168.1.123
[2011-04-25 21:30:22.202430] 超时 192.168.2.1
[2011-04-25 21:30:22.215561] 超时 192.168.1.123
[2011-04-25 21:30:22.229952] 超时 192.168.1.1

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python中对数据进行各种排序的方法

Python列表具有内置的 list.sort()方法,可以在原地修改列表。 还有一个 sorted()内置的函数从迭代构建一个新的排序列表。在本文中,我们将探讨使用Python排序数据...

python 脚本生成随机 字母 + 数字密码功能

下面一段代码给大家介绍python 脚本生成随机 字母 + 数字密码功能,具体代码如下所述: #coding:utf-8 import random,string def GetPa...

浅谈python 里面的单下划线与双下划线的区别

在学习Python的时候,很多人都不理解为什么在方法(method)前面会加好几个下划线,有时甚至两边都会加,比如像 __this__ 这种。在我看到上面的文章之前,我一直以为Pytho...

Python增强赋值和共享引用注意事项小结

概述 Python中的增强赋值是从C语言中借鉴出来的,所以这些格式的用法大多和C一致,本身就是对表达式的简写,即二元表达式和赋值语句的结合,比如a += b 和a = a + b 就是...

Python实现句子翻译功能

Python实现句子翻译功能

初入Python,一开始就被她简介的语法所吸引,代码简洁优雅,之前在C#里面打开文件写入文件等操作相比Python复杂多了,而Python打开、修改和保存文件显得简单得多。 1、打开文件...