Essential Shell Scripts for Linux Ops: Alerts, MySQL Backup, and Traffic Monitoring
This article provides ready‑to‑use Shell scripts for Linux system alerts, automated MySQL database backups, and real‑time network interface traffic monitoring, offering sysadmins practical code snippets and configuration steps to streamline routine operations.
Shell scripting is a fundamental tool for Linux system administrators, enabling automation of repetitive tasks such as sending alerts, backing up databases, and monitoring network traffic. Below are three practical scripts that can be copied directly into your environment.
1. Linux System Alert Script
Configure mailx to send email notifications and create a simple script to trigger alerts.
# yum install mailx
vi /etc/mail.rc
set [email protected] smtp=smtp.163.com
set [email protected]
set smtp-auth-password=123456
set smtp-auth=login2. MySQL Database Backup Loop
This Bash script iterates over all non‑system databases on a MySQL server, creates a timestamped dump for each, and stores the files in /data/db_backup.
#!/bin/bash
DATE=$(date +%F_%H-%M-%S)
HOST=localhost
USER=backup
PASS=123.com
BACKUP_DIR=/data/db_backup
DB_LIST=$(mysql -h $HOST -u $USER -p$PASS -s -e "show databases;" 2>/dev/null | egrep -v "Database|information_schema|mysql|performance_schema|sys")
for DB in $DB_LIST; do
BACKUP_NAME=$BACKUP_DIR/${DB}_${DATE}.sql
if ! mysqldump -h $HOST -u $USER -p$PASS -B $DB > $BACKUP_NAME 2>/dev/null; then
echo "$BACKUP_NAME backup failed!"
fi
done3. Real‑Time Network Interface Traffic Script
Pass the network interface name as the first argument to monitor inbound and outbound traffic in KB/s, updating every second.
#!/bin/bash
NIC=$1
echo -e " In ------ Out"
while true; do
OLD_IN=$(awk "'$0~\"$NIC\"{print $2}'" /proc/net/dev)
OLD_OUT=$(awk "'$0~\"$NIC\"{print $10}'" /proc/net/dev)
sleep 1
NEW_IN=$(awk "'$0~\"$NIC\"{print $2}'" /proc/net/dev)
NEW_OUT=$(awk "'$0~\"$NIC\"{print $10}'" /proc/net/dev)
IN=$(printf "%.1fKB/s" $((($NEW_IN-$OLD_IN)/1024)))
OUT=$(printf "%.1fKB/s" $((($NEW_OUT-$OLD_OUT)/1024)))
echo "$IN $OUT"
sleep 1
doneThese scripts illustrate core automation techniques for system monitoring and maintenance, and can be adapted to fit specific environments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
