linux 监控cpu、磁盘和内存的shell脚本并写成定时任务

最近在学shell脚本开发,然后就想写一个简单的监控脚本,然后做成定时任务,期间碰到了定时任务不生效的问题。在这里统一记录下来
shell脚本如下:

#!/bin/bash
#获取ip地址
#ip=`ifconfig eth0 | grep "inet" | cut -f 2 -d ":"`
#获取系统总核数
#cpu_num=`grep -c 'model name' /proc/cpuinfo`
#cpu_num=grep -c 'cpu cores' /proc/cpuinfo 
#获取当前时间
now=`date -u -d"+8 hour" +'%Y-%m-%d %H:%M:%S'`
#cpt使用阈值
cpu_warn='75'
#mem空闲阈值
mem_warn='100'
#disk使用阈值
disk_warn='90'
#------cpu
function item_cpu(){
    
    
	cpu_idle=` top -b -n 1 | grep Cpu |awk {
     
     'print $8'}|cut -f 1 -d "."`
	#cpu使用率
	cpu_use=`expr 100 - $cpu_idle`
	echo "$now 当前的cpu使用率为 $cpu_use" >> /linuxTest/cpu.log
	if [[ $cpu_use -gt $cpu_warn ]]; then
		echo "cpu报警" >> /linuxTest/cpu.log  #这里的文件类型要写成绝对路径,要不然定时任务会不生效
	else
		echo "cpu使用正常" >> /linuxTest/cpu.log
	fi
}

#----mem内存
function item_mem(){
    
    
	mem_free=`free -m |grep "Mem"| awk {
     
     'print $4+$6'}`
	echo "$now 当前内存剩余空间为 $mem_freeMB" >> /linuxTest/mem.log
	if [[ $mem_free -lt $mem_warn  ]]; then
		echo "mem报警" >> /linuxTest/mem.log
	else
		echo "mem使用正常" >> /linuxTest/mem.log
	fi

}


#----disk磁盘
function item_disk(){
    
    
	disk_use=`df -P | grep /dev | grep -v -E '(tmp|boot)' | awk '{print $5}' | cut -f 1 -d "%"`
	echo "$now 当前磁盘使用率为 $disk_use %" >> /linuxTest/disk.log
	if [[ $disk_use -gt $disk_warn ]]; then
		echo "disk报警" >> /linuxTest/disk.log
	else
		echo "disk使用正常" >> /linuxTest/disk.log
	
	fi

}

item_cpu
item_disk
item_mem

写完shell脚本之后就想这跑个定时任务

命令是:crontab -e
然后就会进入到定时任务的编写中(有关定时任务的参数可以自己百度)
我写了一个每分钟都执行的测试案例
命令是:* * * * * /linuxTest/cpuWatch.sh

然后写完命令后重启crond的服务,发现这个定时任务一直都没有跑起来,去查了一下资料后,设置了几个参数
1.首先 tail -100f /var/log/messages 查看系统运行的日志,发现了
crond: sendmail: fatal: parameter inet_interfaces: no local interface found for ::1,解决完这个问题后,还是没有跑起来
2.然后把日志的文件路径写成了绝对路径后,就可以跑起来了

在这里插入图片描述

嘿嘿,解决问题的感觉还是很爽的!虽然是个小问题,可是这种成就感还是很好的

猜你喜欢

转载自blog.csdn.net/weixin_39040527/article/details/109648462