阅读量:3
设计一个shell程序,每5分钟执行一次获取当前服务器的基本情况(内存使用率,CPU负载,I/O,磁盘使用率),保存到120.20.20.20数据库上数据库帐号aaa密码bbb库名test表名host
创建一个名为server_status.sh
的Shell脚本并添加以下内容:
#!/bin/bash # 获取内存使用率 mem_total=$(free -m | awk 'NR==2{print $2}') mem_used=$(free -m | awk 'NR==2{print $3}') mem_average=$((mem_used * 100 / mem_total)) # 获取CPU负载 load_average1=$(uptime | awk -F ':|+|,' '{print $(NF-4) + 0}') load_average2=$(uptime | awk -F ':|+|,' '{print $(NF-2) + 0}') load_average3=$(uptime | awk -F ':|+|,' '{print $NF}') # 获取I/O io_average=$(iostat -x 1 2 | grep -E '^[a-z]' | awk 'NR==3{print $1 + 0}') # 获取磁盘使用率 disk_usage=$(df -h | awk '$NF=="/"{printf "%s", $5}' | tr -d '%') # 将数据插入数据库 mysql -h120.20.20.20 -uaaa -p'bbb' test -e "INSERT INTO host (ip, mem_usage, load_average1, load_average2, load_average3, io_average, disk_usage) VALUES ('$(hostname)', '$mem_average', '$load_average1', '$load_average2', '$load_average3', '$io_average', '$disk_usage')"
为当前主机创建一个新用户并设置密码(将 your_username 和 your_password 替换为你想要的值): CREATE USER 'your_username'@'%' IDENTIFIED BY 'your_password'; 为新用户授予所有数据库的所有权限: GRANT ALL PRIVILEGES ON *.* TO 'your_username'@'%'; 刷新权限: FLUSH PRIVILEGES; CREATE DATABASE test; CREATE TABLE host ( id INT AUTO_INCREMENT PRIMARY KEY, ip VARCHAR(15) NOT NULL, mem_usage FLOAT NOT NULL, load_average1 FLOAT NOT NULL, load_average2 FLOAT NOT NULL, load_average3 FLOAT NOT NULL, io_average FLOAT NOT NULL, disk_usage FLOAT NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
#!/bin/bash # 获取内存使用率 mem_total=$(free -m | awk 'NR==2{print $2}') mem_used=$(free -m | awk 'NR==2{print $3}') mem_usage=$(echo "scale=2; $mem_used * 100 / $mem_total" | awk '{printf "%.2f", $0}') #mem_usage=$(echo "scale=2; $mem_used * 100 / $mem_total" | bc) 需下载bc命令 # 获取CPU负载 load_avg=$(uptime | awk -F'[, ]+' '{print $9, $10, $11}') # 获取I/O使用情况 io_usage=$(iostat -x 1 2 | awk 'NR==3{if ($1 > 100) print 100; else print $1}') # 获取磁盘使用率 disk_usage=$(df -h | awk '$NF=="/"{printf "%.2f", $5}') # 将数据插入数据库 mysql -h120.20.20.20 -uaaa -p'bbb' test -e "INSERT INTO host (mem_usage, cpu_load, io_usage, disk_usage) VALUES ('$mem_usage', '$load_avg', '$io_usage', '$disk_usage')"
CREATE DATABASE test; CREATE TABLE host ( id INT AUTO_INCREMENT PRIMARY KEY, mem_usage FLOAT NOT NULL, cpu_load VARCHAR(20) NOT NULL, io_usage FLOAT NOT NULL, disk_usage FLOAT NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
使脚本可执行:
chmod +x server_status.sh
接下来,打开Crontab编辑器:
crontab -e
在编辑器中,添加以下行:
*/5 * * * * /path/to/server_status.sh
将/path/to/
替换为实际脚本所在的目录。保存并退出编辑器。
现在,Cron作业将每5分钟运行一次server_status.sh
脚本,并将服务器状态信息插入到远程数据库中。
注意:请确保已在远程数据库(IP:120.20.20.20,用户名:aaa,密码:bbb,数据库名:test)中创建了名为host
的表,并具有适当的字段。以下是一个创建表的示例SQL语句:
CREATE TABLE host ( id INT AUTO_INCREMENT PRIMARY KEY, mem_usage FLOAT NOT NULL, cpu_load VARCHAR(20) NOT NULL, io_usage FLOAT NOT NULL, disk_usage FLOAT NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP );