Only Script You Need for Monitor Linux instance or CloudPanel!

Linux system administrators often face the challenge of monitoring numerous performance metrics, logs, and system health parameters.

Traditionally, you’d rely on a variety of tools and scripts to gather data on disk usage, CPU performance, memory status, network traffic, and system logs. But what if you could have one script to monitor everything on your Linux system?

In this blog post, we’ll show you how to set up a single monitoring script that gives you insights into every crucial aspect of your Linux system.

From CPU usage to disk space, memory consumption to network activity, In this script will provide a one-stop solution for your system monitoring needs.

Let’s dive into it!

Why Monitoring Is Critical

Monitoring your Linux system is crucial for several reasons:

  1. System Health: Proactively identifying issues before they become critical can help avoid system downtime.
  2. Performance Optimization: Monitoring resource usage allows you to adjust your system to ensure peak performance.
  3. Security: Regular monitoring helps detect abnormal patterns that could indicate security breaches or attacks.
  4. Log Management: Effective monitoring includes tracking logs to troubleshoot any errors or warnings promptly.

While there are numerous tools like top, htop, iftop, and df, managing multiple monitoring solutions can become cumbersome. With a single script, you simplify your workflow and have a centralized point of reference for your system’s health.

Setting Up a One-Script Solution

Before creating the script, let’s outline what it needs to monitor:

  1. CPU Usage: Keep an eye on your system’s processor performance.
  2. Memory Usage: Monitor RAM and swap usage.
  3. Disk Usage: Ensure that your file systems aren’t getting too full.
  4. Network Activity: Track incoming and outgoing traffic.
  5. Running Processes: Watch for any rogue or resource-hogging processes.
  6. System Logs: Continuously monitor critical log files for errors or warnings.

The Complete Monitoring Script

Here’s a comprehensive script that combines all the above metrics into one output. You can schedule this to run at intervals or execute it manually when needed.

#!/bin/bash
# Colors for readability
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color
echo -e "${GREEN}===== System Monitoring Script =====${NC}"
# 1. CPU Usage
echo -e "${YELLOW}\n>> CPU Usage: ${NC}"
mpstat | awk '/all/ {print "CPU Load: " $3 "% idle"}'
# 2. Memory Usage
echo -e "${YELLOW}\n>> Memory Usage: ${NC}"
free -h | awk '/Mem/ {print "Total Memory: " $2 "\nUsed: " $3 "\nFree: " $4}'
echo -e "Swap:\n"$(free -h | awk '/Swap/ {print "Total: " $2 ", Used: " $3 ", Free: " $4}')
# 3. Disk Usage
echo -e "${YELLOW}\n>> Disk Usage: ${NC}"
df -h | grep '^/dev' | awk '{print $1 ": " $5 " used, " $4 " available"}'
# 4. Network Traffic
echo -e "${YELLOW}\n>> Network Traffic: ${NC}"
ifstat -i eth0 1 1 | awk 'NR==3 {print "RX: " $1 " KB/s, TX: " $2 " KB/s"}'
# 5. Top 5 Memory Consuming Processes
echo -e "${YELLOW}\n>> Top 5 Memory Consuming Processes: ${NC}"
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -n 6
# 6. Top 5 CPU Consuming Processes
echo -e "${YELLOW}\n>> Top 5 CPU Consuming Processes: ${NC}"
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -n 6
# 7. System Logs Monitoring
echo -e "${YELLOW}\n>> Recent Errors in System Logs: ${NC}"
journalctl -p 3 -xb | tail -n 10
echo -e "${GREEN}===== Monitoring Completed =====${NC}"

Breakdown of the Script

  1. CPU Usage: We use mpstat to get CPU load, particularly focusing on how much idle time the CPU has. If this value is low, your system is under heavy load.
  2. Memory Usage: The free -h command gives a human-readable summary of memory and swap usage. High memory usage can indicate an application using excessive resources.
  3. Disk Usage: df -h shows disk space usage for each partition. Disk space running low can cause performance degradation and system crashes, so this is crucial.
  4. Network Traffic: Using ifstat, the script monitors the incoming and outgoing network traffic on a specific interface (in this case, eth0).
  5. Top 5 Memory and CPU Consuming Processes: With ps, the script lists the top 5 processes that are using the most memory and CPU, helping you pinpoint resource-heavy tasks.
  6. System Logs Monitoring: The journalctl command displays recent errors from system logs, helping you identify issues that might not yet be affecting system performance but are critical to investigate.

Automating the Monitoring Script

While manually running this script is useful, it becomes even more powerful when set to run automatically at intervals. You can do this using cron, the task scheduler built into Linux.

Install Packages

sudo apt install sysstat ifstat

Setting Up a Cron Job

To schedule the script to run, say every hour, follow these steps:

Open your crontab file:

crontab -e

Add the following line to schedule the script to run hourly:

0 * * * * /path/to/your_script.sh >> /var/log/system_monitor.log

This will execute the script every hour on the hour and log the output to a file.

Visualizing Your Data

While the script outputs information to your terminal or logs, you may want to visualize the data, especially if you’re managing a production server. For this, you can integrate the script with tools like Grafana and Prometheus. These tools collect and graph data, giving you an interactive, visual representation of your system’s performance over time.

Enhancing Security with Monitoring

System monitoring isn’t just about performance; it also plays a vital role in security. For example:

  • Log Monitoring: Keeping an eye on system logs helps you detect suspicious activities like repeated login attempts or unauthorized access.
  • Process Monitoring: Watching the processes on your system can reveal malware or unnecessary background tasks.
  • Network Traffic: Monitoring incoming and outgoing traffic may reveal abnormal patterns or potential security breaches.

Having a single script to monitor everything on your Linux system saves you time and makes the monitoring process more efficient. This approach combines multiple critical system checks into one easy-to-manage script, giving you a quick overview of your system’s health at any given moment.

By automating this process with cron jobs and visualizing the data with tools like Grafana, you can ensure that your system is running smoothly and identify issues before they escalate into critical problems.

Helpful Tip: Customize this script based on your system’s unique needs. You can add other checks, such as temperature monitoring for hardware or I/O statistics for high-performance environments.
If you need more inputs on the script, please comment below.

1 Like