Python3 threading, trying to ping multiple IPs/test port simultaineously

2024/10/12 6:22:29

Full (non-working) code below

Full (working, w/o threading) code here: http://pastebin.com/KUYzNtT2

I've written a small script that does the following:

  1. Pull network information from a database
  2. Ping each IP in a cidr (ie - 192.168.0.0/24); if it's up, test to see if a certain port is open
  3. Display the results

This is working fine, but I'd like to implement threading to make the script run faster; as is I have thousands of IPs to scan and it takes forever.

I've played around with threading tutorials but can't seem to grasp how to implement it in my script.

Any thoughts or suggestions are appreciated.

EDIT: I went in a different direction based on this guide: http://chriskiehl.com/article/parallelism-in-one-line/

Now I run the program and get: File "port_test.py", line 39, in display_resultsfor (client, location, cidr) in results: ValueError: too many values to unpack (expected 3) and I don't understand why. Thoughts?

**EDIT: I think I figured out why it failed, looks like pool.map expects only one data point. If I only query the DB for CIDRs instead of the other two columns, the program starts spitting out data (MUCH faster than before). So now I need to figure out how to add the other two columns to the results, then sort the results to they make sense (there's no order to the results, which I suppose makes sense)

#! /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 resultsfor (cidr) in results:logging.info("{} --> ".format(cidr))try:# Prompt the user to input a network addressnet_addr = str(cidr)# Create the networkip_net = ipaddress.ip_network(net_addr)# Get all hosts on that networkall_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 openfor 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()
Answer

Grab all the data initially and store it in a Queue.

Create a function that runs continuously until the Queue is empty (i.e. while my_queue.empty() is False.

Grab the first object in the Queue with Queue's get() method.

Then process it.

Initialize as many threads as you want, they will execute until the Queue is empty.

https://en.xdnf.cn/q/118230.html

Related Q&A

How to print a list of numbers without square brackets?

Im generating a list of random digits, but Im struggling to figure out how to output the digits in a single row without the square brackets?import random def generateAnswer(answerList):listofDigits =…

How to save plotly offline by running my script

I am using below code in my jupyter notebook.import pandas as pd import numpy as np %matplotlib inlinefrom plotly import __version__ from plotly.offline import download_plotlyjs, init_notebook_mode, pl…

Same output of the Keras model

I have a Keras model for predicting moves in the game. I have an input shape of (160,120 ,1). I have the following model with an output of 9 nodes:from keras.models import Sequential from keras.layers.…

Extract common element from 2 tuples python [duplicate]

This question already has answers here:Find intersection of two nested lists?(21 answers)Is there a way to get the difference and intersection of tuples or lists in Python? [duplicate](1 answer)Close…

How to make an integer index row?

I have a DataFrame: +-----+--------+---------+ | usn|log_type|item_code| +-----+--------+---------+ | 0| 11| I0938| | 916| 19| I0009| | 916| 51| I1097| | 916| 19| …

Matplotlib plt.plot with enumerate not working

import numpy as np import matplotlib.pyplot as plt array = np.array([[1,2,3,4,5,6],[10,20,30,40,50,60],[3,4,5,6,7,8],[100,200,300,400,500,600]])def plot(list):fig = plt.figure()ax = fig.add_subplot(11…

using complex conditions to form a pandas data frame from the existing one

Ive got the following dataframe containing function names, their arguments, the default values of the arguments and argument types:FULL_NAME ARGUMENT DEF_VALS TYPE function1 f1_arg1 NAN …

Crawl and scrape a complete site with scrapy

import scrapy from scrapy import Request#scrapy crawl jobs9 -o jobs9.csv -t csv class JobsSpider(scrapy.Spider): name = "jobs9" allowed_domains = ["vapedonia.com"] start_urls = [&qu…

Why is pip freezing and not showing a module, although pip install says its already installed?

Im following these instructions to install Odoo on Mac. It required that I install all the Python modules for the user like so: sudo pip install -—user -r requirements.txt(*A note about the --user par…

Flatten a list of strings which contains sublists

I have a list of strings which contains a sublist os strings:ids = [uspotify:track:3ftnDaaL02tMeOZBunIwls, uspotify:track:4CKjTXDDWIrS0cwSA9scgk, [uspotify:track:6oRbm1KOqskLTFc1rvGi5F, uspotify:track:…