Introduction
Phew! After a long time, I’ve finally planned to write a simple blog post on Dev. So, let’s dive in!
We all know that effective server monitoring is essential for maintaining system stability and performance. In this blog post, I’ll show you how to create an enhanced shell script that monitors CPU usage, memory usage, disk space, network activity, running processes, and system uptime in real time.
Prerequisites
Before we begin, ensure you have:
- Ubuntu Instance: Any Ubuntu-based system or virtual machine.
- Basic Knowledge of Shell Scripting: Familiarity with terminal commands and scripting basics.
Step 1: Create a File in Ubuntu
Start by creating a file for your script. Open a terminal and use your preferred text editor. Here, we’ll use vim:
vim monitor_linux.sh
Step 2: Write the Shell Script
Add the following script to the file:
#!/bin/bash
while true; do
clear
echo "System Resource Monitoring"
echo "--------------------------"
# Display CPU usage
echo "CPU Usage:"
top -n 1 -b | grep "Cpu"
# Display memory usage
echo -e "\nMemory Usage:"
free -h
# Display disk space usage
echo -e "\nDisk Space Usage:"
df -h
# Display top 5 processes by memory usage
echo -e "\nTop 5 Processes by Memory Usage:"
ps -eo pid,ppid,cmd,%mem --sort=-%mem | head -6
# Display network usage
echo -e "\nNetwork Usage (bytes received and transmitted):"
echo "Interface RX Bytes TX Bytes"
cat /proc/net/dev | tail -n +3 | awk '{print $1, $2, $10}'
# Display system uptime
echo -e "\nSystem Uptime:"
uptime -p
sleep 5 # Wait for 5 seconds before the next update
done
Step 3: Make the Script Executable
Give the script execute permissions:
chmod +x monitor_linux.sh
Step 4: Run the Script
Run the script to monitor your server:
./monitor_linux.sh
The script will display updated system information every 5 seconds. To stop the script, please use CTRL + C.
Here is the in detail of this script:
- CPU Usage: The top command displays current CPU utilization.
- Memory Usage: The free command shows memory statistics in a human-readable format.
- Disk Space Usage: The df command shows disk space usage for all mounted filesystems.
- Top 5 Processes: The ps command lists the top 5 memory-consuming processes.
- Network Usage: Displays bytes received and transmitted for each network interface using /proc/net/dev.
- System Uptime: The uptime command shows how long the system has been running.
Conclusion
This simple shell script offers a comprehensive view of your Linux server’s performance metrics. You can easily customize it further to include additional monitoring features like I/O statistics, swap usage, or alert mechanisms.
I’m planning to share more technical posts in the future, covering topics like AWS, Kubernetes, Prometheus, Elastic, and more. Until next time, happy learning!
Top comments (0)