Skip to content
ImagineWorld

Parallel Processing

node_idnode-book_bash-shell-scripting-for-pentesters_chapter-07-parallel-processing
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleParallel Processing
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we will explore the powerful capabilities of parallel processing within the realm of Bash scripting. As tasks become more data-intensive and time-sensitive, leveraging parallelism can significantly enhance the efficiency and effectiveness of Bash scripts. This chapter is designed to progressively build your understanding and skills in parallel processing, starting with fundamental concepts and advancing to practical applications and best practices.

By the end of this chapter, you will have a comprehensive understanding of how to harness the power of parallel processing in Bash scripts, enabling you to handle tasks more efficiently and effectively in various cybersecurity and data processing scenarios.

In this chapter, we’re going to cover the following main topics:

  • Understanding parallel processing in Bash
  • Implementing basic parallel execution
  • Advanced parallel processing with xargs and GNU parallel
  • Practical applications and best practices

The code for this chapter can be found at https://github.com/PacktPublishing/Bash-Shell-Scripting-for-Pentesters/tree/main/Chapter07.

Parallel processing in Bash involves executing multiple tasks simultaneously, rather than sequentially, to improve efficiency and reduce execution time. This concept is particularly useful in scenarios where tasks are independent of each other and can be performed concurrently. Understanding the foundational principles of parallel processing is crucial for effectively leveraging this technique in Bash scripting.

This section will cover the basics of parallel processing, including its benefits and drawbacks. So, let’s begin with understanding some of the key concepts of parallel processing, which are as follows:

  • Serial execution: Tasks are executed one after another in a sequence. Each task must be completed before the next one begins. This approach is straightforward but can be time-consuming for large or complex tasks.
  • Parallel execution: Multiple tasks are executed at the same time, independently of each other. This can significantly reduce the overall execution time, especially for tasks that can run concurrently without dependencies.
  • Concurrency versus parallelism: Concurrency refers to the ability to handle multiple tasks by switching between them, giving the illusion that they’re running simultaneously. Parallelism involves actually running multiple tasks simultaneously, typically utilizing multiple CPU cores.
  • Separate processes: In Bash, parallel tasks are typically executed as separate processes. Each process runs independently, with its own memory space.
  • Background processes: Running tasks in the background allows the shell to execute other commands while the background task continues to run. This is a common technique for achieving parallelism in Bash.

The benefits of parallel processing include the following:

  • Improved performance: By utilizing multiple processors or cores, parallel processing can speed up the execution of scripts, making them more efficient
  • Resource utilization: Parallel processing allows for better utilization of system resources, such as CPU and memory, by distributing the workload across multiple processes
  • Scalability: Scripts that use parallel processing can handle larger datasets and more complex tasks without a linear increase in execution time

There are drawbacks to parallel processing. They are as follows:

  • Complexity: Writing and debugging parallel scripts can be more complex than serial scripts due to the need for synchronization and coordination between tasks
  • Resource exhaustion: Multiple processes may compete for the same resources (e.g., CPU, memory), which can lead to contention and reduced performance if not managed properly
  • Error management: Managing errors in parallel tasks can be challenging, as failures in one task may not immediately impact others, making it harder to detect and handle issues

By understanding these fundamental concepts, you will be well-equipped to explore and implement parallel processing techniques in Bash, enhancing their scripts’ performance and efficiency.

So far, this chapter has been completely theoretical. This section will dive into the practical side and teach you how to implement basic parallel processing in Bash. Practical examples will be used to help you understand and learn this topic.

In Bash scripting, the ability to run commands or scripts in the background is a fundamental aspect of parallel processing. When a process is sent to the background, it allows the user to continue other work in the foreground. This is especially useful in a cybersecurity context where certain tasks such as network scans or data monitoring need to run continuously without tying up the terminal.

The simplest way to send a process to the background in Bash is by appending an ampersand (&) to the end of a command, as in this example:

$ ping google.com &

This command starts pinging google.com and immediately returns the command prompt to the user, allowing further commands to be entered without waiting for the ping process to finish.

Once a process is running in the background, it’s managed by the shell without any user interface. However, Bash provides several commands to manage these background processes:

  • jobs: Lists all current background processes running in the current shell session.
  • fg: Brings a background process to the foreground. You can specify a job using its number (e.g., fg %1 brings the first job back to the foreground).
  • bg: Resumes a paused background process, keeping it in the background.

For instance, imagine you started a script that captures network packets and sent it to the background:

$ sudo tcpdump -i eth0 -w packets.cap &

You can list this process with jobs, pause it with kill -s STOP %1, and resume it with bg %1.

Here’s an example of running this command:

Figure 7.1 – An example of controlling jobs

Background processes are extremely useful in cybersecurity for tasks that are time-consuming and do not require immediate interaction, such as the following:

  • Long-term monitoring: Setting a network monitoring tool to run in the background to log traffic patterns or detect anomalies over time
  • Automated scripts: Running custom scripts that periodically check system logs or scan directories for changes without blocking access to the terminal

Here’s a simple script that monitors the system logs for specific security events, running in the background. You can find the script in this chapter’s folder in the book’s GitHub repository as ch07_background_1.sh:

#!/bin/bash
grep -i "failed password" /var/log/auth.log > /tmp/failed-login-attempts.log &

This script filters the authentication log for failed login attempts and outputs the results to a temporary file, all while running in the background.

While background processing is a powerful tool, it should be used judiciously, keeping in mind the following aspects:

  • Monitor resource usage: Background processes consume system resources. Use tools such as top or htop to monitor resource usage and ensure that background tasks do not adversely affect system performance.
  • Use nohup for unattended tasks: If you start a background process and then log out, the process will terminate unless you use nohup to allow it to continue running: $ nohup ./ your-script.sh &.
  • Error handling: Redirect error messages to a file or a logging service to keep track of any issues that might occur during the execution of background processes.

Using background processes effectively allows pentesters to perform multiple tasks simultaneously, enhancing productivity and efficiency. By understanding and implementing the techniques discussed, you can optimize your Bash scripts for parallel processing tasks, essential in the field of cybersecurity.

In Bash, you can parallelize loops by running iterations in the background using &, and then synchronizing them with wait. This method is particularly useful when the tasks within each iteration do not depend on the completion of others.

Here’s a basic example that can be found in this chapter’s folder in the book’s GitHub repository as ch07_background_2.sh:

#!/usr/bin/env bash
for i in {1..5}; do
echo "Processing item $i"
sleep 1 &
done
wait
echo "All processes complete."

In this example, sleep 1 & simulates a task being processed in the background. The wait command is used after the loop to ensure that the script waits for all background processes to complete before moving on.

This example script for scanning multiple IP addresses concurrently can be found in the book’s GitHub repository as ch07_background_3.sh:

#!/usr/bin/env bash
ips=("192.168.1.1" "192.168.1.2" "192.168.1.3")
for ip in "${ips[@]}"; do
nmap -sS "$ip" > "scan_$ip.txt" &
done
wait
echo "Scanning complete."

Each nmap scan runs in the background, and scan_$ip.txt captures the output. Once all scans are initiated, wait ensures that the script only proceeds once all scans are complete.

Simple parallel loops with & and wait in Bash provide a straightforward way to implement parallel processing for repetitive tasks, particularly useful in cybersecurity for tasks such as network scanning or log processing.

Up to this point, we have been using very basic parallel processing using built-in Bash features. The next section will demonstrate how to use xargs and GNU parallel for more advanced parallel processing.

Advanced parallel processing with xargs and GNU parallel

Section titled “Advanced parallel processing with xargs and GNU parallel”

This section will jump ahead from the basic, and therefore, limited background processing you have seen thus far. You will learn more robust parallel processing with the more capable xargs and Gnu parallel to implement performance-critical Bash code.

Introducing xargs for robust parallel processing

Section titled “Introducing xargs for robust parallel processing”

The xargs application is a powerful command-line utility in Linux. It is used to build and execute command lines from standard input. By default, xargs reads items from the standard input and executes the command specified, one or more times, with the input provided. This tool is particularly useful for handling a large number of arguments or for processing items in parallel to improve efficiency.

The basic syntax of xargs is as follows:

command | xargs [options] [command [initial-arguments]]

Here’s a simple example:

$ echo "file1 file2 file3" | xargs rm

In this case, xargs takes the output of echo (which lists three filenames) and constructs a command to remove those files, executing rm file1 file2 file3.

One of the most powerful features of xargs is its ability to execute commands in parallel using the -P option, which specifies the number of processes to run simultaneously. This can significantly speed up operations that can be performed independently.

