【shell一天一练】xargs命令和top命令、vmstat命令等监控命令

75 阅读2分钟

今日小练题目📢

写一个监控脚本,监控系统负载,如果系统负载超过10,需要记录系统状态信息。

提示:

1)系统负载命令使用uptime看,过去1分钟的平均负载

2)系统状态使用如下工具标记:top、 vmstat、 ss

3)要求每隔20s监控一次

4)系统状态信息需要保存到/opt/logs/下面,保留一个月,文件名建议带有date +%s后缀或者前缀

优秀作业🤌🏻

#!/bin/sh
#author:xYLiuuuuuu
#version:v1
#date:2024-11-18

[ -d /opt/logs ] || mkdir -p /opt/logs

while :
do
        load=`uptime |awk -F 'average:' '{print $2}'|cut -d',' -f1|sed 's/ //g' |cut -d. -f1`
        if [ $load -gt 10 ]
        then
                top -bn1 |head -n 100 > /opt/logs/top.`date +%s`
                vmstat 1 10 > /opt/logs/vmstat.`date +%s`
                ss -an > /opt/logs/ss.`date +%s`
        fi
        sleep 20
        find /opt/logs \( -name "top*" -o -name "vmstat*" -o -name "ss*" \) -mtime +30 | xargs rm -f
done

敲黑板📝

  • 给变量赋值时,赋值号的周围不能有空格!!! Shell会将空格解释为命令或参数之间的分隔符。这意味着赋值语句将被解析为一个命令,而不是将值赋给变量。
  • 死循环可以使用while : + sleep 组合
  • 边写脚本边在命令行里调试
  • find里可以使用小括号将多个条件组合起来当成一个整体来处理
  • xargs 命令 将标准输入转为命令行参数。xargs 命令教程 - 阮一峰的网络日志
$ command1 | xargs command2

# 相当于执行mkdir one two three`
$ echo "one two three" | xargs mkdir

# 单独使用
$ xargs find -name  # 到这会去等待用户输入
"*.txt"
./foo.txt
./hello.txt

# -d 参数与分隔符
$ echo -e "a\tb\tc" | xargs -d "\t" echo
a b c

# -p 参数,-t 参数  可以打印出转换后的命令
$ echo 'one two three' | xargs -p touch
touch one two three ?...    # 等待用户确认

$ echo 'one two three' | xargs -t rm
rm one two three # 不等用户确认
  • uptime命令,显示系统平均负载
  • top命令,用于持续监视系统性能,动态显示进程信息
-n 获取多次cpu的执行情况,top -n 4:只更新4次
-d 间隔时间,top -d 4:每隔4秒更新一次
-p 获取指定端口进程的数据,top -p 22
  • vmstat命令,查看虚拟内存
-a    显示活跃内存(active)和非活跃内存(inact)
-f    显示从系统启动至今的fork数量 
-m    显示slabinfo
-s    静态显示内存相关信息