ekh_development_scripting_examples_p03 - itnett/FTD02H-N GitHub Wiki
💻 Scripting Examples
Welcome to the Scripting Examples section! This page provides practical examples of scripts commonly used in IT security. These examples cover various tasks such as automation, monitoring, data analysis, and incident response. Each script is designed to demonstrate best practices and can be customized to fit your specific needs.
🛠️ Why Scripting Examples are Valuable
Scripting is a powerful tool in IT security, enabling automation, customization, and efficiency. By studying and utilizing these scripting examples, you can streamline your security operations, automate repetitive tasks, and enhance your overall security posture. These examples serve as a foundation for developing more complex scripts tailored to your environment.
Benefits:
- Automation: Save time and reduce errors by automating repetitive security tasks.
- Customization: Adapt scripts to meet specific security needs or to address unique challenges in your environment.
- Learning: Improve your scripting skills by exploring and modifying real-world examples.
- Efficiency: Increase operational efficiency by implementing effective, ready-to-use scripts.
🔍 Scripting Examples
1. Python Script for Log File Analysis
Description: This Python script analyzes log files to identify and report unusual activity, such as multiple failed login attempts or unauthorized access.
import re
log_file = "/var/log/auth.log"
pattern = r"Failed password for (invalid user )?(\w+) from (\d+\.\d+\.\d+\.\d+)"
def analyze_logs(log_file):
with open(log_file, "r") as file:
for line in file:
match = re.search(pattern, line)
if match:
user = match.group(2)
ip_address = match.group(3)
print(f"Suspicious activity detected: {user} from {ip_address}")
if __name__ == "__main__":
analyze_logs(log_file)
Usage:
- Run this script on a Unix-based system to scan authentication logs for suspicious activity.
- Customize the
pattern
to search for specific events in your logs.
2. Bash Script for Automated Backups
Description: This Bash script automates the process of backing up a directory to a remote server using rsync
.
#!/bin/bash
SOURCE_DIR="/home/user/data"
DEST_DIR="/backup/user/data"
REMOTE_SERVER="backup.example.com"
REMOTE_USER="backupuser"
rsync -avz --delete $SOURCE_DIR $REMOTE_USER@$REMOTE_SERVER:$DEST_DIR
if [ $? -eq 0 ]; then
echo "Backup successful!"
else
echo "Backup failed!"
fi
Usage:
- Schedule this script using
cron
to perform regular backups. - Modify
SOURCE_DIR
,DEST_DIR
,REMOTE_SERVER
, andREMOTE_USER
to match your environment.
3. PowerShell Script for Active Directory User Report
Description: This PowerShell script generates a report of all Active Directory users, including their last logon time and account status.
Get-ADUser -Filter * -Property DisplayName, LastLogonDate, Enabled |
Select-Object DisplayName, LastLogonDate, Enabled |
Export-Csv -Path "C:\Reports\ADUserReport.csv" -NoTypeInformation
Write-Host "Active Directory user report generated successfully!"
Usage:
- Run this script on a Windows server with the Active Directory PowerShell module installed.
- The report will be saved as
ADUserReport.csv
in the specified directory.
4. Python Script for Port Scanning
Description: This Python script performs a simple port scan on a given IP address to check for open ports.
import socket
def scan_ports(ip, port_range):
for port in port_range:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((ip, port))
if result == 0:
print(f"Port {port} is open on {ip}")
sock.close()
if __name__ == "__main__":
target_ip = "192.168.1.1"
ports = range(1, 1025)
scan_ports(target_ip, ports)
Usage:
- Modify
target_ip
to the IP address you want to scan. - Adjust the
ports
range to scan different port ranges.
5. Bash Script for Monitoring Disk Usage
Description: This Bash script checks disk usage and sends an alert if usage exceeds a specified threshold.
#!/bin/bash
THRESHOLD=80
PARTITION="/dev/sda1"
usage=$(df -h | grep $PARTITION | awk '{ print $5 }' | sed 's/%//g')
if [ $usage -gt $THRESHOLD ]; then
echo "Disk usage for $PARTITION is at $usage%. Alert triggered!"
# You can add email alerts or other notification mechanisms here
else
echo "Disk usage for $PARTITION is under control."
fi
Usage:
- Set
THRESHOLD
to the percentage of disk usage that should trigger an alert. - Adjust
PARTITION
to the disk partition you want to monitor.
🛡️ Best Practices for Using Scripts
1. Always Test in a Controlled Environment
- Before deploying scripts in a live environment, test them in a sandbox or controlled setting to ensure they work as expected and do not cause unintended side effects.
2. Implement Proper Logging
- Ensure that your scripts generate logs that can be reviewed for troubleshooting, auditing, or understanding script behavior.
3. Secure Sensitive Data
- Never hard-code sensitive data such as passwords or API keys in your scripts. Use secure storage mechanisms like environment variables or vaults.
4. Use Version Control
- Store your scripts in a version control system like Git to track changes, manage versions, and collaborate with others.
5. Regular Updates and Maintenance
- Regularly review and update your scripts to fix bugs, improve efficiency, and adapt to changes in your environment or requirements.
🚀 Implementing Scripting in Your Environment
Objective:
To effectively integrate and utilize scripts within your IT security operations, automating tasks, enhancing monitoring, and improving overall efficiency.
Steps:
- Identify Automation Opportunities: Look for repetitive or time-consuming tasks that could be automated with scripts.
- Customize Examples: Use the provided examples as a starting point, customizing them to meet your specific needs.
- Deploy Securely: Implement scripts in a secure manner, ensuring they run with appropriate privileges and are protected from unauthorized access.
- Monitor and Maintain: Continuously monitor the execution of scripts and update them as needed to ensure they remain effective and secure.
📚 Further Learning Resources
- Books: "Python for Cybersecurity: Using Python for Cyber Offense and Defense" by Howard E. Poston and "Bash Cookbook: Solutions and Examples for Bash Users" by Carl Albing offer great insights into scripting for security.
- Online Courses: Consider courses on scripting for security professionals on platforms like Coursera, Pluralsight, or Udemy.
- Certifications: Explore certifications like GPYC (GIAC Python Coder) to validate your scripting expertise in the security field.
🔗 Quick Links:
💡 Pro Tip: Bookmark this page to quickly access scripting examples that help you automate, monitor, and secure your IT environment effectively!
Automate confidently, secure efficiently! 💻