Posted on
Administration

How to Create a Bash Script to Monitor System Resources

Author
  • User
    Linux Bash
    Posts by this author
    Posts by this author

How to Create a Bash Script to Monitor System Resources

Monitoring system resources is vital for ensuring stable and efficient system performance. Bash scripts offer a lightweight and customizable way to track CPU usage, memory consumption, disk space, and more. This guide walks you through creating a Bash script to monitor these resources and explores advanced customizations for enhanced functionality.


Step 1: Writing a Basic Monitoring Script

Here's a fundamental Bash script for monitoring CPU, memory, and disk usage:

#!/bin/bash

# Variables
LOG_FILE="/var/log/system_monitor.log" # Log file for resource data
THRESHOLD_CPU=80                       # CPU usage threshold (in %)
THRESHOLD_MEM=80                       # Memory usage threshold (in %)
THRESHOLD_DISK=90                      # Disk usage threshold (in %)

# Function to log system metrics
log_metrics() {
  echo "[$(date)] CPU: $(top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}')%" >> "$LOG_FILE"
  echo "[$(date)] Memory: $(free | grep Mem | awk '{print $3/$2 * 100.0}')%" >> "$LOG_FILE"
  echo "[$(date)] Disk: $(df / | grep / | awk '{print $5}')" >> "$LOG_FILE"
}

# Function to check thresholds and alert
check_thresholds() {
  CPU=$(top -bn1 | grep 'Cpu(s)' | awk '{print $2 + $4}')
  MEM=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
  DISK=$(df / | grep / | awk '{print $5}' | tr -d '%')

  if (( $(echo "$CPU > $THRESHOLD_CPU" | bc -l) )); then
    echo "[$(date)] ALERT: CPU usage is above $THRESHOLD_CPU%: $CPU%" >> "$LOG_FILE"
  fi

  if (( $(echo "$MEM > $THRESHOLD_MEM" | bc -l) )); then
    echo "[$(date)] ALERT: Memory usage is above $THRESHOLD_MEM%: $MEM%" >> "$LOG_FILE"
  fi

  if (( $DISK > $THRESHOLD_DISK )); then
    echo "[$(date)] ALERT: Disk usage is above $THRESHOLD_DISK%: $DISK%" >> "$LOG_FILE"
  fi
}

# Main script
log_metrics
check_thresholds

Note: you may need to install bc, try using apt-get install bc for Debian-based systems, dnf install bc for Fedora/RHEL-based systems, or zypper install bc for openSUSE systems.


Step 2: Automating the Script with Cron

To ensure the script runs at regular intervals, schedule it using cron:

  1. Open the crontab editor:

    crontab -e
    
  2. Add an entry to execute the script every 5 minutes:

    */5 * * * * /path/to/system_monitor.sh
    
  3. Save and exit. The script will now run automatically.


Step 3: Enhancements and Customizations

1. Email Notifications

You can configure the script to send email alerts using tools like mailx. Here’s an example:

# Install mailx if not already installed
# apt-get install mailutils (for Debian-based systems)
# dnf install s-nail (for RHEL based since v9)
# zypper install mailx (for openSUSE systems)

send_email_alert() {
  local SUBJECT="Resource Usage Alert"
  local BODY="Alert: High resource usage detected. Check logs for details."
  echo "$BODY" | mailx -s "$SUBJECT" user@example.com
}

# Add this function call to the alert conditions in the script
send_email_alert

2. Detailed Metrics

Extend the script to include more data points. For example, to log network activity:

log_network_activity() {
  echo "[$(date)] Network Activity: $(sar -n DEV 1 1 | grep Average | grep eth0)" >> "$LOG_FILE"
}

# Call this function within log_metrics
log_network_activity

3. Graphical Visualization

Export collected data to visualization tools. For example, generate CSV files for Grafana:

export_to_csv() {
  echo "Timestamp,CPU Usage,Memory Usage,Disk Usage" > /var/log/system_metrics.csv
  while IFS= read -r line; do
    CPU=$(echo "$line" | grep "CPU:" | awk '{print $2}')
    MEM=$(echo "$line" | grep "Memory:" | awk '{print $2}')
    DISK=$(echo "$line" | grep "Disk:" | awk '{print $2}')
    echo "$(date),$CPU,$MEM,$DISK" >> /var/log/system_metrics.csv
  done < "$LOG_FILE"
}

# Schedule this function to run periodically using cron

4. Remote Monitoring

Use SSH to collect data from multiple servers:

monitor_remote_server() {
  local REMOTE_SERVER="user@remote-server"
  ssh "$REMOTE_SERVER" "bash -s" < /var/log/system_monitor.sh
}

# Call this function to include remote server monitoring
monitor_remote_server

Conclusion

Creating a Bash script to monitor system resources is an effective way to ensure system stability and performance. By automating the process and adding customizations like email alerts, detailed metrics, and remote monitoring, you can tailor the solution to meet your specific needs. Start building your own monitoring script today to stay ahead of potential issues.

Further Reading

For those interested in diving deeper into Bash scripting and system monitoring, the following resources provide comprehensive information and advanced tutorials to expand your skill set:

  • Advanced Bash-Scripting Guide: This in-depth guide offers everything from beginner to advanced scripting techniques, which are useful in further customizing your system monitoring scripts.

  • Linux Performance: This site offers detailed articles on monitoring and optimizing Linux system performance, including real-case scenarios and performance debugging.

  • Grafana Labs: Learn how to visualize your monitoring data using Grafana. This site provides documentation and tutorials that help in setting up dashboards for visualizing the data collected by your Bash scripts.

  • DigitalOcean Community Tutorials: DigitalOcean provides a series of tutorials on Linux system monitoring and Bash scripting that can be invaluable for both beginners and experienced developers.

These resources will help you enhance your knowledge and skills in system monitoring with Bash scripts, allowing you to build more robust and sophisticated monitoring solutions.