Automated System Monitoring and Service Management Scripts
Disk Space Alert Script
Monitor avialable disk space and send alerts when below threshold.
Prerequisites
Install email utilities:
yum install mailx -y
Configure email settings in /etc/mail.rc.
Implementation
Create a monitoring script at /root/disk_check.sh:
#!/bin/bash
# Check available disk space
available_space=$(df / | awk 'NR==2 {print $4}')
# Convert to gigabytes
space_gb=$((available_space / 1024 / 1024))
# Alert if less than 20GB
if [ "$space_gb" -lt 20 ]; then
echo "Warning: Available disk space is ${space_gb}GB" | mail -s "Disk Space Alert" admin@example.com
fi
Schedule daily execution using cron:
vim /etc/crontab
0 0 * * * root /bin/bash /root/disk_check.sh
Web Server Status Checker
Verify service status through process and port inspetcion.
Process-Based Check
#!/bin/bash
# Verify nginx process
process_count=$(pgrep nginx | wc -l)
if [ "$process_count" -gt 0 ]; then
echo "nginx is active"
else
echo "nginx is inactive, initiating startup..."
# Install and start services
yum install nginx -y > /dev/null
systemctl start nginx
systemctl start firewalld
# Configure firewall
firewall-cmd --permanent --zone=public --add-service=http > /dev/null
firewall-cmd --permanent --zone=public --add-port=80/tcp > /dev/null
firewall-cmd --reload > /dev/null
echo "nginx has been started"
fi
Port-Based Verification
#!/bin/bash
# Check for listening HTTP port
port_check=$(ss -tuln | grep :80 | wc -l)
if [ "$port_check" -gt 0 ]; then
echo "nginx is active"
else
echo "nginx is inactive, initiating startup..."
# Install and start services
yum install nginx -y > /dev/null
systemctl start nginx
systemctl start firewalld
# Configure firewall
firewall-cmd --permanent --zone=public --add-service=http > /dev/null
firewall-cmd --permanent --zone=public --add-port=80/tcp > /dev/null
firewall-cmd --reload > /dev/null
echo "nginx has been started"
fi
Web Accessibility Validator
Test web server connectivity and return appropriate status codes.
#!/bin/bash
# Retrieve IP address
server_ip=$(ip addr show ens32 | grep inet | awk '{print $2}' | cut -d'/' -f1)
# Test connection
response=$(curl -s -o /dev/null -w "%{http_code}" http://$server_ip)
case $response in
200)
echo "web server is running"
;;
*)
echo "web not accessible"
exit 12
;;
esac