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

yipeiwu_com6年前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的Django和layim实现即时通讯的方法

使用Python的Django和layim实现即时通讯的方法

看到Django和layim实现websocketde资料很少,自己就琢磨了下,顺便搭建出来了。自己要去找闲心大神授权呀。 先来看图 这是初次搭建的,今天一天就搞定。我自己接入了图灵机...

python3实现ftp服务功能(服务端 For Linux)

python3实现ftp服务功能(服务端 For Linux)

本文实例为大家分享了python3实现ftp服务功能的具体代码,供大家参考,具体内容如下 功能介绍: 可执行的命令: ls pwd cd put rm get mkdir 1、...

Pyinstaller将py打包成exe的实例

Pyinstaller将py打包成exe的实例

背景:分享python编写的小脚本时,拷贝代码还缺各种环境,使用Pyinstaller将py可以打包成exe,直接运行即可 1、安装pyinstaller运行时所需要的windows拓展...

Python实现MySQL操作的方法小结【安装,连接,增删改查等】

本文实例讲述了Python实现MySQL操作的方法。分享给大家供大家参考,具体如下: 1. 安装MySQLdb.从网站下载Mysql for python 的package 注意有32位...

python学习笔记之调用eval函数出现invalid syntax错误问题

pytho的使用和分发完全是免费的,它是一种面向对象的语言,它的。它的类模块支持多态,操作符重载和多重继承等高级概念,并且以python特有的简洁的语法和类型,OOP十分易于使用。pyt...