Bash Penetration Test Automation: Why CTF Scripts?
Bash is available on any Linux system. Python may be missing on stripped-down CTF containers and minimal Docker images, but sh, grep, awk And sedcan even be found in BusyBox. On one of the recent assignments, the remote machine contained only sh And awk— this was enough to comb through the file system, extract configs, and detect SUID binaries. For more details, see our article on creating CTF tasks .
The creation speed is the second argument. Link nmap, removing ports and gobuster— six lines in bash. A similar thing in Python with argparse, exception handling and calls subprocess.run()— a 50+ line project. When the timer shows two hours for ten tasks, that gap is everything.
The third point is a direct correspondence to MITRE ATT&CK techniques. Running shell scripts on the target system is mapped to T1059.004 Unix Shell (Execution tactic). File system reconnaissance via find And ls— T1083 File and Directory Discovery (Discovery Tactics). Collecting system data through uname, id, cat /etc/os-release— T1082 System Information Discovery. Password brute-force attack curlin the cycle - T1110.001 Password Guessing (Credential Access tactics).
The Atomic Red Team repository for T1059.004 contains tests for "Create and Execute Bash Shell Script" and "Harvest SUID executable files" - both run via shOn Linux. In CTFs, you do exactly the same thing: write a script, run it, and collect data. Understanding mapping helps not only in competitions but also when writing reports on real pentests—you specify the TTP right away, not just "ran nmap."
Automating CTF tasks via bash saves cognitive resources. Instead of typing the same commands over and over, you think about the logic behind the task. This is what differentiates a participant who completes 12 tasks in a competition from someone who completes just 4.
Preparing the environment
Before your first script, check three things. Bash version: bash --version— Any 4.x or higher will do. On macOS, 3.2 is the default due to licensing—update via brew install bashOn Windows - WSL2 with any distribution.
Utilities: The scripts in the article work with nmap, gobuster, curl, grep, awk, sed And wcEverything is installed out of the box in Kali and Parrot OS. On minimal distributions, you can get it via apt install nmap curl gobuster.
Working directory: mkdir ~/ctf && cd ~/ctfEach script begins with a shebang line. #!/bin/bash— it specifies the interpreter for the system. After creating the file — chmod +x script.sh, otherwise you get Permission denied. Alternatively, launch via bash script.sh, but with frequent use it's less convenient. Any editor: nanofor beginners, vimfor modal-ready users.
Port Enumeration Script: Automated Reconnaissance with Nmap
The most common CTF routine is to scan ports, identify services, and check web directories. These three commands, which always follow one another, are ideal candidates for automation. The logic: accepts an IP address, creates a folder for the results, and runs nmap. Finds the HTTP port and automatically sets it gobuster. Doesn't find it - limited to the nmap stage.
#!/bin/bash
set -euo pipefail
[ -z "${1:-}" ] && echo "Использование: $0 <IP>" && exit 1
IP="$1"; DIR="recon_$IP"; mkdir -p "$DIR"
nmap -sV -sC -oN "$DIR/nmap.txt" "$IP"
WEBPORT=$(grep -E '/tcp.*http' "$DIR/nmap.txt" | grep -oE '^[0-9]+' | head -1 || true)
[ -n "$WEBPORT" ] && gobuster dir -u "http://$IP:$WEBPORT" \
-w /usr/share/wordlists/dirb/common.txt -o "$DIR/dirs.txt" 2>/dev/null
echo "[+] Результаты: ./$DIR/"
Let's understand it line by line.
set -euo pipefail— insurance against silent mistakes. Flag -eterminates the script on any command with a non-zero return code Flag -ucatches references to undefined variables - without it, a typo in a variable name would return an empty string instead of an error. Flag -o pipefailcatches failures in pipes: without it false | echo okwill silently return success. According to hadess.io, these three flags "prevent silent failures that lead to incorrect results." In CTFs, such "silent" failures are especially nasty—you don't notice the problem and end up parsing an empty file.
Construction [ -z "${1:-}" ]Checks if the argument is passed. Note: ${1:-}instead of naked $1. Construction :-returns an empty string if the variable is not set and prevents an error when active set -uWithout this check nmapwill start without a target and hang waiting for input.
Variable DIRgenerates a folder name of the form recon_10.10.10.5— the results of each machine are stored separately. mkdir -p creates the directory without error if it already exists.
Flags nmap -sV -sC— service version detection plus default NSE scripts. Without them, nmap will only show open port numbers without context—not enough for CTF. The flag -oNsaves the output in text format (Normal output), suitable for parsing.
The key construct is extracting the HTTP port. grep -E '/tcp.*http'finds lines of the form 80/tcp open http. Then grep -oE '^[0-9]+'extracts the port number from the beginning of the string. head -1takes the first HTTP port. If nmap doesn't find HTTP, || trueensures that the pipeline will not crash the script due to pipefail— variable WEBPORTthe block with will remain empty gobusterit simply won't work.
Redirection 2>/dev/nullSuppresses the gobuster progress bar, which clutters the terminal when launched automatically. The results are saved in dirs.txt.
To run on multiple targets: while read -r ip; do ./recon.sh "$ip"; done < targets.txt. File targets.txt— one IP per line. Run the command and read the task conditions while the automation runs in the background.
Portability Note
Flag grep -Euses extended regular expressions (ERE). In BusyBox it is only available if grepcompiled with the corresponding option. On stripped-down systems, an alternative: grep '/tcp.*http' "$DIR/nmap.txt" | awk '{print $1}' | cut -d/ -f1 | head -1 — awkmore portable and works even in minimal BusyBox builds.
Parsing nmap bash output: one-liners in awk and sed
Nmap generates text output with a stable structure—an ideal target for parsing. Russian-language materials are usually limited to the basic grep, But awk And sedopen up a whole new level. Let's look at specific tasks.
Извлечение всех открытых портов. Конструкция grep -oE '^[0-9]+/tcp' nmap.txt | cut -d/ -f1 | paste -sd, вытаскивает номера портов и склеивает через запятую. Результат вида 22,80,443,8080 — готовый аргумент для прицельного повторного сканирования: nmap -p 22,80,443,8080 -A $IP. Обратите внимание на paste -sd, — она делает то же, что tr '\n' ',' | sed 's/,$//', but in one team instead of two.
Service versions - clean table. Team awk '/^[0-9]+\/tcp/{print $1, $3, $4, $5}' nmap.txtextracts the port, status and name of the service with the version. awksplits a string into fields by spaces: $1— the first field, $NF— the last one, $(NF-1)— the penultimate one. For nmap output $1 - This 80/tcp, $3 — http, $4 And $5— server name and version.
Filtering by service type. For SSH ports: grep -E '^[0-9]+/tcp.*ssh' nmap.txt | awk '{print $1}'For HTTP, replace sshon http. Bundle grepfor filtration and awkfor extraction - a basic pattern that works with any text output.
# Открытые порты через запятую
grep -oE '^[0-9]+/tcp' nmap.txt | cut -d/ -f1 | paste -sd,
# Версии сервисов
awk '/^[0-9]+\/tcp/{print $1, $3, $4, $5}' nmap.txt
# HTTP-порты для gobuster
grep '/tcp.*http' nmap.txt | grep -oE '^[0-9]+'
# Уникальные IP из access.log
awk '{print $1}' access.log | sort -u
# Неудачные SSH-входы — top по IP
grep "Failed password" auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn
The latest one-liner is worth taking apart. NFin awk - the number of fields in a line. $(NF-3)— the third field from the end. In the line Failed password for admin from 192.168.1.100 port 22 ssh2The IP address is located in the third position from the end. This construction is from real-life analysis practice. /var/log/auth.log— hadess.io describes it for SOC analyst tasks.
Pipe sort | uniq -c | sort -rn— the classic trinity: sorting, counting unique occurrences, and sorting in descending order. Remember this combination—it comes up in every other log analysis task.
nmap XML format
Text output ( -oN) is convenient for simple parsing, but XML is better for complex queries. Run nmap with -oX nmap.xmlTo extract port numbers: grep -oP 'portid="\K[^"]+'— construction \K(Perl-compatible lookbehind) discards everything before the attribute value. If grep -Punavailable, alternative: awk -F'"' '/portid/{print $2}'— awk splits the string by quotes, the second field contains the port number.
According to hadess.io, xmllint --xpath '//port[@protocol="tcp"]/state[@state="open"]/..' nmap_output.xmlallows you to make full XPath queries to nmap's XML output. But xmllintIt's not always on CTF stands - I wouldn't count on it.
Working with JSON
If the API responds with JSON, use jq. Construction curl -s http://api/endpoint | jq -r '.token'will extract the key value tokenFor nested structures: jq -r '.data.users[].name'.
If jqis not installed (a common situation on CTFs), the simplest JSON fields are extracted through grep -oP '"key":"\K[^"]+'— a crude method, but it works for CTFs. For structured logs in JSON format. jqirreplaceable: cat app.log | jq -r 'select(.level == "ERROR") | "\(.timestamp) \(.message)"'Filters only errors and displays them with timestamps.
Brute-force Bash script: brute-force web forms for CTF
A web login form without rate-limiting or CSRF protection is a classic entry-level CTF. A four-digit PIN or password from a short wordlist is required. According to OWASP, this is an A07:2021 Identification and Authentication Failures . In CTFs, this weakness is intentional; in production, it's a huge hole.
Before running a full enumeration, manually check that the server does not return HTTP 429/503 after a series of requests - if there is a rate-limiting, the script below does not process it.
Before writing a script, analyze the request manually. Open Developer Tools (Network tab), enter a deliberately incorrect password, and record four things: the form URL (e.g., http://target:8080/login), method (POST or GET), field names ( user, pass) and the response text in case of error ( Access denied). Without this manual preparation, the script shoots blind.
#!/bin/bash
# set -euo pipefail здесь не используется: grep -q возвращает non-zero при каждом неверном пароле,
# что при set -e прервало бы цикл перебора на первой же попытке.
URL="http://target:8080/login"; FAIL="Access denied"
WORDLIST="${1:-/usr/share/wordlists/rockyou.txt}"
while read -r pass; do
resp=$(curl -s -d "user=admin" --data-urlencode "pass=${pass}" "$URL")
echo "$resp" | grep -q "$FAIL" || { echo "[+] Пароль: $pass"; exit 0; }
done < "$WORDLIST"
echo "[-] Совпадений нет"
Variable FAILcontains an invalid password marker - a string from Developer Tools. Construction ${1:-/usr/share/wordlists/rockyou.txt}Takes the path to the wordlist from the argument. If no argument is passed, it substitutes the default path to rockyou.txtfrom Kali.
Cycle while read -r passReads the file line by line, without loading it into memory entirely. This is critical: rockyou.txtweighs over 140 MB. Design for pass in $(cat rockyou.txt)will attempt to load the entire file into RAM and kill the shell (tested - don't repeat). Flag -rprevents backslashes from being interpreted - without it, the password pa\sswill turn into pass.
curl -s -d ... --data-urlencodesends a POST request. curl automatically concatenates multiple -d And --data-urlencode parameters via &in the request body. --data-urlencodeencodes special characters in the password value - without this flag the password with & or =will break the query structure. Flag -s(silent) suppresses the progress bar.
Construction grep -q "$FAIL" || { ...; }— inverted check. If grepDoesn't find the error string in the response - the password worked. Operator ||executes the block on the right only if the command on the left fails. More compact than if ! echo "$resp" | grep -q "$FAIL"; then.
Limitations and extensions
The script works with simple forms without CSRF tokens. If the form generates a token in a hidden field, first fetch the page. curl-om, extract the token via sed -n 's/.*value="\([^"]*\)".*/\1/p'and insert it into the POST request. This adds 3-4 lines, but the logic is the same.
To generate wordlists on the fly: seq -w 0000 9999 > pins.txt creates a list of four-digit PINs. Flag -wprovides leading zeros ( 0001, 0002instead of 1, 2). For hexadecimal values: printf "%04x\n" $(seq 0 65535) > hex.txt.
According to MITRE ATT&CK, brute force curlThe loop maps to T1110.001 Password Guessing (Credential Access tactic). All three public Atomic Red Team tests for T1110.001 are Windows-oriented (SMB, LDAP, Kerberos)—there are no Linux/bash tests for this technique in the repository, and curl-based brute-force web forms are not covered by official atomic tests. The mapping to the technique is correct: the principle of password dictionary attack is the same on any platform.
Bash is available on any Linux system. Python may be missing on stripped-down CTF containers and minimal Docker images, but sh, grep, awk And sedcan even be found in BusyBox. On one of the recent assignments, the remote machine contained only sh And awk— this was enough to comb through the file system, extract configs, and detect SUID binaries. For more details, see our article on creating CTF tasks .
The creation speed is the second argument. Link nmap, removing ports and gobuster— six lines in bash. A similar thing in Python with argparse, exception handling and calls subprocess.run()— a 50+ line project. When the timer shows two hours for ten tasks, that gap is everything.
The third point is a direct correspondence to MITRE ATT&CK techniques. Running shell scripts on the target system is mapped to T1059.004 Unix Shell (Execution tactic). File system reconnaissance via find And ls— T1083 File and Directory Discovery (Discovery Tactics). Collecting system data through uname, id, cat /etc/os-release— T1082 System Information Discovery. Password brute-force attack curlin the cycle - T1110.001 Password Guessing (Credential Access tactics).
The Atomic Red Team repository for T1059.004 contains tests for "Create and Execute Bash Shell Script" and "Harvest SUID executable files" - both run via shOn Linux. In CTFs, you do exactly the same thing: write a script, run it, and collect data. Understanding mapping helps not only in competitions but also when writing reports on real pentests—you specify the TTP right away, not just "ran nmap."
Automating CTF tasks via bash saves cognitive resources. Instead of typing the same commands over and over, you think about the logic behind the task. This is what differentiates a participant who completes 12 tasks in a competition from someone who completes just 4.
Preparing the environment
Before your first script, check three things. Bash version: bash --version— Any 4.x or higher will do. On macOS, 3.2 is the default due to licensing—update via brew install bashOn Windows - WSL2 with any distribution.
Utilities: The scripts in the article work with nmap, gobuster, curl, grep, awk, sed And wcEverything is installed out of the box in Kali and Parrot OS. On minimal distributions, you can get it via apt install nmap curl gobuster.
Working directory: mkdir ~/ctf && cd ~/ctfEach script begins with a shebang line. #!/bin/bash— it specifies the interpreter for the system. After creating the file — chmod +x script.sh, otherwise you get Permission denied. Alternatively, launch via bash script.sh, but with frequent use it's less convenient. Any editor: nanofor beginners, vimfor modal-ready users.
Port Enumeration Script: Automated Reconnaissance with Nmap
The most common CTF routine is to scan ports, identify services, and check web directories. These three commands, which always follow one another, are ideal candidates for automation. The logic: accepts an IP address, creates a folder for the results, and runs nmap. Finds the HTTP port and automatically sets it gobuster. Doesn't find it - limited to the nmap stage.
#!/bin/bash
set -euo pipefail
[ -z "${1:-}" ] && echo "Использование: $0 <IP>" && exit 1
IP="$1"; DIR="recon_$IP"; mkdir -p "$DIR"
nmap -sV -sC -oN "$DIR/nmap.txt" "$IP"
WEBPORT=$(grep -E '/tcp.*http' "$DIR/nmap.txt" | grep -oE '^[0-9]+' | head -1 || true)
[ -n "$WEBPORT" ] && gobuster dir -u "http://$IP:$WEBPORT" \
-w /usr/share/wordlists/dirb/common.txt -o "$DIR/dirs.txt" 2>/dev/null
echo "[+] Результаты: ./$DIR/"
Let's understand it line by line.
set -euo pipefail— insurance against silent mistakes. Flag -eterminates the script on any command with a non-zero return code Flag -ucatches references to undefined variables - without it, a typo in a variable name would return an empty string instead of an error. Flag -o pipefailcatches failures in pipes: without it false | echo okwill silently return success. According to hadess.io, these three flags "prevent silent failures that lead to incorrect results." In CTFs, such "silent" failures are especially nasty—you don't notice the problem and end up parsing an empty file.
Construction [ -z "${1:-}" ]Checks if the argument is passed. Note: ${1:-}instead of naked $1. Construction :-returns an empty string if the variable is not set and prevents an error when active set -uWithout this check nmapwill start without a target and hang waiting for input.
Variable DIRgenerates a folder name of the form recon_10.10.10.5— the results of each machine are stored separately. mkdir -p creates the directory without error if it already exists.
Flags nmap -sV -sC— service version detection plus default NSE scripts. Without them, nmap will only show open port numbers without context—not enough for CTF. The flag -oNsaves the output in text format (Normal output), suitable for parsing.
The key construct is extracting the HTTP port. grep -E '/tcp.*http'finds lines of the form 80/tcp open http. Then grep -oE '^[0-9]+'extracts the port number from the beginning of the string. head -1takes the first HTTP port. If nmap doesn't find HTTP, || trueensures that the pipeline will not crash the script due to pipefail— variable WEBPORTthe block with will remain empty gobusterit simply won't work.
Redirection 2>/dev/nullSuppresses the gobuster progress bar, which clutters the terminal when launched automatically. The results are saved in dirs.txt.
To run on multiple targets: while read -r ip; do ./recon.sh "$ip"; done < targets.txt. File targets.txt— one IP per line. Run the command and read the task conditions while the automation runs in the background.
Portability Note
Flag grep -Euses extended regular expressions (ERE). In BusyBox it is only available if grepcompiled with the corresponding option. On stripped-down systems, an alternative: grep '/tcp.*http' "$DIR/nmap.txt" | awk '{print $1}' | cut -d/ -f1 | head -1 — awkmore portable and works even in minimal BusyBox builds.
Parsing nmap bash output: one-liners in awk and sed
Nmap generates text output with a stable structure—an ideal target for parsing. Russian-language materials are usually limited to the basic grep, But awk And sedopen up a whole new level. Let's look at specific tasks.
Извлечение всех открытых портов. Конструкция grep -oE '^[0-9]+/tcp' nmap.txt | cut -d/ -f1 | paste -sd, вытаскивает номера портов и склеивает через запятую. Результат вида 22,80,443,8080 — готовый аргумент для прицельного повторного сканирования: nmap -p 22,80,443,8080 -A $IP. Обратите внимание на paste -sd, — она делает то же, что tr '\n' ',' | sed 's/,$//', but in one team instead of two.
Service versions - clean table. Team awk '/^[0-9]+\/tcp/{print $1, $3, $4, $5}' nmap.txtextracts the port, status and name of the service with the version. awksplits a string into fields by spaces: $1— the first field, $NF— the last one, $(NF-1)— the penultimate one. For nmap output $1 - This 80/tcp, $3 — http, $4 And $5— server name and version.
Filtering by service type. For SSH ports: grep -E '^[0-9]+/tcp.*ssh' nmap.txt | awk '{print $1}'For HTTP, replace sshon http. Bundle grepfor filtration and awkfor extraction - a basic pattern that works with any text output.
# Открытые порты через запятую
grep -oE '^[0-9]+/tcp' nmap.txt | cut -d/ -f1 | paste -sd,
# Версии сервисов
awk '/^[0-9]+\/tcp/{print $1, $3, $4, $5}' nmap.txt
# HTTP-порты для gobuster
grep '/tcp.*http' nmap.txt | grep -oE '^[0-9]+'
# Уникальные IP из access.log
awk '{print $1}' access.log | sort -u
# Неудачные SSH-входы — top по IP
grep "Failed password" auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -rn
The latest one-liner is worth taking apart. NFin awk - the number of fields in a line. $(NF-3)— the third field from the end. In the line Failed password for admin from 192.168.1.100 port 22 ssh2The IP address is located in the third position from the end. This construction is from real-life analysis practice. /var/log/auth.log— hadess.io describes it for SOC analyst tasks.
Pipe sort | uniq -c | sort -rn— the classic trinity: sorting, counting unique occurrences, and sorting in descending order. Remember this combination—it comes up in every other log analysis task.
nmap XML format
Text output ( -oN) is convenient for simple parsing, but XML is better for complex queries. Run nmap with -oX nmap.xmlTo extract port numbers: grep -oP 'portid="\K[^"]+'— construction \K(Perl-compatible lookbehind) discards everything before the attribute value. If grep -Punavailable, alternative: awk -F'"' '/portid/{print $2}'— awk splits the string by quotes, the second field contains the port number.
According to hadess.io, xmllint --xpath '//port[@protocol="tcp"]/state[@state="open"]/..' nmap_output.xmlallows you to make full XPath queries to nmap's XML output. But xmllintIt's not always on CTF stands - I wouldn't count on it.
Working with JSON
If the API responds with JSON, use jq. Construction curl -s http://api/endpoint | jq -r '.token'will extract the key value tokenFor nested structures: jq -r '.data.users[].name'.
If jqis not installed (a common situation on CTFs), the simplest JSON fields are extracted through grep -oP '"key":"\K[^"]+'— a crude method, but it works for CTFs. For structured logs in JSON format. jqirreplaceable: cat app.log | jq -r 'select(.level == "ERROR") | "\(.timestamp) \(.message)"'Filters only errors and displays them with timestamps.
Brute-force Bash script: brute-force web forms for CTF
A web login form without rate-limiting or CSRF protection is a classic entry-level CTF. A four-digit PIN or password from a short wordlist is required. According to OWASP, this is an A07:2021 Identification and Authentication Failures . In CTFs, this weakness is intentional; in production, it's a huge hole.
Before running a full enumeration, manually check that the server does not return HTTP 429/503 after a series of requests - if there is a rate-limiting, the script below does not process it.
Before writing a script, analyze the request manually. Open Developer Tools (Network tab), enter a deliberately incorrect password, and record four things: the form URL (e.g., http://target:8080/login), method (POST or GET), field names ( user, pass) and the response text in case of error ( Access denied). Without this manual preparation, the script shoots blind.
#!/bin/bash
# set -euo pipefail здесь не используется: grep -q возвращает non-zero при каждом неверном пароле,
# что при set -e прервало бы цикл перебора на первой же попытке.
URL="http://target:8080/login"; FAIL="Access denied"
WORDLIST="${1:-/usr/share/wordlists/rockyou.txt}"
while read -r pass; do
resp=$(curl -s -d "user=admin" --data-urlencode "pass=${pass}" "$URL")
echo "$resp" | grep -q "$FAIL" || { echo "[+] Пароль: $pass"; exit 0; }
done < "$WORDLIST"
echo "[-] Совпадений нет"
Variable FAILcontains an invalid password marker - a string from Developer Tools. Construction ${1:-/usr/share/wordlists/rockyou.txt}Takes the path to the wordlist from the argument. If no argument is passed, it substitutes the default path to rockyou.txtfrom Kali.
Cycle while read -r passReads the file line by line, without loading it into memory entirely. This is critical: rockyou.txtweighs over 140 MB. Design for pass in $(cat rockyou.txt)will attempt to load the entire file into RAM and kill the shell (tested - don't repeat). Flag -rprevents backslashes from being interpreted - without it, the password pa\sswill turn into pass.
curl -s -d ... --data-urlencodesends a POST request. curl automatically concatenates multiple -d And --data-urlencode parameters via &in the request body. --data-urlencodeencodes special characters in the password value - without this flag the password with & or =will break the query structure. Flag -s(silent) suppresses the progress bar.
Construction grep -q "$FAIL" || { ...; }— inverted check. If grepDoesn't find the error string in the response - the password worked. Operator ||executes the block on the right only if the command on the left fails. More compact than if ! echo "$resp" | grep -q "$FAIL"; then.
Limitations and extensions
The script works with simple forms without CSRF tokens. If the form generates a token in a hidden field, first fetch the page. curl-om, extract the token via sed -n 's/.*value="\([^"]*\)".*/\1/p'and insert it into the POST request. This adds 3-4 lines, but the logic is the same.
To generate wordlists on the fly: seq -w 0000 9999 > pins.txt creates a list of four-digit PINs. Flag -wprovides leading zeros ( 0001, 0002instead of 1, 2). For hexadecimal values: printf "%04x\n" $(seq 0 65535) > hex.txt.
According to MITRE ATT&CK, brute force curlThe loop maps to T1110.001 Password Guessing (Credential Access tactic). All three public Atomic Red Team tests for T1110.001 are Windows-oriented (SMB, LDAP, Kerberos)—there are no Linux/bash tests for this technique in the repository, and curl-based brute-force web forms are not covered by official atomic tests. The mapping to the technique is correct: the principle of password dictionary attack is the same on any platform.