Python基于多线程实现ping扫描功能示例
作者:wanlifeipeng 时间:2023-08-02 17:30:09
本文实例讲述了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程序设计有所帮助。
来源:http://www.cnblogs.com/hupeng1234/p/6729810.html
标签:Python,多线程,ping
0
投稿
猜你喜欢
“生活”设计
2009-03-03 12:14:00
MySQL使用LVM快照实现备份
2024-01-26 20:21:17
Python实现分割文件及合并文件的方法
2022-01-28 00:02:02
nodejs使用socket5进行代理请求的实现
2024-05-09 14:49:44
懒人必备Python代码之自动发送邮件
2022-08-31 20:17:41
解析一个通过添加本地分区索引提高SQL性能的案例
2023-07-22 13:29:32
国内外字体网站(font)的整理
2007-10-14 09:58:00
ASP分页类(支持多风格变换)
2011-04-08 10:39:00
代码总结Python2 和 Python3 字符串的区别
2023-05-25 00:58:52
PJBlog3优化——301定向跳转解决重复内容的问题
2009-05-20 10:40:00
IE Cookie文件格式说明
2023-03-13 17:17:22
千篇一律的JS运算符讲解,一起来看看
2024-05-13 10:06:52
详解vue配置请求多个服务端解决方案
2024-05-05 09:06:11
LangChain简化ChatGPT工程复杂度使用详解
2022-10-21 22:25:34
js鼠标按键事件和键盘按键事件用法实例汇总
2024-04-17 10:04:29
SqlServer 扩展属性的介绍
2024-01-17 09:32:15
mysql 8.0.18 压缩包安装及忘记密码重置所遇到的坑
2024-01-28 18:01:35
Python格式化输出的具体实现
2023-11-20 16:22:19
js数组的基本用法及数组根据下标(数值或字符)移除元素
2024-04-10 10:40:26
Python的Flask框架标配模板引擎Jinja2的使用教程
2022-07-17 08:47:35