How to Build a Lightweight VPS Monitoring and Telegram Alert System Using Glances and Bash
Introduction: The Challenge of Lightweight Server Monitoring
For system administrators, DevOps engineers, and business owners alike, maintaining the health and uptime of a Virtual Private Server (VPS) is critical. However, traditional enterprise monitoring solutions such as Zabbix, Prometheus, or Datadog often introduce significant resource overhead. On smaller VPS instances with limited RAM and CPU cores, running these heavy monitoring agents can ironically degrade the very performance you are trying to protect.
To solve this dilemma, we can engineer a streamlined, ultra-lightweight monitoring and alerting framework. By combining the real-time diagnostic power of Glances with a tailored Bash script and the Telegram Bot API, you can establish an instantaneous notification system that consumes virtually zero idle resources. This comprehensive guide walks you through the complete setup from scratch.
Why Glances and Bash Scripting?
Before diving into the technical implementation, it is important to understand why this specific stack offers an ideal balance between efficiency and capability for production environments.
- Glances (Python-based): Unlike complex suite tools, Glances provides a comprehensive overview of system resources (CPU, Memory, Disk I/O, Network, and Processes) in a highly optimized format. It can expose this data via a fast, lightweight RESTful JSON API.
- Bash Scripting: A native shell script executes directly within the operating system environment. It requires no heavy runtimes, making it the fastest and least resource-intensive method for parsing text, calculating thresholds, and executing conditional logic.
- Telegram Bot API: Telegram provides a robust, free, and secure webhook platform for instantaneous push notifications. By utilizing simple
curlHTTP POST requests, your server can alert your mobile or desktop device within milliseconds of an anomaly.
Prerequisites and Environment Setup
To follow this tutorial, you will need root or sudo access to a Linux VPS (such as Ubuntu 22.04 or 24.04 LTS). Ensure your system packages are fully updated before proceeding by executing:
sudo apt update && sudo apt upgrade -yStep 1: Installing Glances
Glances is available in most standard Linux repositories, but to ensure you have the required dependencies for its JSON API mode, we recommend installing it along with python3-pip and the jq utility, which our Bash script will use to parse JSON data.
Run the following command to install the necessary packages:
sudo apt install glances jq curl -yOnce installed, you can verify that Glances is operational by running the glances command in your terminal. Press q to exit the interactive interface.
Configuring Glances as a Background Service
To ensure our monitoring system runs continuously and survives system reboots, we must configure Glances to run in API mode as a background daemon controlled by systemd.
Creating the systemd Service File
Create and edit a new systemd service file using your preferred text editor:
sudo nano /etc/systemd/system/glances-api.servicePaste the following configuration into the file:
[Unit]
Description=Glances API Daemon
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/glances -w --api-port 61208
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.targetThis configuration instructs Glances to start a web server (-w) exposing the raw performance metrics via an API on port 61208, bound strictly to local access for maximum security.
Enabling and Starting the Service
Reload the systemd manager configuration, enable the service to start automatically on boot, and start it immediately:
sudo systemctl daemon-reload sudo systemctl enable glances-api.service sudo systemctl start glances-api.serviceYou can verify that the API is responding correctly by querying it locally via curl:
curl [http://127.0.0.1:61208/api/3/cpu/user](http://127.0.0.1:61208/api/3/cpu/user)Setting Up Your Telegram Notification Bot
To receive instant alerts on your smartphone or computer, you must create a dedicated Telegram Bot and obtain your unique Chat ID.
- Open the Telegram application and search for @BotFather.
- Send the command
/newbotand follow the prompts to assign a name and username for your monitoring bot. - Securely save the HTTP API Token provided by BotFather (e.g.,
123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ). - To acquire your personal Chat ID, search for @userinfobot on Telegram and send any message. It will immediately reply with your numerical ID. Alternately, add your bot to a specific monitoring group and extract the group chat ID.
Writing the Automation and Alerting Bash Script
Now, we will write the core intelligence of our system: a robust Bash script that queries the Glances API, extracts key performance indicators (KPIs), evaluates them against safety thresholds, and dispatches alerts when boundaries are crossed.
Creating the Script
Create a directory for your monitoring scripts and open a new file:
sudo mkdir -p /opt/monitoring
sudo nano /opt/monitoring/vps_monitor.shInject the following production-ready Bash script. Be sure to replace the placeholder values with your actual Telegram Token and Chat ID.
#!/bin/bash
# --- CONFIGURATION ---
TELEGRAM_TOKEN="YOUR_TELEGRAM_BOT_TOKEN"
CHAT_ID="YOUR_TELEGRAM_CHAT_ID"
SERVER_NAME=$(hostname)
# Thresholds (Percentage)
CPU_THRESHOLD=85
MEM_THRESHOLD=90
DISK_THRESHOLD=85
# Glances API URL
API_URL="[http://127.0.0.1:61208/api/3](http://127.0.0.1:61208/api/3)"
# --- METRIC COLLECTION ---
# Fetch data using curl and parse with jq
CPU_USAGE=$(curl -s "$API_URL/cpu" | jq '.total' | cut -d. -f1)
MEM_USAGE=$(curl -s "$API_URL/mem" | jq '.percent' | cut -d. -f1)
DISK_USAGE=$(curl -s "$API_URL/fs" | jq '.[0].percent' | cut -d. -f1)
# Fallback check if API is unreachable
if [ -z "$CPU_USAGE" ] || [ -z "$MEM_USAGE" ] || [ -z "$DISK_USAGE" ]; then
ALERT_MSG="⚠️ *CRITICAL ALERT: [$SERVER_NAME]*\nGlances API monitoring service is unreachable! Check server status immediately."
curl -s -X POST "[https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage](https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage)" -d "chat_id=$CHAT_ID" -d "text=$ALERT_MSG" -d "parse_mode=Markdown"
exit 1
fi
# --- ALERTS LOGIC ---
ALERT_TRIGGERED=false
NOTIFICATION_BODY="⚠️ *RESOURCE ALERT: [$SERVER_NAME]*\n\n"
if [ "$CPU_USAGE" -gt "$CPU_THRESHOLD" ]; then
NOTIFICATION_BODY+="🔴 *High CPU Usage:* ${CPU_USAGE}% (Threshold: ${CPU_THRESHOLD}%)\n"
ALERT_TRIGGERED=true
fi
if [ "$MEM_USAGE" -gt "$MEM_THRESHOLD" ]; then
NOTIFICATION_BODY+="🔴 *High Memory Allocation:* ${MEM_USAGE}% (Threshold: ${MEM_THRESHOLD}%)\n"
ALERT_TRIGGERED=true
fi
if [ "$DISK_USAGE" -gt "$DISK_THRESHOLD" ]; then
NOTIFICATION_BODY+="🔴 *Critical Disk Space:* ${DISK_USAGE}% (Threshold: ${DISK_THRESHOLD}%)\n"
ALERT_TRIGGERED=true
fi
# --- SEND DISPATCH ---
if [ "$ALERT_TRIGGERED" = true ]; then
curl -s -X POST "[https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage](https://api.telegram.org/bot$TELEGRAM_TOKEN/sendMessage)" \
-d "chat_id=$CHAT_ID" \
-d "text=$NOTIFICATION_BODY" \
-d "parse_mode=Markdown"
fiMaking the Script Executable
For security, modify the script's permissions so that it can be executed securely by authorized users:
sudo chmod +x /opt/monitoring/vps_monitor.shYou can execute a manual test by temporarily lowering the thresholds in the script configuration to 10% and running sudo /opt/monitoring/vps_monitor.sh. You should receive a notification on Telegram instantly.
Automating the System with Cron
To transform this setup into an autonomous monitoring engine, we must instruct the system to run the script automatically at regular intervals using the Linux cron scheduler.
Open the system crontab configuration tool:
sudo crontab -eTo run the health check routine every 5 minutes, append the following cron expression to the bottom of the file:
*/5 * * * * /opt/monitoring/vps_monitor.sh > /dev/null 2>&1Save and close the file. The cron daemon will automatically parse the entry and initialize the monitoring schedule without needing a system restart.
Conclusion and Operational Best Practices
By implementing this custom architecture, you have established a highly resilient, enterprise-capable alert system that protects your digital infrastructure while saving vital system resources. To ensure optimal performance moving forward, consider implementing these production strategies:
- Fine-Tune Thresholds: Adjust your CPU, RAM, and Disk thresholds according to the specific workload profiles of your application to mitigate alert fatigue.
- Monitor Multi-Disk Volumes: If your VPS utilizes separate mount points for storage and system runtimes, expand the script's
jqfiltering arrays to evaluate all active storage systems. - Network Constraints: Keep the Glances API isolated to
localhost(127.0.0.1) as specified in our systemd configuration to avoid exposing system telemetry data to the public internet.
