我用Python编写了一个小脚本,用于ping我学校无线网络的所有子网,并打印出连接到网络每个子网的计算机的IP地址和主机名。我目前的设置是我依靠创建线程来处理每个ping请求。
from threading import Thread
import subprocess
from Queue import Queue
import time
import socket
#wraps system ping command
def ping(i, q):
"""Pings address"""
while True:
ip = q.get()
#print "Thread %s: Pinging %s" % (i, ip)
result = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#Avoid flooding the network with ping requests
time.sleep(3)
if result == 0:
try:
hostname=socket.gethostbyaddr(ip)
print "%s (%s): alive" % (ip,hostname[0])
except:
print "%s: alive"%ip
q.task_done()
num_threads = 100
queue = Queue()
addresses=[]
#Append all possible IP addresses from all subnets on wireless network
for i in range(1,255):
for j in range(1,254):
addresses.append('128.119.%s.%s'%(str(i),str(j)))
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=ping, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Place work in queue
for ip in addresses:
queue.put(ip)
#Wait until worker threads are done to exit
queue.join()
但是,我想修改我的脚本,以便它只搜索子网中的第一个可用主机。这意味着假设我有以下子网(128.119.177.0/24),第一个可用主机是128.119.177.20。我希望我的脚本在成功联系128.119.177.20后停止ping 128.119.177.0/24中的其余主机。我想对网络上的每个子网重复一遍(128.119.0.1 - 128.119.255.254)。鉴于我目前的设置,进行此更改的最佳做法是什么?我正在考虑做一些类似于队列列表的事情(其中每个队列为其中一个子网保存255个IP地址)并且每个队列都有一个线程处理(除非我在Windows上用Python生成多少个线程有限制)
编辑:我已经使用nmap(和愤怒的IP扫描程序)来完成这项任务,但我有兴趣继续编写自己的脚本。答案 0 :(得分:1)
最简单的方法是让一个线程在整个子网中工作,并在找到主机时退出。
<强> UNTESTED 强>
from Queue import Queue
import time
import socket
#wraps system ping command
def ping(i, q):
"""Pings address"""
while True:
subnet = q.get()
# each IP addresse in subnet
for ip in (subnet=str(x) for x in range(1,254)):
#print "Thread %s: Pinging %s" % (i, ip)
result = subprocess.call("ping -n 1 %s" % ip, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
#Avoid flooding the network with ping requests
time.sleep(3)
if result == 0:
try:
hostname=socket.gethostbyaddr(ip)
print "%s (%s): alive" % (ip,hostname[0]
except:
print "%s: alive"%ip
break
q.task_done()
num_threads = 100
queue = Queue()
#Put all possible subnets on wireless network into a queue
for i in range(1,255):
queue.put('128.119.%s.'%i)
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=ping, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Wait until worker threads are done to exit
queue.join()
答案 1 :(得分:0)
由于您知道在运行开始时获得了多少线程,因此您可以定期检查当前运行的线程数,以查看nowThreadCount&lt; startThreadCount。如果它是真的终止当前线程。
PS:最简单的方法就是清除队列对象,但我在文档中找不到。