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程序设计有所帮助。

相关文章

Django restframework 源码分析之认证详解

Django restframework 源码分析之认证详解

前言 最近学习了 django 的一个 restframework 框架,对于里面的执行流程产生了兴趣,经过昨天一晚上初步搞清楚了执行流程(部分方法还不太清楚),于是想详细的总结一下当来...

对Pandas DataFrame缺失值的查找与填充示例讲解

查看DataFrame中每一列是否存在空值: temp = data.isnull().any() #列中是否存在空值 print(type(temp)) print(temp)...

Python利用前序和中序遍历结果重建二叉树的方法

Python利用前序和中序遍历结果重建二叉树的方法

本文实例讲述了Python利用前序和中序遍历结果重建二叉树的方法。分享给大家供大家参考,具体如下: 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中...

python小项目之五子棋游戏

python小项目之五子棋游戏

本文实例为大家分享了python五子棋游戏的具体代码,供大家参考,具体内容如下 1.项目简介 在刚刚学习完python套接字的时候做的一个五子棋小游戏,可以在局域网内双人对战,也可以和电...

关于Django ForeignKey 反向查询中filter和_set的效率对比详解

前言 大家使用 Django 创建模型的时候一定会经常使用 ForeignKey 来创建两个表格之间多对一的外键关系,例如B中有一个 models.ForeignKey(A) 。而当我们...