编写脚本,实时监控本机内存和硬盘剩余空间,剩余内存小于500M、根分区剩余空间小于1000M时,发送报警邮件给root管理员 (提示:如果提示找不到mail命令,请使用yum install mailx -y安装) (1)查看根分区剩余空间 df / (2)查看内存剩余空间 free (3)发送邮件 mail -s
时间: 2024-03-26 14:39:17 浏览: 76
好的,以下是脚本的代码:
```
#!/bin/bash
# 获取根分区剩余空间
free_space=$(df / | awk '/\//{print $(NF-2)}')
# 获取内存剩余空间
free_mem=$(free | awk '/Mem/{print $4}')
# 判断是否需要发送邮件
if [[ $free_space -lt 1000000 || $free_mem -lt 500000 ]]; then
echo "Warning: Root partition free space is less than 1000M or free memory is less than 500M!" | mail -s "System Alert!" root
fi
```
解释一下代码:
首先通过 `df /` 命令获取根分区剩余空间,然后使用 awk 命令提取出空间大小并赋值给变量 `free_space`。
接着使用 `free` 命令获取内存剩余空间,同样使用 awk 命令提取出空间大小并赋值给变量 `free_mem`。
最后通过 if 判断语句判断根分区剩余空间是否小于 1000M 或内存剩余空间是否小于 500M,如果满足条件则发送报警邮件给 root 管理员。邮件内容为 "Warning: Root partition free space is less than 1000M or free memory is less than 500M!",主题为 "System Alert!"。邮件发送使用了 mail 命令,如果提示找不到该命令需要先安装 mailx。
阅读全文
相关推荐















