Shell script for system and process monitor
Below is a simple shell script that can SSH from one host to four other remote hosts and checks the memory, CPU usage, and currently running processes for an application. If the CPU or memory usage exceeds 85%, the script will log it and send the output via email in a table format.
Assumptions:
1. The script assumes SSH access to the remote hosts is already set up (using SSH keys or passwordless SSH).
2. The script uses `ps`, `top`, `free`, and `awk` for system resource information.
3. The `mail` command is available on the system for sending emails.
Script: `check_resources.sh`
```bash
#!/bin/bash
Define the list of remote hosts
HOSTS=("host1" "host2" "host3" "host4")
Define the application name to monitor (replace with your app name)
APP_NAME="your_application_name"
Define the email recipient
EMAIL_RECIPIENT="your_email@example.com"
Define the log file
LOG_FILE="/tmp/resource_usage_log.txt"
Initialize the log file
echo "Resource Usage Report - (date)" >LOG_FILE
echo "-------------------------------------------------" >> LOG_FILE
Function to check resource usage on a remote host
check_host_resources()
local host=1
# SSH into the remote host and gather system information
output=(ssh "host" bash <<'EOF'
-----------------------
# Get the current memory and CPU usage
memory_usage=(free | grep Mem | awk 'print3/2 * 100.0')
cpu_usage=(top -bn1 | grep "Cpu(s)" | sed "s/.*, *[0-9.]*%* id.*/\1/" | awk '{print 100 - 1')
# Get application process details (memory and CPU usage)
app_cpu_usage=(ps aux | grep "APP_NAME" | awk 'sum+=3} END {print sum}')
app_mem_usage=(ps aux | grep "APP_NAME" | awk '{sum+=4 END print sum')
# Check if CPU or memory usage is over 85
if (((echo "cpu_usage > 85" | bc -l) )) || (((echo "memory_usage > 85" | bc -l) )) || (((echo "app_cpu_usage > 85" | bc -l) )) || (((echo "app_mem_usage > 85" | bc -l) )); then
echo "host, CPU Usage: cpu_usagememory_usage%, App CPU Usage: app_cpu_usageapp_mem_usage%" >> /tmp/resource_usage_log.txt
fi
EOF
)
# Append the output to the log file
echo "output" >>LOG_FILE
}
Loop over all the hosts and check their resource usage
for host in "HOSTS[@]"; do
echo "Checking resources onhost..."
check_host_resources "host"
done
Send the email with the log file attached
mail -s "Resource Usage Report" -a "LOG_FILE" "EMAIL_RECIPIENT"
Comments
Post a Comment