Imagine you have a list of files to compress. Instead of compressing them one by one, you can use xargs to process them in parallel:

$ ls *.log | xargs -P 4 -I {} gzip {}

Here’s what each part of this command does:

  • ls *.log lists all .log files in the current directory
  • xargs -P 4 tells xargs to use up to four parallel processes
  • -I {} is a placeholder for the argument from the input (each filename)
  • gzip {} compresses each file listed by ls

This command will compress up to four log files simultaneously, making the operation much faster than processing each file sequentially.

In cybersecurity, xargs is extremely useful for parallelizing tasks such as scanning multiple hosts, analyzing large sets of log files, or executing commands across many systems. Here’s an example of using xargs for parallel network scanning:

$ cat hosts.txt | xargs -P 5 -I {} nmap -sS -oN {}_scan.txt {}

This command does the following:

  • cat hosts.txt reads a list of hostnames or IP addresses from the hosts.txt file
  • xargs -P 5 runs up to five parallel instances of the following command
  • -I {} inserts the hostname or IP address from hosts.txt into the command
  • nmap -sS -oN {}_scan.txt {} runs an nmap scan on each host, saving the output to a file named after the host

Managing output from parallel processes can be tricky. Here are a few tips:

  • Separate output files: As shown in the examples, direct each command’s output to a unique file
  • Combine outputs: Use cat or similar tools to combine output files after processing
  • Logging: Redirect both standard output and error to log files for each process to ensure you capture all relevant information, as shown in the
    cat hosts.txt | xargs -P 5 -I {} sh -c 'nmap -sS {} > {}_scan.txt 2>&1'

The xargs command is a versatile tool that can greatly enhance the efficiency of your Bash scripts by enabling parallel execution. Its ability to handle large numbers of arguments and process them in parallel makes it invaluable for various cybersecurity tasks, from network scanning to log file analysis. By mastering xargs, you can significantly reduce the time required for many repetitive tasks, improving both productivity and effectiveness in your cybersecurity operations.

Before diving into the usage of GNU parallel, ensure that it is installed on your system. On most Linux distributions, you can install it using the package manager. For example, on Debian-based systems, use the following:

$ sudo apt-get update && sudo apt-get install parallel

GNU parallel allows you to run commands in parallel by reading input from standard input, files, or command-line arguments:

$ parallel echo ::: A B C D

Here is an explanation:

  • parallel: The command to invoke GNU parallel
  • echo: The command to be executed in parallel
  • :::: A separator indicating the start of input values from the command line
  • A B C D: The input values that will be processed in parallel

In this example, GNU parallel runs the echo command four times concurrently, each time with one of the input values (A, B, C, D).

GNU parallel shines when dealing with more complex tasks, such as processing files or executing scripts on multiple targets. Suppose you have a directory with multiple text files and you want to count the number of lines in each file simultaneously, use the following command:

$ ls *.txt | parallel wc -l

Here is an explanation:

  • ls *.txt: Lists all text files in the current directory
  • | parallel: Pipes the list of files to GNU parallel
  • wc -l: The command to count the lines in each file

Here, GNU parallel runs wc -l on each file concurrently, significantly speeding up the process compared to running the command sequentially.

GNU parallel can handle more complex scenarios involving scripts and multiple input arguments. Imagine you have a scan.sh script that performs network scans, and you need to run this script on multiple IP addresses. The following code demonstrates basic parallel usage:

$ cat ips.txt | parallel ./scan.sh

Here is an explanation:

  • cat ips.txt: Outputs the contents of ips.txt, which contains a list of IP addresses
  • | parallel: Pipes the list of IP addresses to GNU parallel
  • ./scan.sh: The script to be executed on each IP address

In this example, GNU parallel runs scan.sh for each IP address listed in ips.txt concurrently, enhancing the efficiency of your network scanning operations.

GNU parallel offers advanced options for controlling the number of concurrent jobs, handling input from multiple sources, and managing output.

You can limit the number of jobs running simultaneously using the - j option:

$ cat ips.txt | parallel -j 4 ./scan.sh

Here, -j 4 limits the number of concurrent jobs to 4. This command ensures that no more than four instances of scan.sh run at the same time, which can be useful for managing system resources.

Parallel can also handle multiple input sources, enabling more complex workflows:

$ parallel -a ips.txt -a ports.txt ./ch07_parallel_1.sh

Here is an explanation:

  • -a ips.txt: Specifies ips.txt as an input file
  • -a ports.txt: Specifies ports.txt as another input file
  • ./scan.sh: The script to be executed with combined inputs

Here, parallel combines inputs from both ips.txt and ports.txt, running scan.sh with pairs of IP addresses and ports. In the ch07_parallel_1.sh script, the input from ips.txt and ports.txt are referenced as positional variables:

#!/usr/bin/env bash
IP_ADDRESS=$1
PORT=$2
echo "Scanning IP: $IP_ADDRESS on Port: $PORT"

This code can be found in the book’s GitHub repository as ch07_parallel_1.sh. Here’s the output:

Scanning IP: 192.168.1.1 on Port: 80
Scanning IP: 192.168.1.1 on Port: 443
Scanning IP: 192.168.1.1 on Port: 8080
Scanning IP: 192.168.1.2 on Port: 80
Scanning IP: 192.168.1.2 on Port: 443
Scanning IP: 192.168.1.2 on Port: 8080
Scanning IP: 192.168.1.3 on Port: 80
Scanning IP: 192.168.1.3 on Port: 443
Scanning IP: 192.168.1.3 on Port: 8080

Managing errors and outputs from parallel processes can be challenging, but parallel provides mechanisms to handle these scenarios, as shown here:

$ parallel ./scan.sh {} '>' results/{#}.out '2>' errors/{#}.err :::: ips.txt

Here is an explanation:

  • {}'>': Redirects standard output to a file. Note that the > character is quoted. Other special shell characters (such as *, ;, $, >, <, |, >>, and <<) also need to be put in quotes, as they may otherwise be interpreted by the shell and not given to parallel.
  • results/{#}.out: The file to store standard output, with {#} representing the job number.
  • 2>: Redirects standard error to a file.
  • errors/{#}.err: The file to store standard error, with {#} representing the job number.
  • :::: ips.txt: Specifies ips.txt as the input file. :::: is used to specify that the following arguments are filenames containing input items.

This command redirects the output and errors of each job to separate files, making it easier to review results and debug issues.

Input to GNU parallel can be specified in four different ways:

  • :::: Direct input list, parallel echo ::: A B C
  • ::::: Input from a file, parallel echo :::: ``input.txt
  • |: Standard input, cat input.txt | parallel echo
  • --arg-file or -a: Specify a file, parallel --arg-file input.txt echo

Keep in mind that multiple inputs can be specified. The following example includes multiple file and argument inputs:

$ parallel -a file1 -a file2 ::: arg1 arg2 :::: file3 :::: file4 command

Let’s break down this complex parallel command:

  1. -a file1 -a file2: The -a option specifies input sources. This tells parallel to read input lines from both file1 and file2. Each line from these files will be used as an argument to the command.
  2. ::: arg1 arg2: The ::: separator introduces command-line arguments. arg1 and arg2 are literal arguments that will be used in each job.
  3. :::: file3: The :::: separator introduces another input source. file3 will be read, and each of its lines will be used as an argument.
  4. :::: file4: Another input source, similar to file3. Each line from file4 will be used as an argument.
  5. command: This is the actual command that will be executed in parallel for each combination of inputs.

Here’s how parallel will process this command. It will create a job for each combination of the following:

  1. A line from file1
  2. A line from file2
  3. Either arg1 or arg2
  4. A line from file3
  5. A line from file4

For each of these combinations, it will execute command, substituting the arguments in order. The number of jobs that run simultaneously depends on the number of CPU cores available, unless specified otherwise.

Let’s create a real-world example where we use the parallel command to perform a series of automated security checks on multiple servers using different tools and configurations. This could be part of a pentesting or security audit exercise.

Here are the contents of the servers.txt file:

10.2.10.10
10.2.10.11

Here are the contents of the ports.txt file:

80,445
22,3389

Here are the contents of the scan_types.txt file:

quick
thorough

Here are the contents of the output_formats.txt file:

txt
json

Now, let’s create a script that will perform these security checks. You can find this file in the book’s GitHub repository as ch07_parallel_3.sh. The purpose of this script is to automate and parallelize a series of simulated security checks across multiple servers:

#!/usr/bin/env bash
perform_security_check() {
server="$1"
ports="$2"
scan_type="$3"
output_format="$4"
echo "Performing $scan_type security check on $server (ports: $ports) with $output_format output"
# Simulating nmap scan
nmap_options=""
if [ "$scan_type" == "quick" ]; then
nmap_options="-T4 -F"
else
nmap_options="-sV -sC -O"
fi
output_file="scan_${server//./}_${scan_type}_${output_format}.${output_format}"
nmap $nmap_options -p $ports $server -oN $output_file
# Simulating additional security checks
echo "Running vulnerability scan on $server" >> $output_file
echo "Checking for misconfigurations on $server" >> $output_file
echo "Performing brute force attack simulation on $server" >> $output_file
echo "Security check completed for $server. Results saved in $output_file"
echo "-----"
}
export -f perform_security_check
parallel -a servers.txt -a ports.txt :::: scan_types.txt :::: output_formats.txt perform_security_check

Here’s the partial output of running the script:

$ ./ch07_parallel_3.sh
Performing quick security check on 10.2.10.10 (ports: 80,445) with txt output
Security check completed for 10.2.10.10. Results saved in scan_1021010_quick_txt.txt
-----
Performing quick security check on 10.2.10.10 (ports: 80,445) with json output
Security check completed for 10.2.10.10. Results saved in scan_1021010_quick_json.json
-----
Performing thorough security check on 10.2.10.10 (ports: 80,445) with txt output
Security check completed for 10.2.10.10. Results saved in scan_1021010_thorough_txt.txt
-----
Performing thorough security check on 10.2.10.10 (ports: 80,445) with json output
Security check completed for 10.2.10.10. Results saved in scan_1021010_thorough_json.json
-----
Performing quick security check on 10.2.10.10 (ports: 22,3389) with txt output
Security check completed for 10.2.10.10. Results saved in scan_1021010_quick_txt.txt
-----
Performing quick security check on 10.2.10.10 (ports: 22,3389) with json output
Security check completed for 10.2.10.10. Results saved in scan_1021010_quick_json.json
-----

This command structure is particularly useful when you need to process data from multiple sources in combination, allowing for complex parallel processing tasks.

Now that you’ve been introduced to both xargs and parallel, I’ll explain in the next section when to choose one over the other.

What are the key differences between xargs and parallel and how do you know when either one is the right tool for the job? The following table should help you choose the right tool for the job:

AspectxargsGNU parallel
ExecutionSerial by default. Can run parallel with the -P option, but is less flexible.Designed for efficient parallel execution out of the box.
ComplexitySimpler, lightweight. Good for straightforward tasks.Feature-rich. Handles complex scenarios, job control, and load balancing.
Error handlingBasic. May stop on errors.Robust. Can continue despite failures.
AvailabilityInstalled by default on most Unix systems.Requires separate installation.

Table 7.1 – A comparison of xargs and parallel features

Having learned how Bash parallel processing works, in the next section, we’ll explore using these concepts in practical applications.

The screen command is a Linux utility that allows users to manage multiple terminal sessions within a single window. It’s particularly useful for running long processes, managing remote sessions, and achieving parallelism in Bash scripts.

Before proceeding, ensure you have screen installed by running the following command:

$ sudo apt update && sudo apt install -y screen

Here’s how you can use screen to run multiple tasks in parallel. You can find the code in the book’s GitHub repository as ch07_screen_1.sh:

perform_task() {
echo "Starting task $1"
sleep 5 # Simulating work
echo "Finished task $1"
}

The perform_task function simply sleeps for five seconds to simulate performing work.

The following code creates a new detached screen session named parallel_tasks:

screen -dmS parallel_tasks

The -d flag starts the session in detached mode, and m creates a new session.

for i in {1..5}; do
screen -S parallel_tasks -X screen -t "Task $i" bash -c "perform_task $i; exec bash"
done

The preceding for loop starts multiple tasks in separate screen windows. This command creates a new window within the parallel_tasks session. The -X flag sends a command to the session, screen creates a new window, -t sets the window title, and bash -c executes the specified command in the new window.

screen -S parallel_tasks -X windowlist -b

The preceding command waits for all windows in the session to close. It’s useful for synchronizing the completion of parallel tasks.

screen -S parallel_tasks -X quit

The preceding command terminates the entire screen session once all tasks are complete.

Now that we have a solid foundation on the use of xargs, parallel, and screen, let’s move on to the next section and look at some practical applications and review best practices for their use.

This section will further solidify your understanding of parallel processing in Bash by showing practical applications. This will be followed by best practices to help you get the most out of learning these concepts.

Practical applications of Bash parallel processing

Section titled “Practical applications of Bash parallel processing”

In this section, we will use examples to show the real-world usage of Bash parallel processing in pentesting.

The first example uses GNU parallel for SQL injection testing, as shown in the following code:

#!/usr/bin/env bash
urls=("http://example.com/login.php" "http://test.com/index.php" "http://site.com/search.php")
echo "${urls[@]}" | parallel -j 3 'sqlmap -u {} --batch --crawl=2'
echo "All SQL injection tests completed."

The code can be found in the book’s GitHub repository as ch07_parallel_2.sh. Here’s an explanation:

  • urls is an array of URLs to test
  • echo "${urls[@]}" outputs the list of URLs
  • parallel -j 3 'sqlmap -u {} --batch --crawl=2' runs sqlmap on each URL with up to three concurrent jobs

The next example shows how to do network TCP port scanning in parallel, as shown here:

#!/usr/bin/env bash
ips=$(seq 1 254 | awk '{print "192.168.1." $1}')
echo "$ips" | xargs -n 1 -P 10 -I {} bash -c 'nmap -sP {}'
echo "Network scan completed."

The code can be found in the book’s GitHub repository as ch07_xargs_1.sh. Here’s an explanation:

  • seq 1 254 | awk '{print "192.168.1." $1}' generates IP addresses from 192.168.1.1 to 192.168.1.254.
  • echo "$ips" outputs the list of IPs.
  • xargs -n 1 -P 10 -I {} bash -c 'nmap -sP {}' runs nmap ’s ping scan (-sP) on each IP, with up to 10 parallel jobs. The -n 1 option tells xargs to use, at most, one argument per command line. In this context, it means that xargs will run the nmap command once for each IP address or hostname it receives as input.

While the preceding is an example of performing port scanning in parallel, nmap already has this capability. Therefore, let’s explore how to do this in Bash. You may find yourself in a shell on a system you have exploited and can’t install tools such as nmap for one reason or another so you should be prepared to use the system as a pivot into other networks.

The following Bash script has no external dependencies and scans for live hosts, then port-scans the top 100 TCP ports. It’s not nearly as fast as it could be if xargs or parallel were used. Just keep in mind that, someday, you’ll need something that doesn’t require any external dependencies and you can’t be assured that xargs and parallel will always be available. This script should work anywhere with Bash and the ping application:

#!/usr/bin/env bash
IP_RANGE="10.2.10.{1..20}"
PORTS=(21 22 23 25 53 80 110 143 443 587 3306 3389 5900 8000 8080 9000 49152 49153 49154 49155 49156 49157 49158 49159 49160 49161 49162 49163 49164 49165 49166 49167 49168 49169 49170 49171 49172 49173 49174 49175 49176 49177 49178 49179 49180 49181 49182 49183 49184 49185 49186 49187 49188 49189 49190 49191 49192 49193 49194 49195 49196 49197 49198 49199 49200 49201 49202 49203 49204 49205 49206 49207 49208 49209 49210 49211 49212 49213 49214 49215 49216 49217 49218 49219 49220 49221 49222 49223 49224 49225 49226 49227 49228 49229 49230 49231)
LIVE_HOSTS=()
for IP in $(eval echo $IP_RANGE); do
if ping -c 1 -W 1 $IP > /dev/null 2>&1; then
LIVE_HOSTS+=($IP)
fi
done
scan_ports() {
local IP=$1
for PORT in "${PORTS[@]}"; do
(echo >/dev/tcp/$IP/$PORT) > /dev/null 2>&1 && echo "$IP:$PORT"
done
}
# Export the function to use in subshells
export -f scan_ports
# Loop through live hosts and scan ports in parallel
for IP in "${LIVE_HOSTS[@]}"; do
scan_ports $IP &
done
echo "Waiting for port scans to complete…"
wait

The code can be found in the book’s GitHub repository as ch07_no_dependencies_scan.sh. Here’s an explanation:

  • #!/usr/bin/env bash: The usual shebang that we’ve covered in earlier chapters. This basically tells the shell what program to use to execute the following code.
  • IP_RANGE: Defines the range of IP addresses to scan using brace expansion ({1..20}), which denotes the last octet ranging from 1 to 20 for the base IP 192.168.1.
  • PORTS: An array holding the nmap top 100 TCP ports.
  • LIVE_HOSTS: An empty array to store the IP addresses of live hosts that respond to pings.
  • for IP in $(eval echo $IP_RANGE): Iterates through the expanded list of IP addresses.
  • ping -c 1 -W 1 $IP > /dev/null 2>&1: Sends one ICMP echo request (-c 1) with a 1-second timeout (-W 1) to check whether the host is up. The output is redirected to /dev/null to suppress it.
  • LIVE_HOSTS+=($IP): Adds the IP address to the LIVE_HOSTS array if the host is up.
  • scan_ports $IP: A function that takes an IP address as an argument.
  • (echo >/dev/tcp/$IP/$PORT) > /dev/null 2>&1: Attempts to open a TCP connection to the specified port on the IP address. If successful, it prints the IP address and port.
  • Export the function: Using export -f scan_ports allows the function to be used in subshells.
  • for IP in "${LIVE_HOSTS[@]}": Iterates through the list of live hosts.
  • scan_ports $IP &: Calls the scan_ports function in the background for each IP address, allowing concurrent execution.
  • wait: Waits for all background jobs to complete before exiting the script.

The script checks 20 consecutive IP addresses for live hosts and then scans the top 100 TCP ports and completes in 10 seconds on my system:

Figure 7.2 – A Bash TCP port scanner that should work on any system

Here’s an example of downloading multiple files in parallel:

$ parallel -j 3 wget ::: http://example.com/file1 http://example.com/file2 http://example.com/file3

Here is the explanation:

  • parallel -j 3: Executes three parallel jobs
  • wget :::: The three URLs following the series of colon characters are the input

This command downloads three files concurrently using wget.

Best practices for parallel execution in Bash

Section titled “Best practices for parallel execution in Bash”

This section explores best practices for using xargs and parallel to execute tasks concurrently, leveraging the full potential of your system’s resources.

The following are the best practices for parallel execution:

  • Determine the optimal number of jobs: The ideal number of parallel jobs depends on your system’s CPU and memory capacity. Start with the number of CPU cores and adjust based on performance. If you don’t specify a number of jobs, the defaults are one job for xargs and one job per CPU core for GNU parallel.
  • Monitor resource usage: Use tools such as htop or vmstat to monitor CPU and memory usage during parallel execution, ensuring your system remains responsive. See the man entry for these tools for examples.
  • Make a dry run: You can check what will be run with parallel by including the -- dry-run option.
  • Handle errors gracefully: Both xargs and GNU parallel can capture and log errors. Use these features to identify and debug issues without halting the entire process.
  • Redirect output appropriately: Redirect the output of each job to separate files or a log system to avoid interleaved and confusing outputs.
  • Use meaningful job names: When using GNU Parallel, you can assign meaningful names to jobs to easily track their progress.

Parallel execution with xargs and GNU parallel can vastly improve the efficiency of Bash scripts, particularly in cybersecurity and pentesting tasks. By following best practices such as optimizing job numbers, monitoring resources, handling errors, and managing output, you can harness the full potential of parallel processing to enhance your scripts and workflows.

In this chapter, we learned about parallel processing techniques in Bash scripting. This helped you gain knowledge on the basics of parallel execution using background processes and job control. We also learned about advanced parallel processing using tools such as xargs and GNU parallel and covered managing errors and output in parallel tasks. The chapter also covered applying parallel processing to pentesting workflows.

This chapter will help you significantly speed up tasks that involve processing large amounts of data or executing multiple commands simultaneously. Parallel processing can greatly reduce the time required for network scans, brute-force attacks, or analyzing multiple targets concurrently. Understanding how to manage parallel tasks helps in creating more efficient and robust scripts for various pentesting scenarios. The skills learned can be applied to optimize resource usage and improve overall productivity during security assessments.

By mastering parallel processing in Bash, pentesters can create more powerful and efficient scripts, allowing them to handle complex tasks and large-scale assessments more effectively.

In the next chapter, we dive into Part 2, where we put all of the Bash goodness that you’ve learned to work for a pentest.