Linux

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > Linux > Ubuntu监控内存、磁盘和cpu使用率shell脚本

Ubuntu服务器上监控内存、磁盘和cpu使用率shell脚本详解

作者:夜半子时

还在为服务器性能监控发愁?本文手把手教你用Shell脚本监控Linux系统的CPU、内存和磁盘使用情况,并配合crontab定时任务实现自动化报警,附Python发送邮件脚本,让你轻松掌握服务器运行状态

一、监控系统cpu的情况

  1. 使用top命令查看linux系统cpu使用情况:
	#抓取cpu的总核数 
	grep -c 'model name' /proc/cpuinfo
	
	#使用top命令查看linux系统cpu使用情况:(-b -n 1 表只需要1次的输出结果)
	top -b -n 1 | grep Cpu
	
	us:用户态使用的cpu时间比
	sy:系统态使用的cpu时间比
	ni:用做nice加权的进程分配的用户态cpu时间比
	id:空闲的cpu时间比
	wa:cpu等待磁盘写入完成时间
	hi:硬中断消耗时间
	si:软中断消耗时间
	st:虚拟机偷取时间
	
	查看截取空闲cpu的百分比数值命令(只取整数部分 | cut -f 1 -d "."):
	top -b -n 1 | grep Cpu | awk '{print $8}' | cut -f 1 -d "."
  1. 编写cpu监控的脚本文件 cpu-usage.sh:
	#!/bin/bash
	#获取空闲CPU百分比 取整数部分
	cpuUsage=$(top -b -n 1 | grep Cpu | awk '{print $8}' | cut -f 1 -d ".")
	#cpu剩余告警阀值
	max=20
	# 如果cpu空闲使用率小于等于 max
	if [[ ${cpuUsage} -le ${max} ]]; then
	# $1 监控服务器ip
	python /opt/disk-monitor/mail.py xxx@qq.com "cpu-usage" "$1 上CPU剩余可用 : $cpuUsage %,使用率已经超过 $max %  时间: $(date)"
	fi
  1. 脚本启动命令:
	# 用bash 而不是sh命令启动;ip 为监控服务器ip
	bash cpu-usage.sh ip

二、监控服务器磁盘使用情况

  1. 查看服务磁盘使用情况:
	# 查看服务器磁盘使用情况
	df -h
	#返回值说明
	Filesystem   指定文件系统的名称
	Size         总磁盘内存
	Used         已用磁盘内存
	Avail        可用磁盘内存
	Use%         磁盘内存使用率
	Mounted on   指定的文件系统的挂载点,即目录
  1. 编写磁盘监控的脚本文件 disk-usage-alert.sh:
	#!/bin/bash
	# 获取服务器Filesystem 为 /dev/sda1 (即 / 目录)的内存使用率
	used=$(df -Ph | grep '/dev/sda1' | awk {'print $5'})
	# 磁盘使用率告警阀值
	max=65%
	if [ ${used%?} -ge ${max%?} ]; then
	python /opt/disk-monitor/mail.py xxx@qq.com "disk-usage-alert" "$1 上磁盘内存剩余可用 : $used %,使用率已经超过 $max %  时间: $(date)"
	fi
  1. 脚本启动命令:
	# 用bash 而不是sh命令启动;ip 为监控服务器ip
	bash  disk-usage-alert.sh ip

三、监控服务器内存使用情况

  1. 查看服务内存使用情况:
	# 查看服务器内存使用情况
	free -m
	#返回值说明
	total 	表示物理,内存总量
	used 	总计分配给缓存(包含Buffer和cache)使用的数量,但其中可能部分缓存并未实际使用
	free 		未被分配的内存
	shared 共享内存,一般系统不会用到,这里也不讨论
	buffers 系统分配但未被使用的buffers数量
	cached 系统分配但未被使用的cache数量

  1. 编写内存监控的脚本文件memory-monitor.sh:
	#!/bin/bash
	#获取空闲内存,单位MB
	memfree=$(free -m | grep Mem | awk '{print $4}')
	#内存剩余告警阀值,根据实际情况配置
	max=1024
	# 如果未分配内存值小于等于 max
	if [[ ${memfree} -le ${max} ]]; then
	python /opt/disk-monitor/mail.py xxx@qqq.com "memory-monitor" "$1 上内存剩余可用 : $memfree Mb,  时间: $(date)"
	fi

  1. 脚本启动命令:
	# 用bash 而不是sh命令启动;ip 为监控服务器ip
	bash  memory-monitor.sh ip

四、定时任务执行shell脚本

添加定时任务,以下两种方式均可

1.修改 crontab 文件

vi /etc/crontab

2.crontab命令添加

crontab -e

定时任务 :

	# */30   * * * * 每隔30分钟执行一次定时任务
	# /opt/disk-monitor/disk-usage-alert.sh shell脚本路径
	# 192.168.1.1 监控服务器ip
	*/30   * * * * root    bash /opt/disk-monitor/disk-usage-alert.sh 192.168.1.1

五、发送邮件mail的python脚本:mail.py

#!/usr/bin/env python
#-*- coding: UTF-8 -*-
import os,sys
reload(sys)
sys.setdefaultencoding('utf8')
import getopt
import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from  subprocess import *

def sendqqmail(username,password,mailfrom,mailto,subject,content):
    # 邮箱的服务地址
    gserver = 'smtp.exmail.qq.com'
    gport = 465
    try:
    	# 发送邮件内容
        msg = MIMEText(content ,'plain', 'utf-8')
        # 发件人
        msg['from'] = mailfrom
        # 收件人
        msg['to'] = mailto
        msg['Reply-To'] = mailfrom
        msg['Subject'] = subject
        msg['Accept-Language']='zh-CN'
        msg['Accept-Charset']='ISO-8859-1,utf-8'
        smtp = smtplib.SMTP_SSL(gserver, gport)
        smtp.set_debuglevel(0)
        smtp.login(username,password)
        smtp.sendmail(mailfrom, mailto.split(','), msg.as_string())
        smtp.close()
    except Exception,err:
        print "Send mail failed. Error: %s" % err
def main():
    to=sys.argv[1]
    subject=sys.argv[2]
    content=sys.argv[3]
    print ('content:'+content)
    #定义QQ邮箱的账号和密码,你需要修改成你自己的账号和密码
    sendqqmail('发件人邮箱账号','发件人邮箱密码','发件人邮箱账号',to,subject,content)
if __name__ == "__main__":
    main()

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文