real time shell scripts usecases with example codes
1
2
3
System Monitoring Script
#!/bin/bash
cpu_threshold=90
mem_threshold=90
cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
mem_usage=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
if (( $(echo "$cpu_usage > $cpu_threshold" | bc -l) )) || (( $(echo "$mem_usage > $mem_threshold" | bc -l) )); then
echo "High CPU or memory usage detected!"
# Send alert here
fi4
5
6
7
Web Server Log Analysis Script
#!/bin/bash
access_log="/var/log/apache/access.log"
error_log="/var/log/apache/error.log"
# Analyze access log
echo "Top 10 IP addresses:"
awk '{print $1}' "$access_log" | sort | uniq -c | sort -nr | head -n 10
# Analyze error log
echo "Errors by type:"
awk '{print $9}' "$error_log" | sort | uniq -c | sort -nr8
10
11
Email Notification Script
#!/bin/bash
subject="Alert: High CPU Usage"
body="CPU usage exceeded 90%"
recipient="[email protected]"
echo "$body" | mail -s "$subject" "$recipient"12
13
Data Encryption Script
#!/bin/bash
gpg --encrypt --recipient [email protected] sensitive_file.txt14
15
16
17
18
19
21
22
Backup Verification Script
#!/bin/bash
backup_file="/path/to/backup.tar.gz"
expected_checksum="expected_checksum"
actual_checksum=$(md5sum "$backup_file" | awk '{print $1}')
if [ "$actual_checksum" == "$expected_checksum" ]; then
echo "Backup integrity verified"
else
echo "Backup integrity compromised"
fi23
24
25
26
27
File Encryption and Decryption Script
#!/bin/bash
gpg --output encrypted_file.txt.gpg --encrypt --recipient [email protected] plaintext_file.txt
gpg --output decrypted_file.txt --decrypt encrypted_file.txt.gpg28
29
