怎么在Python中利用多线程实现ping扫描

今天就跟大家聊聊有关怎么在Python中利用多线程实现ping扫描,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

具体如下:

# -*- 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中利用多线程实现ping扫描有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。