ansible_使用ansible+shell脚本进行环境巡检

一、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

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

3. 执行脚本

ansible local -m shell -a "~/check.sh" -i hosts

二、定时任务巡检记录日志

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

3. 添加定时任务

crontab -e
# 添加以下内容,每天9点巡检
0 9 * * * ~/xunjian.sh

4.查看巡检结果

# 查看当天的巡检
cat ~/inspection.log
# 查看历史巡检
cd ~/logs
ls

参考

https://www.jianshu.com/p/031a0214f931

https://blog.csdn.net/yxys01/article/details/77367733

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值