Commit 4306958d authored by Ranjithkumar R 's avatar Ranjithkumar R

Script for monitoring the temperature of the server

parents
#!/bin/bash
#Cheking lm-sensors command
if command -v sensors 2>&1 >/dev/null
then
echo "sensors command already found"
else
# Check for internet connection
if ! wget -T 3 --spider https://www.google.com 2>&1; then
echo "No internet connection. Exiting."
exit 1
fi
# Detect OS and install lm-sensors
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
else
echo "Unable to detect operating system. Exiting."
exit 1
fi
echo "Detected OS: $OS"
# Install lm-sensors based on the OS
if [[ "$OS" == "ubuntu" || "$OS" == "debian" ]]; then
echo "Installing lm-sensors using apt..."
sudo apt update
sudo apt install -y lm-sensors
elif [[ "$OS" == "centos" || "$OS" == "rhel" || "$OS" == "fedora" ]]; then
echo "Installing lm-sensors using yum..."
sudo yum install -y lm_sensors
else
echo "Unsupported OS. please install lm-sensors manually and run the script again."
exit 1
fi
# Run sensors-detect to set up sensors (Auto-detect all)
echo "Running sensors-detect..."
yes | sudo sensors-detect > /dev/null
fi
# Create the monitoring script
LOG_FILE="$HOME/temp_monitor.log"
MONITOR_SCRIPT="/usr/local/bin/temp_monitor.sh"
echo "Creating temperature monitoring script..."
sudo tee $MONITOR_SCRIPT > /dev/null << 'EOF'
#!/bin/bash
# Maximum allowed temperature in Celsius
MAX_TEMP=75.0
# Get the current CPU temperature
CURRENT_TEMP=$(sensors | awk '/Core [0-9]+:/ {print $3}' | sed 's/+//g;s/°C//g' | sort -nr | head -n 1)
# Log file location
LOG_FILE="$HOME/temp_monitor.log"
# Log the current temperature
echo "$(date): Current temperature is $CURRENT_TEMP°C" >> $LOG_FILE
# Check if temperature exceeds the threshold
if [ $(echo "$CURRENT_TEMP > $MAX_TEMP" | bc -l) -eq 1 ]; then
echo "$(date): WARNING: Temperature exceeded $MAX_TEMP°C. Shutting down server!" >> $LOG_FILE
echo "Temperature exceeded on $(hostname) - Shutting down the server in 10 seconds!"
sleep 10
sudo /sbin/shutdown -h now
fi
EOF
# Make the script executable
sudo chmod +x $MONITOR_SCRIPT
# Set up log rotation for the log file to prevent filling up space
echo "Setting up log rotation..."
LOGROTATE_CONF="/etc/logrotate.d/temp_monitor"
sudo tee $LOGROTATE_CONF > /dev/null << EOF
$LOG_FILE {
weekly
rotate 4
compress
missingok
notifempty
create 640 root root
}
EOF
# Set up a cron job to run the monitoring script every minute
CRON_CHECK=$(sudo crontab -l |grep temp_monitor | wc -l )
if [ $CRON_CHECK -gt 0 ]
then
echo "Please remove the existing cronjob /usr/local/bin/temp_monitor.sh"
else
echo "Setting up cron job for temperature monitoring..."
(sudo crontab -l 2>/dev/null; echo "*/5 * * * * /usr/local/bin/temp_monitor.sh 1>&2 > ~/temp_monitor_cron.out") | sudo crontab -
echo "Temperature monitoring setup completed."
fi
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment