Why bash Scripting for Hackers?
local graph
Chapter 1 — Why bash Scripting for Hackers?
Section titled “Chapter 1 — Why bash Scripting for Hackers?”As we begin our journey, a common question arises: why do hackers need bash scripting?
bash scripting is one of the most practical tools an ethical hacker can use. It helps automate repetitive tasks, save time during assessments, and make your workflow more reliable. In security testing, where timing and accuracy matter, being able to script your actions gives you a real advantage. This book, Linux Shell Scripting for Hackers, focuses on using bash in real hacking scenarios and shows how it can make your work faster, cleaner, and easier to repeat.
In this chapter, you’ll learn why bash scripting is such an important skill for ethical hackers. We’ll look at how automation improves both accuracy and speed, and how scripts let you run the same attacks and scans across multiple targets without extra effort.
You’ll also see how scripting fits into the different stages of a hacking process, with real-world examples.
We’ll discuss responsible scripting too because powerful tools can do damage if used carelessly. Understanding scope, safety checks, and ethical boundaries is just as important as writing good code. You’ll also learn a few tips for optimizing scripts so they run faster and use fewer resources.
Finally, we’ll lay the groundwork for writing our own bash scripts. You’ll explore the basic syntax, control structures, variables, and functions that form the backbone of every useful shell script.
The goal of this chapter is to give you a clear understanding of how bash scripting fits into ethical hacking. Once you understand these fundamentals, you’ll be ready to build your own scripts, automate routine work, and sharpen your skills as a hacker who truly understands the command line.
In this chapter, we are going to cover the following main topics:
- The power of automation for efficiency and accuracy
- Scaling your attacks through scripts
- How scripting improves the hacking process
- Ethical considerations – responsible scripting in hacking
- Optimizing scripts for speed and efficiency– performance tweaks
- bash fundamentals
Technical requirements
Section titled “Technical requirements”To follow along with the examples in this chapter, you will need the following:
- A Linux distribution installed, preferably Kali Linux or Parrot OS
- Reliable internet access
The code for this chapter is available in the book’s GitHub repository.
The power of automation for efficiency and accuracy
Section titled “The power of automation for efficiency and accuracy”Automation with scripts lets ethical hackers do more work in less time and avoid simple human mistakes. bash scripts are ideal for turning repetitive, time-consuming tasks into single commands you can run again and again, freeing you to focus on the tricky parts of an engagement.
A clear example is port scanning and reconnaissance. Scanning a handful of hosts by hand is tedious and easy to botch when you’re doing it repeatedly or across large ranges. If a basic ping sweep of five IPs takes a minute or two by hand, doing the same for 1,000 addresses could eat up hours and leave you tired and error-prone. A bash script can handle that same job in minutes, and it will produce consistent results every time.
Consider the following simple script that automates a TCP connect-like scan:
#!/bin/baship_list_file=$1# Check if the input file is providedif [ "$ip_list_file" == "" ]; then echo "You forgot to provide the input file name!" echo "Syntax: ./net-scan.sh <filename>" exit 1fi# Check if the input file existsif [ ! -f "$ip_file" ]; then echo "Error: The input file '$ip_list_file' does not exist!" exit 1fi# Read IP addresses from the file and process each onewhile IFS= read -r ip_address; do echo "Checking IP address: $ip_address" # Perform a single ping with a timeout of 1 second ping_result=$(ping -c 1 -w 1 "$ip_address" 2>&1) # Check if the ping result doesn't contain "Request timed out" if [[ ! $ping_result =~ "Request timed out" ]]; then echo "-------------------[HOST] $ip_address is live----------------" echo "Initiating Nmap scan..."
# Perform Nmap scan on the live host nmap -Pn -sC -sV -T4 $ip_address else echo "Host $ip_address is not reachable or timed out." fi echo "--------------------------------------"done < "$ip_list_file"It reads targets from a file, checks whether each host responds to a ping, and runs Nmap against live hosts. This turns an otherwise repetitive workflow into a repeatable process you can log, audit, and improve.
When run against a network of 1,000 IPs, this script can finish in roughly 10–15 minutes, depending on network latency, timeouts, and the machine running the scans. Compare that to the estimated three-plus hours of manual work: the time savings are obvious. Beyond saving time, the script removes human error and fatigue, producing consistent results you can trust.
The script also improves reconnaissance. It filters out inactive IPs so you don’t waste time scanning dead hosts, then launches Nmap against live targets to collect ports, service versions, and other useful details. That flow, discovery straight into a detailed scan, would be time-consuming and inefficient to do by hand. Because the script produces consistent, parseable output, you can feed results into other tools or analysis pipelines without extra work.
Scalability matters too. In real engagements, you’ll often face hundreds or thousands of devices, not a single host. Being able to run scripts that handle large target sets reliably makes the difference between a thorough assessment and one that misses things. Good scripts let you scale your checks while maintaining control over speed, logging, and safety.
Important note
If you don’t understand this code yet, don’t worry. We’ll cover these concepts in more detail in the bash fundamentals section later in this chapter.
Scaling your attacks through scripts
Section titled “Scaling your attacks through scripts”As an ethical hacker, you’ll often need to assess large networks or organizations with many targets. Running the same commands against each host by hand is slow and invites mistakes. With bash scripts, you can scale your assessments so they cover a wider attack surface while staying consistent and repeatable.
bash isn’t trying to replace specialized tools; it’s how you glue those tools together. The shell is available on almost every Unix-like system and makes it easy to chain commands, parse output, and automate multi-step tasks. That’s exactly what you need when an assessment requires several tools to run in sequence.
A common scenario is a large network scan. Manually mapping subnets and scanning dozens or hundreds of hosts across multiple ranges is slow, tedious, and easy to get wrong. A script can automate discovery, run deeper scans only against live hosts, and kick off follow-up checks (Server Message Block (SMB) enumeration, vulnerability scans, etc.) without you babysitting the process.
Below is a simple example that shows this idea in practice:
#!/bin/bash# Define the network range to scannetwork_range="192.168.1.0/24"# Perform a ping sweep to identify live hostslive_hosts=$(nmap -sn -oG - "$network_range" | awk '/Up/{print $2}')# Loop through the live hostsfor host in $live_hostsdo # Perform a comprehensive port scan nmap -sV -sC -p- -oN "$host.nmap" "$host" # Enumerate SMB shares enum4linux "$host" # Perform vulnerability scanning nessus_scan "$host"doneIt finds live hosts in a network range and runs a set of checks against each one. The code does the heavy lifting so you can focus on analysis and triage.
This script uses a few staple tools in your toolkit: Nmap for discovery and port scans, Enum4Linux for SMB enumeration, and Nessus for vulnerability checks. Chaining them in bash turns separate manual steps into a single automated workflow.
Let’s break down how this script scales your assessment:
- Network Discovery: The script uses Nmap to perform a ping sweep across an entire subnet, identifying all live hosts. This task alone could take hours if done manually.
- Port Scanning: For each live host, it conducts a comprehensive port scan. Manually performing this level of scanning on numerous hosts would be impractical.
- Service Enumeration: The script automatically enumerates SMB shares on each host, a task that’s crucial but time-consuming when done manually.
- Vulnerability Scanning: Finally, it launches a Nessus scan on each host, further automating the vulnerability assessment process.
Automating these stages doesn’t just save time. It lets you scale how many targets you examine, the depth of checks per target, and the consistency of results. You’ll get output that is structured and consistent across runs, which you can parse, log, and feed into other tools or reporting pipelines.
Beyond scaling, bash scripts help enforce a consistent methodology, reduce simple human mistakes, and make it easier to adapt workflows to different environments. You can also add logging, error handling, and report generation so your runs are auditable and reproducible.
Now let’s discuss how bash scripting can improve our overall hacking process.
How scripting improves the hacking process
Section titled “How scripting improves the hacking process”bash scripting plays a pivotal role in enhancing the overall hacking process, simplifying various stages, and ensuring a more efficient and effective approach. By automating repetitive tasks and incorporating robust scripts into your workflows, you can optimize your entire hacking process, reducing the risk of human error and maintaining a consistent and reproducible methodology.
During the reconnaissance phase, scripting can significantly improve the information-gathering process. For instance, consider a scenario where you need to perform subdomain enumeration for a target organization. Manually checking for subdomains quickly leads to fatigue and missed results, especially when dealing with large organizations or complex domain structures. Consider the following example:
#!/bin/bash# Define the target domaintarget_domain=$1# Use various subdomain enumeration techniquesecho "################### ASSETFINDER INITIATED ###############"assetfinder --subs-only "$target_domain" | sort -u >> "$target_domain.domains.txt"echo "################### GOBUSTER INITIATED ###############"gobuster_d=$(gobuster dns -d "$target_domain" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt)# Cleaning gobuster outputecho "Cleaning GOBUSTER output..."echo "$gobuster_d" | grep "Found" | cut -d ' ' -f 2 | sort -u >> "$target_domain.domains.txt"# Remove duplicate entries and save resultssort -u "$target_domain.domains.txt" -o "$target_domain.domains.txt"In this example, we used popular subdomain enumeration tools like assetfinder and gobuster to identify potential subdomains associated with the target domain. By automating this process through a script, you can efficiently gather comprehensive subdomain information, which can be used for further reconnaissance and targeting.
Ethical considerations – responsible scripting in hacking
Section titled “Ethical considerations – responsible scripting in hacking”Ethical hacking is a delicate balance between leveraging powerful tools and techniques to identify vulnerabilities and ensuring that these capabilities are used responsibly and within legal boundaries. When it comes to scripting, ethical hackers must exercise heightened vigilance and adhere to strict ethical principles to prevent misuse or unintended consequences.
One of the primary ethical considerations when scripting for hacking purposes is ensuring that the scripts are used strictly within the scope of authorized engagements. For example, a poorly designed script intended to test for SQL injection vulnerabilities could inadvertently delete or corrupt critical data, even if the hacker had permission to test the system. Similarly, scripts with logic flaws, such as improper input validation, can result in unintended system behavior, leading to service disruptions or data loss.
Additionally, even within authorized and legal bounds, ethical hackers must take care when scripting tasks to avoid causing adverse effects. Overly aggressive or resource-intensive scripts, such as those designed to automate vulnerability scanning or brute-force attempts, can inadvertently overwhelm system resources, degrade performance, or cause network outages. Careful scripting and thorough testing are essential to ensure that tools do not exceed their intended scope, minimizing any potential harm to the target system.
Here’s an example of how to include a safeguard within a script to prevent unauthorized targeting:
#!/bin/bash# Check if target IP is in the list of authorized targetsAUTHORIZED_IPS=("192.168.1.10" "10.0.0.5" "172.16.0.22")TARGET_IP=$1if [[ " ${AUTHORIZED_IPS[@]} " =~ " ${TARGET_IP} " ]]; then echo "Target IP is authorized. Proceeding with the script..." # Script logic goes hereelse echo "Error: Target IP is not authorized. Exiting..." exit 1fiIn this example, the script includes a check to ensure that the target IP address is present in a list of authorized targets before proceeding with any further actions. By implementing such safeguards within the script, ethical hackers can mitigate the risk of inadvertently targeting unauthorized systems and ensure compliance with the established rules of engagement.
Another critical ethical consideration is the responsible handling and storage of sensitive data obtained during hacking engagements. Scripts that automate tasks such as data exfiltration or credential harvesting must incorporate robust security measures to protect the confidentiality and integrity of the collected data. Take a look at the following example:
#!/bin/bash# Encrypt and securely transfer collected datagpg --symmetric --cipher-algo AES256 collected_data.zipscp collected_data.zip.gpg secure_server:/encrypted_data/# Securely delete local copiesshred -zuv collected_data.zipThe above script ensures the responsible handling of collected data by encrypting it using strong encryption algorithms (for example, AES-256) and securely transferring the encrypted data to a designated server. Additionally, the script implements secure data deletion techniques to remove local copies of the sensitive data, further mitigating the risk of unauthorized access or data breaches.
Ethical considerations are paramount when it comes to hacking, and scripting is no exception. By adhering to strict ethical principles, implementing robust security measures, and incorporating appropriate safeguards within your scripts, you can make use of the power of automation while maintaining the highest standards of responsible and ethical conduct.
Optimizing scripts for speed and efficiency – performance tweaks
Section titled “Optimizing scripts for speed and efficiency – performance tweaks”Optimizing scripts for speed and efficiency matters in ethical hacking. Quicker runs mean faster results, and lower resource use reduces the chance of impacting a target or your own tools. By tuning scripts and using the shell smartly, an ethical hacker can cut execution time, use CPU cores more effectively, and keep scans from slowing everything down.
One common optimization technique is to make use of built-in shell features and external tools to execute tasks in parallel, taking advantage of modern multi-core processors and maximizing CPU utilization. This approach can significantly reduce the overall execution time for tasks that can be parallelized:
#!/bin/bash# Define the list of target hoststargets=("192.168.1.101" "192.168.1.102" "192.168.1.103")# Function to perform port scanningport_scan() { local target_ip=$1 nmap -p- --open -oG - "$target_ip" | awk '/open/{print $1}' | cut -d'/' -f1 | tr '\n' ',' | sed 's/,$//' > "$target_ip.ports"}# Execute port scans in parallel using GNU Parallelexport -f port_scanparallel --jobs 50% port_scan ::: "${targets[@]}"In this example, the script utilizes GNU Parallel to execute port scans on multiple target hosts concurrently. By efficiently making use of the available CPU cores, the overall execution time for scanning multiple hosts can be significantly reduced compared to a sequential approach.
However, it’s important to note that parallelization isn’t the only way to optimize your scripts. You can also leverage tools that have asynchronous execution built into their design. For instance, when it comes to port scanning, you might consider using Masscan instead of Nmap in scenarios where speed is critical. Here’s how you could modify the script to use Masscan:
#!/bin/bash# Define the list of target hoststargets=("192.168.1.101" "192.168.1.102" "192.168.1.103")# Function to perform port scanning with Masscanmasscan_port_scan() { local target_ip=$1 masscan -p1-65535 --rate=1000 "$target_ip" --output-format list | awk '{print $3}' | cut -d'/' -f1 | sort -n | tr '\n' ',' | sed 's/,$//' > "$target_ip.ports"}# Execute Masscan port scansfor target in "${targets[@]}"; do masscan_port_scan "$target" &done# Wait for all background jobs to completeWaitIn this modified version, we’re using Masscan, which is designed for rapid scanning. Masscan uses asynchronous transmission, allowing it to send packets much faster than traditional scanning tools. By default, it is asynchronous and optimized for speed, making it an excellent choice when you need to scan large networks quickly.
The & at the end of the masscan_port_scan call in the loop launches each scan in the background, effectively running them in parallel. The wait command at the end ensures the script doesn’t terminate until all background jobs are complete.
Another key way to speed up scripts is to avoid doing the same work twice. You can do this by caching results, skipping repeated computations, and trimming any steps that don’t add value. A simple caching mechanism can make a big difference in both time and system load, especially when dealing with repetitive tasks like subdomain enumeration. In the following example, the get_subdomains function checks for a cached results file before running. If the cache exists, it simply reads and returns the data. If not, it performs the enumeration, saves the results, and uses them for future runs. This keeps your workflow fast and prevents wasting time redoing work you’ve already completed.
#!/bin/bash# Function to retrieve subdomains (with caching)get_subdomains() { local domain=$1 local cache_file="$domain.subdomains.cache" # Check if the cache file exists if [ -f "$cache_file" ]; then cat "$cache_file" return fi # Perform subdomain enumeration and cache the results subdomains=$(subfinder -d "$domain" -silent | sort -u) subdomains+=" $(assetfinder --subs-only "$domain" | sort -u)" subdomains+=" $(amass enum -d "$domain" -silent)" subdomains=$(echo "$subdomains" | tr ' ' '\n' | sort -u) echo "$subdomains" > "$cache_file" echo "$subdomains"}# Retrieve subdomains (cached if available)target_domain="example.com"subdomains=$(get_subdomains "$target_domain")Optimizing scripts for speed and efficiency is an essential aspect of ethical hacking, as it ensures that valuable resources are utilized effectively and that operations are executed in a timely and efficient manner. By implementing techniques such as parallelization and caching, you can create efficient and high-performing scripts, maximizing their impact while minimizing resource utilization.
To finish this chapter, let’s discuss the fundamentals of bash scripting.
bash fundamentals
Section titled “bash fundamentals”bash, short for Bourne-Again SHell, is the standard command interpreter on most Unix-like systems, including Linux. It’s both a shell and a scripting language that lets you automate commands, process data, and build reusable tools.
For ethical hackers and IT professionals, understanding bash fundamentals is essential. It forms the backbone of automating tasks, simplifying workflows, and building scripts that save time during security assessments or system administration.
In this section, you’ll learn the core building blocks of bash scripting, how to create your first script, use variables, add comments, and apply command substitution. These basics form the foundation for every advanced script you’ll write later in the book.
Create your first bash script
Section titled “Create your first bash script”To create a new bash script, use the following steps:
- Open a text editor and create a new file with a
.shextension, for example,my_script.sh. Then, add the following line of code:#!/bin/bashecho "Hello, World!" - Save the file and exit the text editor.
- Next, open a terminal and navigate to the directory where you saved the script using the
cdcommand. For example, if you saved the script in your home directory, you can usecd ~.
Once you’re in the correct directory, you need to make the script executable by running the following command:
chmod +x my_script.shThis command grants execute permissions to the script file.
- Now, you can run the script by typing:
./my_script.sh
You should see the output Hello, World! printed in the terminal.
You can also run your script by typing:
bash my_script.shThis doesn’t require you to grant execute permissions on the script.
shebang
Section titled “shebang”You might have noticed that every bash script we’ve written begins with the line #!/bin/bash. This line is known as the shebang or hashbang. It serves as an interpreter directive, informing the operating system which interpreter should be used to execute the script. In this case, #!/bin/bash specifies that the bash shell should be used to run the script.
For instance, if you were to run your script using the Zsh interpreter instead of bash, your shebang line would look like this:
#!/bin/zshAdding your script to PATH
Section titled “Adding your script to PATH”While you can run your script by specifying the full path to the file (/path/to/my_script.sh), it’s more convenient to add the script to your system’s PATH so you can run it from any directory. Here’s how you can do that:
- Open your shell configuration file (e.g.,.
bashrcor.bash_profile) in a text editor. - Add the following line to the file, replacing
/path/to/scriptswith the actual path to the directory where you want to store your scripts:export PATH="$PATH:/path/to/scripts" - Save and close the file.
- Either restart your terminal or run
source ~/.bashrc(orsource ~/.bash_profile) to apply the changes.
After following these steps, you should be able to run your script by simply typing its name in the terminal, regardless of the current working directory.
bash variables
Section titled “bash variables”One of the foundational concepts in bash scripting is variables. In bash, like in any other programming language, a variable is a storage location that holds a value, which can be a string, number, or other data types. Think of variables as containers for data that you can reuse throughout your script or command-line session. They provide a way to label data with a descriptive name, making your scripts easier to understand and modify. Here is how you can declare and assign a value to a variable in bash:
#!/bin/bash# Assigning a value to a variabletarget_ip="192.168.1.100"In this example, we created a variable named target_ip and assigned it a value of 192.168.1.100. Once you have defined your variable, you can access its value by prefixing it with a dollar sign ($):
# Accessing the variable's valueecho "Scanning target IP: $target_ip"When declaring a variable in bash, it is important to follow these naming rules:
- Variable names can contain letters, numbers, and underscores.
- The first character must be a letter or underscore.
- Names are case-sensitive -
MYVARandmyvarwould be different variables. - Avoid using
bashreserved keywords as variable names. - For a full list of reserved words, refer to https://www.gnu.org/software/bash/manual/html_node/Reserved-Words.html
When declaring variables, there should be no spaces between the variable name and the equal sign, or between the equal sign and the variable value.
This will throw a command not found error:
target_ip= "192.168.1.100"Now that we’ve covered how to define and use variables in bash, let’s move on to the next important concept – bash comments.
Comments
Section titled “Comments”Like any programming language, bash scripts support writing comments to document your code. Comments are useful for explaining sections of your script, leaving notes for yourself or other developers, or commenting out debug code.
bash scripting supports two types of comments:
- Single-line (in-line) comments
- Multi-line comments
Single line comments start with a hash/pound symbol (#). Any text after the # on that line will be ignored by the bash interpreter:
# This is a single line commentecho "Hello World" # This line will print Hello WorldTo ensure clarity, single-line comments should be placed on their own line.
bash does not have a dedicated syntax for multi-line comments. However, you can achieve the same effect by using single-line comments on consecutive lines or by taking advantage of:
:' or :" syntaxHeredocsHere is a an example of using :' syntax::'This is a multi-linecomment using the:' 'syntax'This allows you to create a multi-line string that is immediately discarded, effectively creating a comment block. You can also replace the :' with :" and still get the same results.
As mentioned, you can also create multi-line comments using heredocs. heredocs provide a more structured way to create multi-line comments in bash scripts. This technique uses a delimiter (typically <<COMMENT) to mark the start of the comment block and a matching delimiter (COMMENT) to mark the end. Here’s an example:
<<COMMENTThis is a multi-linecomment in Bashusing heredocsCOMMENTAnything between <<COMMENT and COMMENT will be ignored by bash as a comment. The delimiter COMMENT can be replaced with any text as long as the starting and ending delimiters match.
While heredocs are commonly used for creating multi-line comments, they also serve another important purpose: defining multi-line strings without the need to escape newline characters. This functionality can be particularly useful when working with large blocks of text or data.
Command substitution
Section titled “Command substitution”Command substitution allows you to use the output of a command as an argument to another command or variable assignment. This functionality becomes invaluable when you need to dynamically set values based on system information or the results of external commands. Command substitution is a fundamental concept in shell scripting, and you will encounter its use frequently throughout this book.
There are two ways of doing command substitution:
$( )Using backticks \`\`.The first one is more common in bash scripts. Here is an example:
# Perform subdomain enumeration and store the resultssubdomains=$(subfinder -d "example.com" -silent | sort -u)echo -e " Found subdomains\n $subdomains"This runs the subfinder command, captures its output, and assigns it to the $subdomains variable. The $subdomains variable is then printed using the echo command.
Without command substitution, our code would look like this:
# Perform subdomain enumeration and store the resultssubdomains=subfinder -d "example.com" -silent | sort -uecho -e " Found subdomains\n $subdomains"This would print the literal string "subfinder -d "example.com" -silent | sort -u" rather than running it and capturing its output.
Functions
Section titled “Functions”Functions are an essential part of bash scripting. Just like functions in traditional programming languages, bash functions allow you to modularize your code by encapsulating sections of code with related functionality into reusable units, thereby reducing the amount of code and increasing readability.
To define a function in bash scripting, we use the function_name () syntax, followed by a block of commands enclosed in braces {}. Consider the following example:
#!/bin/bash# Function to perform a TCP connect scantcp_connect_scan() { local target_ip=$1 nmap -sT -p- --open --reason "$target_ip" | grep ^[0-9] | cut -d '/' -f 1 | tr '\n' ',' | sed 's/,$//'}# Function to scan for vulnerabilitiesscan_vulnerabilities() { local target_ip=$1 nikto -host "$target_ip" | tee "$target_ip.nikto"}# Scan target IP addressestargets=("192.168.1.101" "192.168.1.102")for target in "${targets[@]}"; do open_ports=$(tcp_connect_scan "$target") echo "Open ports on $target: $open_ports" scan_vulnerabilities "$target"doneIn this example, we define two functions: tcp_connect_scan to perform a TCP connect scan on a target IP address, and scan_vulnerabilities to scan for vulnerabilities using the Nikto tool. These functions are then called within a loop, iterating over a list of target IP addresses and executing the respective operations.
Control structures
Section titled “Control structures”Control structures are another essential element of bash scripting, allowing you to implement logic and conditionally execute code based on specific criteria:
#!/bin/bash# Check if a port is openport=80if nmap -p "$port" "$target_ip" | grep -q "open"; then echo "Port $port is open on $target_ip"else echo "Port $port is closed on $target_ip"fi# Loop through a list of IP addressesip_list=("192.168.1.101" "192.168.1.102" "192.168.1.103")for ip in "${ip_list[@]}"; do echo "Scanning $ip..." # Perform scanning or other operations on $ipdoneThis example showcases the use of an if statement to check if a specific port is open on a target IP address, and a for loop to iterate through a list of IP addresses, performing a set of operations on each one.
Until now, we have concentrated on writing and executing scripts from files. Now, let’s explore an alternative approach that allows us to execute scripts easily without needing a file.
One-liners and quick terminal scripting
Section titled “One-liners and quick terminal scripting”While we’ve focused on creating standalone scripts, bash shines in another crucial area for ethical hackers: one-liners. These are powerful, single-line commands executed directly in the terminal. They’re perfect for rapid tasks or for chaining multiple commands together.
Let’s explore some useful one-liners that showcase bash ‘s versatility in hacking scenarios:
- Finding all
setuidfiles in the system:sudo find / -perm /4000 -type f
This command searches the entire filesystem for files with the setuid bit set. These files can be potential security risks if they are misconfigured.
- Real-time system log monitoring:
tail -f /var/log/syslog | grep --color 'error\|warning'
Here, we’re continuously watching the system log for any lines containing “ error ” or “ warning.” The matching terms are highlighted for easy identification.
- Scanning open ports on a remote host:
for port in {1..65535}; do nc -zvw1 example.com $port 2>&1 | grep -v 'Connection refused'; done
This one-liner attempts to connect to every port on a specified host, reporting any that are open. It’s a basic port scanner in a single line of bash.
These examples demonstrate how complex tasks can be accomplished without creating separate script files. As you progress through this book, you’ll see how these techniques can be integrated into larger scripts or used on their own for quick, targeted actions.
By mastering these fundamental concepts and incorporating them into your bash scripts, you can create powerful and efficient tools to automate various tasks, streamline your ethical hacking workflows, and enhance the overall effectiveness of your security assessments.
Summary
Section titled “Summary”This first chapter gave us space to cover a lot: why automation matters, how to scale attacks with scripts, the role of scripting in reconnaissance and enumeration, ethics and safety, performance tweaks, and the bash basics you’ll use throughout the book. By now, you should have a solid sense of how bash fits into an ethical hacker’s toolbox.
In the next chapter, you’ll learn how to build a lab to practice safely. You’ll get an intro to Kali Linux and Metasploitable 2, a step-by-step install and configuration walk-through (physical or virtual), and a guide to automatically provisioning the lab using Vagrant so you can spin it up and tear it down reliably.
Questions
Section titled “Questions”- Why is automation considered a force multiplier for ethical hackers?
- It allows them to bypass firewalls automatically. 2. It saves time, reduces errors, and enables large-scale tasks. 3. It guarantees undetectable attacks. 4. It eliminates the need to learn manual techniques.
- Which of the following ensures a script is executed with the correct interpreter when run directly (for example,
./myscript.sh)?#start2.#runbash3.#!/bin/bash4.#!/usr/local/bin
- What happens if you declare a variable in
bashwith spaces around the equals sign, like this: var = 10?- The variable is not set to 10. In bash, spaces around the equals sign are not allowed when declaring variables.
2. It defaults to 0.
3. It throws a
command not founderror. 4. It automatically trims the spaces.
- The variable is not set to 10. In bash, spaces around the equals sign are not allowed when declaring variables.
2. It defaults to 0.
3. It throws a
- Which option below is a safe and ethical scripting practice?
- Running scripts against any IP you find online. 2. Encrypting sensitive data collected and securely transferring it. 3. Using scripts that overwhelm system resources to ensure results. 4. Using scripts that bypass authentication by default.
- What is the main benefit of using parallel execution in scripts (e.g., GNU Parallel)?
- It improves accuracy by running one command at a time. 2. It reduces the overall execution time by running tasks concurrently. 3. It avoids the need for variables. 4. It ensures scripts can run without user input.
- Which of the following is an example of command substitution in
bash?var=$(date)2.var=$(date)3.var=date4.var=date
- What’s the difference between running a script with.
/myscript.shversus bashmyscript.sh?./myscript.shrequires execute permissions, whilebash myscript.shdoes not. 2../myscript.shruns faster. 3.bash myscript.shignores errors. 4. There is no difference.
- Short Answer: Why should an ethical hacker add safeguards (such as an authorized IP list) to their scripts?
- Short Answer: Write a one-liner in
bashthat finds all files with thesetuidpermission bit set on a system.
Further reading
Section titled “Further reading”- GNU
bashManual (variables, control structures, and functions): https://www.gnu.org/software/bash/manual/bash.html - Nmap documentation: https://nmap.org/book/man.html
- Vulnerability Disclosure Cheat Sheett: https://cheatsheetseries.owasp.org/cheatsheets/Vulnerability_Disclosure_Cheat_Sheet.html
Answers
Section titled “Answers”- b
- c
- c
- b
- b
- a
- a
- To prevent accidentally or maliciously running the script against unauthorized targets, which could cause legal or ethical violations.
sudo find / -perm /4000 -type f