Friday 22 May 2020

Ping Scanner Part 2: Multi-Processing


by Vaggelis Atlasis

In my previous Blogspot, I constructed a "ping sweep" scanner in Python, using the Scapy library. One of the limitations of the program was the amount of time it took the program to go through all the addresses in the subnet. This problem was addressed by using a multiprocessing library. 

The previous version of the code


Multiprocessing

To enable multiprocessing, I imported Pool from the library multiprocessing. Pool replaced the for loop that was previously used to go through the addresses in a subnet one by one. Instead, Pool contains a parameter where the number of parallel tasks which can be executed is defined. The .map function of Pool iterates through the list of the addresses, allocating each address to a separate task (in this case, the number of parallel tasks is 10). 

The code used to implement Pool in the program. 10 is the number of processes running simultaneously


As you may have noticed in the picture, one of the parameters (send_ping) was not on the previous program. send_ping is simply the code that creates the ping placed into a function; allowing us to input all of the code as a parameter.

The code for the function send_ping. Note that the parameter address is taken using the .map function which individually iterates through targets, separately picking out each network address. 

Parsing Arguments from the Command Line

In the case that the user wants to change the number of processes running simultaneously doing directly from the program can be quite tedious. Therefore, I imported ArugmentParser from the library argparse. Next, the variable values will receive arguments from the command line. In this example, this happens when the user uses -p or --processes along with an integer of the user's choice. Conveniently, validation is automated by the library so there is no need for me to validate the type of input. 

The code for parsing argument from the command line. If there is no input from the user, the default number of processes is 10 (Please click on the picture to magnify it). 




Finally, we set values.processes as the parameter of Pool. We use the variable values and the argument processes to refer to the value of this argument. Consequently, the number next to the argument corresponds to the number of processes running simultaneously. 

Updated code for the Pool function

Further Changes

For usability reasons, a while loop was inserted in the code to allow the user to input a valid IPv4 subnet/address as many times as it took for the input to be valid. Previously, the program would just exit if the input was invalid. The added loop makes the program more user friendly.

The program code so far (You can find the while loop in lines 21 - 27)

Next Steps

In the coming days/weeks I will develop the code for finding the hostnames for the IP addresses that I received a reply from in a specific subnet.


3 comments: