
Linux Shell Scripting for Hackers
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
- Build custom Linux command-line tools for penetration testing, log analysis, and network scripting
- Apply secure coding best practices to develop modular, maintainable hacking utilities
Book DescriptionLinux shell scripting is a foundational skill for ethical hackers and penetration testers who want to automate repetitive tasks and build powerful command-line tools. This practical guide shows you how to use bash scripting for cybersecurity automation, helping you streamline reconnaissance, exploitation, and post-exploitation workflows on Linux systems. You'll progress from advanced bash techniques to real-world penetration testing applications, learning how to automate reconnaissance processes, parse logs, extract indicators, and develop custom exploitation utilities. Using tools such as awk, sed, grep, and regular expressions, you'll manipulate data efficiently and craft scripts that solve real security challenges. A dedicated section on network scripting demonstrates how to build scripts that interact with remote systems, perform scanning tasks, and gather actionable information. You'll also explore system hardening automation and learn best practices for writing secure, modular, and maintainable shell scripts. By the end of this book, you'll have the confidence to integrate Linux shell scripting into your ethical hacking toolkit, scale your penetration testing workflow, and build reusable security tools tailored to real-world cybersecurity scenarios.What you will learn - Develop scripts and tools tailored for ethical hacking and penetration testing
- Leverage powerful tools such as awk, sed, and grep for data manipulation and log parsing
- Design scripts for system hardening
- Integrate scripting into your cybersecurity workflows for maximum efficiency
- Discover best practices for writing secure, maintainable, and modular scripts
- Apply scripting knowledge through real-world case studies and hands-on exercises
Who this book is forIf you're a cybersecurity enthusiast or ethical hacker who wants to learn more about building hacking tools, this book is for you. A basic understanding of ethical hacking, GNU/Linux, and bash scripting concepts will be helpful to get the most out of this book. The book is also ideal for seasoned pentesters and sysadmins looking to optimize operations.
All prices
More details
Content
- Cover
- Title page
- Copyright and credits page
- Contributors
- Table of Contents
- Preface
- Free benefits with your book
- Part 1: Scripting Basics and Environment Setup
- Chapter 1: Why bash Scripting for Hackers?
- Technical requirements
- 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
- Create your first bash script
- shebang
- Adding your script to PATH
- bash variables
- Comments
- Command substitution
- Functions
- Control structures
- One-liners and quick terminal scripting
- Summary
- Questions
- Further reading
- Answers
- Chapter 2: Hacking Lab Setup with Kali Linux
- Technical requirements
- Introduction to Kali Linux and its tools
- Manually setting up your ethical hacking lab
- Why set up a local lab?
- Preparation
- Setting up your virtual lab manually
- Automating lab setup with Vagrant
- Summary
- Questions
- Further reading
- Answers
- Chapter 3: Input, Output, and File Manipulation
- Technical requirements
- Reading input from the user (keyboard, files)
- The read command
- Prompting user for input
- Read multiple inputs with read
- Reading with no display
- Timing out
- Validating user input using if statements
- Read command options table
- Read input from a file
- Understanding command-line parameters
- Passing parameters to scripts
- Reading parameters in scripts
- Reading the script name
- Validating parameters
- bash special parameter variables
- Counting all the parameters
- Grabbing all the data using ($@)
- Grabbing all the data using ($*)
- Getting the process ID
- Understand the shift command
- Processing multiple command-line options
- Dealing with command-line options
- How to process simple options
- Separating options from parameters
- Putting it all together
- How to process options with values
- Using the getopt command
- Looking at the getopt command format
- Using getopt in your scripts
- Standardizing script options
- Redirecting input/output for flow control
- Redirect the standard output of a command to a file
- Redirect the standard error of a command to a file
- Discard the standard output of a command
- Redirect the contents of a file to the stdin of a command
- Manipulating file contents with awk, sed, and grep
- awk
- sed
- grep
- Summary
- Questions
- Further reading
- Answers
- Part 2: Scripting for Network Hacking
- Chapter 4: Reconnaissance and Scanning with Nmap
- Technical requirements
- Automate scans with Nmap
- What is Nmap?
- Why automate Nmap scans?
- Understanding Nmap scan types
- TCP connect scan
- SYN scan
- UDP scan
- Other scan types
- Automating Nmap scans with bash scripts
- Parsing Nmap output with bash
- Scheduling Nmap scans with cron jobs
- Advanced Nmap scripting techniques - parallel scanning
- Parsing, formatting Nmap scan results, and creating reports
- Understanding Nmap output formats
- Why use bash for Nmap report generation?
- Generating custom reports using grep and awk
- Creating automated HTML reports
- Nmap Scripting Engine for enhanced scans
- Getting started with NSE scripts
- Incorporating Nmap scripts in a bash script
- Summary
- Questions
- Further reading
- Answers
- Chapter 5: Automating Web Application Attacks
- Technical requirements
- Web scanning with Nikto
- Installing Nikto on Kali Linux
- Scanning the Metasploitable2 website
- Scanning the Metasploitable2 web apps
- Saving Nikto scan output to a file
- Scanning an HTTPS site with Nikto
- Scanning websites with non-standard ports
- Automating Nikto scans with shell scripts
- Scanning website directories with dirb
- Basic scanning with dirb
- Using wordlists with dirb
- Automatically downloading indexed files
- Automatically scanning for robots.txt files
- SQL injection attack automation with SQLMap
- Configuring Metasploitable2
- Correcting a configuration error in the Mutillidae app
- Creating or resetting the DVWA database and configure security
- SQL injection with the GET method
- SQL injection with the POST method
- Operating system command injection automation
- The basic command injection demo
- Getting a reverse shell from the web server
- Automating scans for command injection vulnerabilities
- Automating command injection scans with Commix
- Scanning for blind injection vulnerabilities
- Summary
- Questions
- Further reading
- Answers
- Part 3: Exploiting Systems and Post-Exploitation
- Chapter 6: Password Cracking Techniques
- Technical requirements
- Understanding password attacks
- Scanning for exposed network services
- Wordlist generation and customization
- Building username lists
- Building custom password lists
- Creating password lists with rsmangler
- Creating password lists with cewl
- Cracking passwords with hydra
- Attacking exposed network services with hydra
- Attacking SSH with hydra
- Attacking multiple targets at once with hydra
- Saving hydra output to a file
- Attacking a web form login page with hydra
- Attacking the SSH daemon with a shell script
- Cracking passwords with John the Ripper
- Understanding the Linux and Unix shadow system, and password hash algorithms
- Stage 1-Preparing the username and hash file for John the Ripper
- Stage 2-Using john to process the username and hash file
- Understanding password hashing algorithms
- Understanding the john output files
- Cracking SSH private keys with john
- Summary
- Questions
- Further reading
- Answers
- Chapter 7: Understanding Privilege Escalation and Persistence
- Technical requirements
- Understanding privilege escalation methods
- Finding a user with full sudo privileges
- Exploiting bad sudo configurations
- Exploiting bad SUID permissions
- Escalating after logging into someone else's account
- Escalating after a command injection attack
- Using the root user shell to create a privileged user account
- Using the root user shell to add a user to an admin group
- Automatically invoking a reverse shell
- Uploading malware via an NFS exploit
- Escalating user privileges on a web application
- Exploiting an unsecured Docker container
- Method 1 - Change the user's UID to 0
- Method 2 - Add the user to an administrator group
- Preventing attacks with insecure containers
- Cleaning up after a penetration test
- Summary
- Questions
- Further reading
- Answers
- Chapter 8: Automate Penetration Testing with Metasploit
- Technical requirements
- Introduction to the Metasploit Framework
- Understanding the Metasploit modules
- Getting started with msfconsole
- Using msfconsole in interactive mode
- Escalating privileges with Meterpreter
- Using msfconsole with a resource file
- Using msfconsole commands within a shell script
- Using Metasploit with the PostgreSQL database
- Using the database with multiple target hosts
- Using the database in shell scripts
- Summary
- Questions
- Further reading
- Answers
- Part 4: Advanced Scripting and Real-World Hacking Projects
- Chapter 9: Wi-Fi Hacking with Kismet and Wifite
- Technical requirements
- Understanding the wireless security protocols
- Wired Equivalent Privacy (WEP)
- Wi-Fi Protected Access (WPA)
- Wi-Fi Protected Access 2 (WPA2)
- Wi-Fi Protected Access 3 (WPA3)
- Hacking networks with default passwords
- A different password for each device
- The same default password for every device
- The same default password for initial setup
- Setting up a wireless adapter for VirtualBox
- Performing wireless reconnaissance with Kismet
- Setting up Kismet
- Viewing wireless networks with Kismet
- Automating Wi-Fi attacks with Wifite
- 4-way handshakes
- Wi-Fi Protected Setup (WPS)
- Pairwise Master Key Identifier keys
- Performing a WPA 4-way handshake attack
- Performing a PMKID attack
- Performing a WPS attack
- Attacking a WPA3 access point
- Summary
- Questions
- Further reading
- Answers
- Chapter 10: Auditing and Hardening Linux with Shell Scripts
- Technical requirements
- Automating security updates
- Automating security updates for Ubuntu Server
- Automating security updates on Red Hat-type systems
- Automating updates for openSUSE 16
- When to enable automatic updates
- Auditing users' sudo activity
- Auditing for enabled root user accounts
- Auditing Apache access logs for malicious attacks
- Installing the bat viewer
- Creating the xss_detect.sh script
- Auditing and hardening with LinPEAS and Lynis
- Auditing with LinPEAS
- Auditing with Lynis
- Comparing LinPEAS and Lynis
- Shell scripts for firewall configuration
- Understanding Linux firewalls
- Shell scripting with Uncomplicated Firewall
- Creating a shell script for SSH and Apache access
- Creating a shell script for controlling web server access
- Shell scripting for firewalld
- Understanding firewalld zones
- Understanding firewalld services
- Creating a shell script for web server access
- Creating a shell script to restrict web server access
- Summary
- Questions
- Further reading
- Answers
- Chapter 11: Automated Report Generation and Visualization
- Technical requirements
- Creating and using automated report templates
- Understanding report templates
- Creating a basic report template
- Automating report generation with bash
- Extracting key findings with scripting
- Parsing tool outputs
- Parsing nmap output
- Extracting vulnerabilities
- Extracting vulnerabilities from JSON output
- Summarizing findings
- Summarizing findings in bash
- Basic data visualization (graphs, charts)
- Choosing between Gnuplot and bash scripts
- Generating graphs with Gnuplot
- Generating a simple line graph
- Generating a bar chart
- Creating charts with bash scripts
- Creating an ASCII bar chart
- Exporting data to CSV
- Summary
- Chapter 12: End-to-End Penetration Testing Projects
- Technical requirements
- An internal network compromise
- Reconnaissance - scanning the network
- Manual process
- Automation with bash
- Finding exploits with SearchSploit
- Manual process
- Recognizing the need for automation
- Automating SearchSploit with bash
- Exploiting port 21 - FTP
- Manual exploitation with Metasploit
- Automating exploitation with Metasploit
- Exploiting port 8180 - Apache Tomcat
- Step 1 - Brute-forcing credentials
- Step 2 - Brute-forcing login with discovered usernames
- Step 3 - Deploying the exploit
- Automating Apache Tomcat exploit with bash
- Exploiting port 6667 - UnreallRCd backdoor
- Manual process - exploiting UnreallRCd
- Automating the UnreallRCd exploit with bash
- Privilege escalation - exploiting port 2049 - Network File System (NFS)
- Step 1 - Identifying NFS exports
- Step 2 - Gaining access by adding an SSH key
- Step 3 - SSH into the target as root
- Automating NFS exploit with bash
- A vulnerable web application
- Vulnerability - brute force
- Step 1 - Extracting cookies
- Step 2 - Inspecting the login form
- Brute-forcing the DVWA login page
- Brute-forcing at medium security
- Brute-forcing at high security
- Using a bash script for high security
- Why this script works at high security
- Summary
- Chapter 13: Unlock Access to the Code Bundle and the PDF Version
- Unlock this book's free benefits in three easy steps
- Other Books You May Enjoy
- Index
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
Your purchase includes a free PDF copy + exclusive extras
Your purchase includes a DRM-free PDF copy of this book, 7-day trial to the Packt+ library (no credit card required), and additional exclusive extras. See the Free benefits with your book section in the Preface to unlock them instantly and maximize your learning.
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. To access the repository link, follow the steps in the Download the example code files section in the Preface.
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/bash ip_list_file=$1 # Check if the input file is provided if [ "$ip_list_file" == "" ]; then echo "You forgot to provide the input file name!" echo "Syntax: ./net-scan.sh <filename>" exit 1 fi # Check if the input file exists if [ ! -f "$ip_file" ]; then echo "Error: The input file '$ip_list_file' does not exist!" exit 1 fi # Read IP addresses from the file and process each one while 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
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 scan network_range="192.168.1.0/24" # Perform a ping sweep to identify live hosts live_hosts=$(nmap -sn -oG - "$network_range" | awk '/Up/{print $2}') # Loop through the live hosts for host in $live_hosts do # Perform a comprehensive port scan nmap -sV -sC -p- -oN "$host.nmap" "$host" # Enumerate SMB shares enum4linux...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.
File format: ePUB
Copy protection: without DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Use a reader that can handle the file format ePUB, such as Adobe Digital Editions or FBReader – both free (see eBook Help).
- Tablet/Smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePUB works well for novels and non-fiction books – i.e., 'flowing' text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook does not use copy protection or Digital Rights Management
For more information, see our eBook Help page.