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 专题二 条件语句和循环语句的基础知识

Python 专题二 条件语句和循环语句的基础知识

前面讲述了"专题一.函数的基础知识",而这篇文章讲述的Python的条件语句和循环语句的基础知识.主要内容包括: 1.条件语句:包括单分支、双分支和多分支语句,if-elif-else...

浅谈django model postgres的json字段编码问题

django model的json字段的编码器不能有效编码诸如uuid,datetime等数据类型,当直接存储此类型的对象到json字段中为抛出编码异常,这时可以通过JSONField字...

python ceiling divide 除法向上取整(或小数向上取整)的实例

向上取整的方法: 方法1: items = 102 boxsize = 10 num_boxes = (items + boxsize - 1) // boxsize 方法2:...

对Python 简单串口收发GUI界面的实例详解

忙活了三个多小时,连学带做,总算是搞出来了一个具有基本功能的串口通信PC机的GUI界面,Tkinter在python中确实很好用,而且代码量确实也很少,不足的是Tkinter不自带com...

详解Numpy数组转置的三种方法T、transpose、swapaxes

详解Numpy数组转置的三种方法T、transpose、swapaxes

Numpy是高性能科学计算和数据分析的基础包,里面包含了许多对数组进行快速运算的标准数学函数,掌握这些方法,能摆脱数据处理时的循环。 1.首先数组转置(T) 创建二维数组data如下:...