编程需求:
日常巡检是每一个运维必须要做的事情,如果能用脚本实现的话,那将大大简化巡检的工作难度!
现编写一个日常巡检脚本!
源代码
#!/bin/bash
#输入不同字符完成不同巡检内容
#作者:洪思源
#打印提示符
HINT(){
read -p "请按回车继续:"
}
#查看CPU信息
CPU_INFO(){
echo
echo -e "\033[4;31mPrint the CPU info:\033[0m"
cat /proc/cpuinfo | awk 'BEGIN {FS=":"} /model name/{print "CPU Model:" $2 }'
cat /proc/cpuinfo | awk 'BEGIN {FS=":"} /cpu MHz/{print "CPU Speed:" $2"MHz"}'
grep -Eq 'svm|vmx' /proc/cpuinfo && echo "Virtualization: Support" || \
echo "Virtualization: No Support"
echo
}
#查看系统负载
LOAD_INFO(){
echo -e "\033[4;31mPrint the system load:\033[0m"
uptime | awk 'BEGIN{FS=":"} {print $5}' | awk 'BEGIN{FS=","}\
{print "Last 1 minutes system load:"$1"\n""Last 5 minutes system load:"$2"\n"\
"Last 15 minutes system load:"$3}'
echo
}
#查看内存与交换分区信息
MEM_INFO(){
echo
echo -e "\033[4;31mPrint the Memory and Swap info:\033[0m"
free | grep Mem | awk '{print "Mem free: "$5" Bytes"}'
free | grep Swap | awk '{print "Swap free: "$4" Bytes"}'
echo
}
#查看磁盘挂载信息
DISK_INFO(){
echo
echo -e "\033[4;31mPrint system disk space usage:\033[0m"
df -h
echo
}
while true
do
clear
echo "------------------------------------------------------"
echo "1. 查看CPU信息"
echo "2. 查看系统负载"
echo "3. 查看内存与交换分区信息"
echo "4. 查看磁盘挂载信息"
echo "5. 退出系统"
echo "-------------------------------------------------------"
read -p "请选择1-4选项:" U_SELECT
#通过调用函数名称调用函数
case $U_SELECT in
1)
CPU_INFO
HINT
;;
2)
LOAD_INFO
HINT
;;
3)
MEM_INFO
HINT
;;
4)
DISK_INFO
HINT
;;
5)
exit
;;
*)
read -p "请选择1-4选项,输入回车继续:"
esac
done
代码运行结果
1. 查看CPU信息
2. 查看系统负载
3. 查看内存与交换分区信息
4. 查看磁盘挂载信息
5. 退出系统
-------------------------------------------------------
请选择1-4选项:1
Print the CPU info:
CPU Model: Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
CPU Model: Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
CPU Model: Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
CPU Model: Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
CPU Speed: 834.765MHz
CPU Speed: 844.726MHz
CPU Speed: 838.476MHz
CPU Speed: 854.492MHz
Virtualization: Support
请按回车继续:
请选择1-4选项:2
Print the system load:
Last 1 minutes system load: 0.88
Last 5 minutes system load: 0.57
Last 15 minutes system load: 0.47
请选择1-4选项:3
Print the Memory and Swap info:
Mem free: 10657284 Bytes
Swap free: 0 Bytes
Print system disk space usage:
文件系统 容量 已用 可用 已用% 挂载点
/dev/sda2 99G 21G 74G 22% /
devtmpfs 7.8G 0 7.8G 0% /dev
tmpfs 7.8G 26M 7.8G 1% /dev/shm
tmpfs 7.8G 11M 7.8G 1% /run
tmpfs 7.8G 0 7.8G 0% /sys/fs/cgroup
/dev/sda1 293G 52G 227G 19% /var/lib/libvirt/images
/dev/loop0 8.8G 8.8G 0 100% /var/ftp/centos-1804
tmpfs 1.6G 40K 1.6G 1% /run/user/1000
/dev/sdb1 29G 368M 29G 2% /run/media/student/3514-8688
请选择1-4选项:5