Linux基础
1 前言
某些场景,我们不方便使用Zabbix去监控服务器的硬盘空间,所以需要使用单机脚本实现。
2 实践部分
2.1 准备工作
2.1.1 测试邮件发送功能
echo "This is test mail" | mail -s "Test mail" will@cmdschool.org
注:邮件发送功能配置请参阅以下文档,
https://www.cmdschool.org/archives/1560
2.1.2 新建脚本目录
mkdir ~/scripts
2.2 编辑脚本
vi ~/scripts/check-filesystem-space.sh
输入如下内容,
#!/bin/bash ########################################################################################## # Filename : $RCSfile$ # Source : $Source$ # Current Rev : $Revision$ # On branch : $Name$ # Last change by will on 06/15 2018 # # Change History (CVS checkin 'cvs commit ' and enter comments) # - $Log$ # - # ----------------Do not Edit above this line ------------------------------------------- # # Description : in n1.cmdschool.org n2.cmdschool.org # # Functions :monitor filesystem used space.if ge 85 then send mail to admin # # Location : ~/scripts/check-filesystem-space.sh # # To Do : # ########################################################################################## #remote machine, if used space ge 80 then send mail to admin user=root #公钥认证的用户 adminList="will@cmdschool.org" #管理员的邮箱,使用空格分隔 machineList="n1.cmdschool.org n2.cmdschool.org" #机器的名称,使用空格分隔 use=85 #当分区空间达到85%时,向管理员发送警告邮件 checkSpace() { user=$1 machine=$2 use=$3 parList=`ssh $user@$machine df -k | awk '{print $(NF-1),$(NF)}' | grep -vE "Mounted on|/dev|/dev/shm|//|:/"` j=0 pass=0 outList="" for i in $parList; do ((j=j+1)) if [ `expr $j % 2` -ne 0 ]; then if [ `echo $i | cut -d% -f1` -ge $use ]; then pass=1 else pass=0 fi fi if [ `expr $j % 2` -eq 0 ] && [ $pass -eq 1 ]; then outList="$outList $i" fi done if [ "$outList" != "" ]; then echo -e $outList else echo "" fi } for i in $machineList; do machine=$i partition=`checkSpace $user $machine $use` if [ "$partition" != "" ]; then ssh $user@$machine df -kh | mail -s "In $machine filesystem:($partition) will run out of space!" $adminList fi done
注:以上注意更改“adminList”变量的管理员邮箱和machineList的邮箱名称
2.3 配置公钥认证
2.3.1 生成公钥和私钥
首先用账号密码登陆到应用程序服务器
ssh-keygen -t rsa
向导如下:
Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /root/.ssh/id_rsa. Your public key has been saved in /root/.ssh/id_rsa.pub. The key fingerprint is: […]
注:一路回车
2.3.2 部署公钥
ssh-copy-id -i ~/.ssh/id_rsa.pub root@n1 ssh-copy-id -i ~/.ssh/id_rsa.pub root@n2
注:将公钥复制到被控制的机器
2.3.3 测试公钥认证
ssh root@n1 ssh root@n2
2.4 定制脚本触发
2.4.1 每分钟一次
*/1 * * * * /scripts/check-filesystem-space.sh 2>&1 > /dev/null
2.4.2 每30分钟一次
*/30 * * * * /scripts/check-filesystem-space.sh 2>&1 > /dev/null
2.4.3 每小时一次
* */1 * * * /scripts/check-filesystem-space.sh 2>&1 > /dev/null
注:以上选择一种方式即可,不同的只是检查的频率
没有评论