• Kloudnative
  • Posts
  • Only Script You Need for Monitoring Linux !

Only Script You Need for Monitoring Linux !

Unlock full transparency into your Linux system's operations with this powerful monitoring script.

In partnership with

Linux system administrators often juggle a multitude of performance metrics, logs, and health parameters to keep their systems running smoothly. Traditionally, this involves a mix of tools and scripts to monitor various aspects such as disk usage, CPU performance, memory status, network traffic, and system logs. But what if there was a way to streamline this process with just one script that could provide insights into every critical component of your Linux system?

In this blog post, we’ll guide you through setting up a single monitoring script that covers everything from CPU usage to disk space, memory consumption to network activity. This script will serve as your all-in-one solution for monitoring the health and performance of your Linux environment.

Kloudnative is committed to staying free for all our users. We kindly encourage you to explore our sponsors to help support us.

There’s a reason 400,000 professionals read this daily.

Join The AI Report, trusted by 400,000+ professionals at Google, Microsoft, and OpenAI. Get daily insights, tools, and strategies to master practical AI skills that drive results.

☝️ Support Kloudnative by clicking the link above to explore our sponsors!

Why Use a Single Monitoring Script?

Managing multiple tools can be cumbersome and inefficient. With a unified script, you can:

  • Simplify Monitoring: Instead of switching between different tools, you’ll have all the information you need in one place.

  • Save Time: A single script reduces the time spent on setup and maintenance.

  • Enhance Insights: By consolidating metrics, you can gain better insights into how different components interact.

Why Monitoring Is Critical?

Monitoring your Linux system is crucial for several reasons:

1. System Health

Proactively identifying issues before they escalate can significantly reduce the risk of system downtime. Regular monitoring allows you to catch potential problems early, ensuring your system remains operational and reliable.

2. Performance Optimization

By keeping an eye on resource usage, you can make necessary adjustments to maintain peak performance. Monitoring tools help you analyze CPU, memory, and disk usage, enabling you to optimize resource allocation and prevent bottlenecks.

3. Security

Consistent monitoring is critical for detecting abnormal patterns that may indicate security breaches or attacks. By tracking network traffic and system logs, you can quickly respond to potential threats and safeguard your data.

4. Log Management

Effective monitoring includes comprehensive log management, allowing you to track errors and warnings promptly. This capability is vital for troubleshooting issues as they arise, ensuring that you can maintain system integrity. While there are numerous tools available—such as top, htop, iftop, and df—managing multiple monitoring solutions can become cumbersome. A single script simplifies your workflow by providing a centralized point of reference for your system's health, making it easier to monitor and manage various performance metrics.

Benefits of Using a Single Monitoring Script

  • Streamlined Workflow: Instead of juggling different tools, you can access all critical information from one script.

  • Time Efficiency: A unified approach reduces the time spent on setup and maintenance.

  • Enhanced Visibility: Consolidating metrics enhances your ability to spot trends and anomalies in your system's performance.

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.