Python基于多线程实现ping扫描功能示例

yipeiwu_com5年前Python基础

本文实例讲述了Python基于多线程实现ping扫描功能。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
#! python2
import subprocess
from Queue import Queue
import threading
class Pinger(object):
  def __init__(self, ip_list, thread_num=2):
    self._ip_list = ip_list
    self._thread_num = thread_num
    self._queue = Queue(len(ip_list))
  def ping(self, thread_id):
    while True:
      if self._queue.empty():
        break
      addr = self._queue.get()
      print 'Thread %s: Ping %s' % (thread_id, addr)
      ret = subprocess.call('ping -c 1 %s' % (addr),
                 shell=True,
                 stdout=open("/dev/null", 'w'),
                 stderr=subprocess.STDOUT)
      if ret == 0:
        print '%s: is still alive' % addr
      else:
        print '%s: did not respond ' % addr
      self._queue.task_done() #unfinished tasks -= 1
  def run(self):
    for ip in self._ip_list:
      self._queue.put(ip) #unfinished_tasks += 1
    print '---------------------task begin------------------'
    for i in range(self._thread_num):
      thrd = threading.Thread(target=self.ping, args=(i + 1,))
      #thrd.setDaemon(True)
      thrd.start()
    self._queue.join() # 主线程一直阻塞,一直等到Queue.unfiinshed_tasks == 0
    print '---------------------task done-------------------'

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

相关文章

Python获取网段内ping通IP的方法

问题描述 在某些问题背景下,需要确认是否多台终端在线,也就是会使用我们牛逼的ping这个命令,做一些的ping操作,如果需要确认的设备比较少,也还能承受。倘若,在手中维护的设备很多。那么...

python使用mysqldb连接数据库操作方法示例详解

复制代码 代码如下:# -*- coding: utf-8 -*-     #mysqldb    import...

同时安装Python2 & Python3 cmd下版本自由选择的方法

同时安装Python2 & Python3 cmd下版本自由选择的方法

系统:win7 python2.7,python3.6同时安装,于是问题来了,python27与python36文件夹下的文件名都是python.exe 这样在cmd下,直接输入pyt...

python主线程捕获子线程的方法

最近,在做一个项目时遇到的了一个问题,主线程无法捕获子线程中抛出的异常。 先看一个线程类的定义 ''''' Created on Oct 27, 2015 @author:...

Python设计模式之抽象工厂模式原理与用法详解

Python设计模式之抽象工厂模式原理与用法详解

本文实例讲述了Python设计模式之抽象工厂模式原理与用法。分享给大家供大家参考,具体如下: 抽象工厂模式(Abstract Factory Pattern):提供一个创建一系列相关或相...