2025-02-12
Shell scripting is an essential skill for cybersecurity professionals, enabling automation of repetitive tasks, system monitoring, and rapid response to security incidents. Below, we’ll explore practical examples of shell scripts using tools like awk
, sed
, and basic shell commands to enhance your cybersecurity workflow.
Basic Shell Script for Log Monitoring
#!/bin/bash <h1>Monitor auth.log for failed login attempts</h1> LOG_FILE="/var/log/auth.log" FAILED_LOGINS=$(grep "Failed password" $LOG_FILE | awk '{print $9}' | sort | uniq -c | sort -nr) echo "Failed Login Attempts:" echo "$FAILED_LOGINS"
This script monitors `/var/log/auth.log` for failed SSH login attempts and lists the IP addresses with the most attempts.
Using `sed` for Data Sanitization
#!/bin/bash <h1>Sanitize sensitive data from a file</h1> INPUT_FILE="data.txt" OUTPUT_FILE="sanitized_data.txt" sed 's/(credit card number)[0-9]{12}/\1XXXX-XXXX-XXXX-XXXX/g' $INPUT_FILE > $OUTPUT_FILE
This script uses `sed` to replace credit card numbers in a file with a sanitized format.
Automating Network Scans with `nmap`
#!/bin/bash <h1>Automated network scan and report</h1> TARGET="192.168.1.0/24" OUTPUT_FILE="network_scan.txt" nmap -sP $TARGET > $OUTPUT_FILE echo "Network scan completed. Results saved to $OUTPUT_FILE."
This script performs a ping scan on a subnet and saves the results to a file.
Parsing Logs with `awk`
#!/bin/bash <h1>Extract unique IP addresses from a web server log</h1> LOG_FILE="/var/log/nginx/access.log" awk '{print $1}' $LOG_FILE | sort | uniq -c | sort -nr
This script extracts and counts unique IP addresses from an Nginx access log.
What Undercode Say
Shell scripting is a cornerstone of cybersecurity, enabling professionals to automate tasks, analyze data, and respond to threats efficiently. By mastering tools like awk
, sed
, and nmap
, you can streamline your workflow and enhance your system’s security posture. Below are additional commands and resources to deepen your knowledge:
- Log Analysis: Use `journalctl -u sshd` to view SSH service logs.
- File Integrity Monitoring: Implement `tripwire` or `aide` to detect unauthorized file changes.
- Network Security: Use `iptables` to configure firewalls and `tcpdump` for packet analysis.
- Incident Response: Automate incident response with scripts that isolate compromised systems using
systemctl stop network.service
. - Resource Monitoring: Monitor system resources with
top
,htop
, orvmstat
.
For further reading, explore the following resources:
By integrating these tools and techniques into your daily operations, you can build a robust cybersecurity framework that leverages the power of Linux and shell scripting.
References:
Hackers Feeds, Undercode AI