ansible性能巡检+定时任务执行shell脚本

发布时间 2023-11-13 16:48:31作者: 往事已成昨天

一、ansible_使用ansible+shell脚本进行环境巡检
1.编写脚本
# 用户目录下执行
cd ~
# 编辑
vi check.sh
实现效果:
脚本内容:

巡检指标1: cpu使用率大于70 ,输出unhealth

巡检指标2: 内存使用率大于70 ,输出unhealth

巡检指标3:/picclife磁盘使用率大于70,输出unhealth

#!/bin/bash
# cpu巡检
sar 3 5| grep Average| awk '{print "cpu use:"100-$8"%"}'
sar 3 5| grep Average| awk '{if ((100-$8) >70) print "unhealth" ;}'

# 内存巡检
free -m | sed -n '2p'| awk '{print "Memory_total: "$2"M use: "$3/$2*100"%"}'
free -m | sed -n '2p'| awk '{if (($3/$2*100) >70) print "unhealth" ;}'

# 磁盘巡检
df -h /picclife | sed -n '2p'| awk '{print "Disk_total:"$2" use:"$5""}'
df -h /picclife | sed -n '2p'| awk '{print ""$5""}' |cut -d '%' -f 1 | awk '{if ($1 >70) print "unhealth" ;}'

 


给check.sh赋执行权限

chmod +x check.sh
1
2. 拷贝脚本
# 删除local组机器的~/check.sh 文件(如果已存在删除)
ansible local -m shell -a "rm ~/check.sh" -i hosts
# 拷贝ansible机器的check.sh到local组机器,src为当前机器,dest为目标机器路径
ansible local -m copy -a "src=~/check.sh dest=~/check.sh mode=0750 " -i hosts
1
2
3
4
3. 执行脚本
ansible all -m shell -a "~/check.sh" -i hosts
1
二、定时任务巡检记录日志
1. 创建巡检脚本
# 用户目录创建巡检脚本
touch xunjian.sh
# 赋权
chmod u+x xunjian.sh
# 创建logs目录
mkdir logs
# 编辑内容
vi xunjian.sh


2. 添加以下内容
#!/bin/bash
echo "+++++++++++++++++++++++++++++++++++++++++++++++"> ~/inspection.log
date +%F >> ~/inspection.log
echo "+++++++++++++++++++++++++++++++++++++++++++++++">> ~/inspection.log
ansible local -m shell -a "~/check.sh" -i hosts >> ~/inspection.log
cp ~/inspection.log ~/logs/inspection-`date +%y%m%d`.log
1
2
3
4
5
6
3. 添加定时任务
crontab -e
# 添加以下内容,每天9点巡检
0 9 * * * ~/xunjian.sh
1
2
3
4.查看巡检结果
# 查看当天的巡检
cat ~/inspection.log
# 查看历史巡检
cd ~/logs
ls

 坑: