[英]Python3 threading, trying to ping multiple IPs/test port simultaineously
下面的完整(无效)代码
完整的(有效的,无线程的)代码在这里: http : //pastebin.com/KUYzNtT2
我编写了一个小脚本,该脚本执行以下操作:
这工作正常,但是我想实现线程化以使脚本运行得更快。 因为我要扫描的IP数以千计,所以要花很多时间。
我玩过线程教程,但是似乎无法掌握如何在脚本中实现它。
任何想法或建议,表示赞赏。
编辑:根据本指南,我朝另一个方向前进: http : //chriskiehl.com/article/parallelism-in-one-line/
现在,我运行程序,并得到: File "port_test.py", line 39, in display_results for (client, location, cidr) in results: ValueError: too many values to unpack (expected 3)
,我不明白为什么。 有什么想法吗?
**编辑:我想我弄清楚了它为什么失败,看起来像pool.map期望只有一个数据点。 如果仅查询DB而不是其他两列,则该程序将开始吐出数据(比以前快得多)。 因此,现在我需要弄清楚如何在结果中添加其他两列,然后对结果进行排序以使它们有意义(我认为这是没有道理的)
#! /usr/bin/python
# Import modules
import socket
import subprocess
import ipaddress
import mysql.connector
import configparser
import logging
import coloredlogs
from multiprocessing.dummy import Pool as ThreadPool
#logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.INFO)
coloredlogs.install(level='DEBUG')
coloredlogs.DEFAULT_LOG_FORMAT = '%(asctime)s -- %(message)s'
# read from the config file
config = configparser.ConfigParser()
config.read('config.ini')
db=config['mysql']
net=config['network']
port = int(net['port'])
# create the connection, connect, and setup the query
cnx = mysql.connector.connect(user=db['user'], database=db['database'], password=db['password'])
cursor = cnx.cursor()
query = ("select fw.net_cidr as cidr "
"from firewalls fw "
"left join clients c on c.id = fw.client_id "
"left join locations l on l.id = fw.location_id "
"where fw.net_cidr <> '' and c.active = '1' and fw.active = '1'")
cursor.execute(query)
results = cursor.fetchall()
def display_results(results):
# execute and display the results
for (cidr) in results:
logging.info("{} --> ".format(cidr))
try:
# Prompt the user to input a network address
net_addr = str(cidr)
# Create the network
ip_net = ipaddress.ip_network(net_addr)
# Get all hosts on that network
all_hosts = list(ip_net.hosts())
except ValueError as e:
logging.warning(e)
continue
# For each IP address in the subnet, test to see if port 3389 is open
for i in range(len(all_hosts)):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(.25)
result = sock.connect_ex((str(all_hosts[i]),port))
if result == 0:
logging.info(str(all_hosts[i]) + ": " + net['port'] + " is open")
else:
logging.debug(str(all_hosts[i]) + ": " + net['port'] + " is not open")
# make a pool of workers
pool = ThreadPool(4)
# ping the cidrs in their own thread
pool.map(display_results, results)
pool.close()
pool.join()
# close the database connection
cursor.close()
cnx.close()
最初获取所有数据并将其存储在Queue
。
创建一个连续运行直到Queue
为空的函数(即, while my_queue.empty() is False
。
抓住在所述第一对象Queue
与Queue
的get()
方法。
然后处理它。
初始化任意数量的线程,它们将一直执行到Queue
为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.