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与STM32通信方式

实现Python与STM32通信方式

断断续续学了几周Stm32后,突然想实现上位机和下位机的通信,恰好自己学过一点python,便想通过python实现通信. 在网上看见python库pyserial可以实现此功能,便去官...

python+matplotlib绘制3D条形图实例代码

python+matplotlib绘制3D条形图实例代码

本文分享的实例主要实现的是Python+matplotlib绘制一个有阴影和没有阴影的3D条形图,具体如下。 首先看看演示效果: 完整代码如下: import numpy as n...

用Python写飞机大战游戏之pygame入门(4):获取鼠标的位置及运动

用Python写飞机大战游戏之pygame入门(4):获取鼠标的位置及运动

目标是拷贝微信的飞机大战,当然拷贝完以后大家就具备自己添加不同内容的能力了。 首先是要拿到一些图片素材,熟悉使用图像处理软件和绘画的人可以自己制作,并没有这项技能的同学只能和我一样从网上...

Python的面向对象思想分析

本文实例讲述了Python的面向对象思想。分享给大家供大家参考。具体分析如下: 面向对象的基本思想是封装,继承,多态。 首先是继承: 定义一个类: 复制代码 代码如下:class Bir...

Python 网络编程之UDP发送接收数据功能示例【基于socket套接字】

本文实例讲述了Python 网络编程之UDP发送接收数据功能。分享给大家供大家参考,具体如下: demo.py(UDP发送数据): import socket # 导入socket模...