Sophisticated Bash & Python Automation
#!/bin/bash
# Advanced System Monitoring and Backup Script
# Features: Error handling, logging, user input, process monitoring
set -o errexit
set -o nounset
set -o pipefail
# Configuration
readonly BACKUP_ROOT="/var/backups"
readonly LOG_FILE="$(dirname "$0")/system_monitor.log"
readonly TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
readonly MAX_CPU_USAGE=90
readonly MAX_MEM_USAGE=85
# Colors for output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly NC='\033[0m' # No Color
# Initialize logging
exec >>(tee -a "$LOG_FILE") 2>&1
function log() {
local level="$1"
local message="$2"
local timestamp="$(date +"%Y-%m-%d %H:%M:%S")"
case "$level" in
INFO) color="$GREEN" ;;
WARN) color="$YELLOW" ;;
ERROR) color="$RED" ;;
*) color="$NC" ;;
esac
echo -e "${timestamp} ${color}[${level}]${NC} ${message}"
}
function check_system() {
local cpu_usage="$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}' | cut -d. -f1)"
local mem_usage="$(free | grep Mem | awk '{print $3/$2 * 100.0}' | cut -d. -f1)"
local disk_usage="$(df -h / | tail -1 | awk '{print $5}' | tr -d %)"
log INFO "System check - CPU: ${cpu_usage}%, Memory: ${mem_usage}%, Disk: ${disk_usage}%"
if [ "$cpu_usage" -gt "$MAX_CPU_USAGE" ]; then
log WARN "High CPU usage detected: ${cpu_usage}%"
fi
if [ "$mem_usage" -gt "$MAX_MEM_USAGE" ]; then
log WARN "High Memory usage detected: ${mem_usage}%"
fi
}
function create_backup() {
local backup_dir="${BACKUP_ROOT}/${TIMESTAMP}"
local backup_file="${backup_dir}/system_backup_${TIMESTAMP}.tar.gz"
log INFO "Creating backup directory: ${backup_dir}"
mkdir -p "$backup_dir" || {
log ERROR "Failed to create backup directory"
return 1
}
local include_dirs="/etc /home /var/www"
log INFO "Starting backup of system directories"
if tar -czf "$backup_file" $include_dirs 2>/dev/null; then
local backup_size="du -sh "$backup_file" | cut -f1"
log INFO "Backup completed successfully. Size: ${backup_size}"
return 0
else
log ERROR "Backup failed"
return 1
fi
}
function cleanup_old_backups() {
local days_to_keep=7
log INFO "Cleaning up backups older than ${days_to_keep} days"
find "$BACKUP_ROOT" -type d -mtime +"$days_to_keep" -exec rm -rf {} \; || {
log ERROR "Failed to clean up old backups"
return 1
}
log INFO "Cleanup completed"
}
function send_notification() {
local subject="$1"
local message="$2"
if [ -f "/usr/sbin/sendmail" ]; then
echo -e "Subject: ${subject}\n\n${message}" | sendmail root
log INFO "Notification sent via sendmail"
else
log WARN "Sendmail not found, cannot send notification"
fi
}
function main() {
log INFO "=== Starting System Maintenance ==="
# Check system resources
check_system
# Prompt user for confirmation
read -p "Do you want to proceed with backup? (y/n) " -n 1 -r
echo
if [[ ! "$REPLY" =~ ^[Yy]$ ]]; then
log INFO "Operation cancelled by user"
exit 0
fi
# Perform backup
if create_backup; then
send_notification "Backup Successful" "System backup completed at $(date)"
else
send_notification "Backup Failed" "System backup failed at $(date)"
exit 1
fi
# Cleanup old backups
cleanup_old_backups
log INFO "=== System Maintenance Completed ==="
}
# Entry point
main "$@"
#!/usr/bin/env python3
# Advanced System Monitoring Tool
import psutil
import smtplib
from email.mime.text import MIMEText
import socket
import logging
from datetime import datetime
# Configuration
THRESHOLDS = {
'cpu': 90,
'memory': 85,
'disk': 90
}
LOG_FILE = '/var/log/system_monitor.log'
ALERT_EMAIL = 'admin@example.com'
def setup_logging():
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def check_resources():
"""Check system resources against thresholds"""
alerts = []
# CPU check
cpu_percent = psutil.cpu_percent(interval=1)
if cpu_percent > THRESHOLDS['cpu']:
alerts.append(f"High CPU usage: {cpu_percent}%")
# Memory check
mem = psutil.virtual_memory()
if mem.percent > THRESHOLDS['memory']:
alerts.append(f"High memory usage: {mem.percent}%")
# Disk check
for partition in psutil.disk_partitions():
if 'rw' in partition.opts.split(','):
usage = psutil.disk_usage(partition.mountpoint)
if usage.percent > THRESHOLDS['disk']:
alerts.append(
f"High disk usage on {partition.mountpoint}: {usage.percent}%"
)
return alerts
def send_alert(alerts):
"""Send email alert with issues"""
hostname = socket.gethostname()
subject = f"[ALERT] System issues on {hostname}"
body = "\n".join([
f"System alert at {datetime.now().isoformat()}",
"The following issues were detected:",
""
] + alerts)
msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = 'monitor@example.com'
msg['To'] = ALERT_EMAIL
try:
with smtplib.SMTP('localhost') as server:
server.send_message(msg)
logging.info("Alert email sent successfully")
except Exception as e:
logging.error(f"Failed to send alert email: {str(e)}")
def main():
setup_logging()
logging.info("Starting system monitoring")
alerts = check_resources()
if alerts:
for alert in alerts:
logging.warning(alert)
send_alert(alerts)
else:
logging.info("All systems normal")
logging.info("Monitoring complete")
if __name__ == '__main__':
main()