使用Python统计系统资源占用情况,并针对磁盘占用情况判断是否发邮件提醒管理员。有同样需求的朋友可以自己参考修改一下。
剩下的就是加入crontab中,让脚本定时运行了,so easy。
#!/usr/bin/python
# -*- coding:utf8 -*-
import os, time,re,smtplib,subprocess
from email.mime.text import MIMEText
from email.utils import formataddr
# 获取CPU负载信息
def get_cpu():
last_worktime = 0
last_idletime = 0
f = open("/proc/stat", "r")
line = ""
while not "cpu " in line: line = f.readline()
f.close()
spl = line.split(" ")
worktime = int(spl[2]) + int(spl[3]) + int(spl[4])
idletime = int(spl[5])
dworktime = (worktime - last_worktime)
didletime = (idletime - last_idletime)
rate = float(dworktime) / (didletime + dworktime)
last_worktime = worktime
last_idletime = idletime
if (last_worktime == 0): return 0
return rate
# 获取内存负载信息
def get_mem_usage_percent():
try:
f = open('/proc/meminfo', 'r')
for line in f:
if line.startswith('MemTotal:'):
mem_total = int(line.split()[1])
elif line.startswith('MemFree:'):
mem_free = int(line.split()[1])
elif line.startswith('Buffers:'):
mem_buffer = int(line.split()[1])
elif line.startswith('Cached:'):
mem_cache = int(line.split()[1])
elif line.startswith('SwapTotal:'):
vmem_total = int(line.split()[1])
elif line.startswith('SwapFree:'):
vmem_free = int(line.split()[1])
else:
continue
f.close()
except:
return None
physical_percent = usage_percent(mem_total - (mem_free + mem_buffer + mem_cache), mem_total)
virtual_percent = 0
if vmem_total > 0:
virtual_percent = usage_percent((vmem_total - vmem_free), vmem_total)
return physical_percent, virtual_percent
def usage_percent(use, total):
try:
ret = (float(use) / total) * 100
except ZeroDivisionError:
raise Exception("ERROR - zero division error")
return ret
# 获取磁盘根目录占用信息
def disk_info():
statvfs = os.statvfs('/') #根目录信息 可根据情况修改
total_disk_space = statvfs.f_frsize * statvfs.f_blocks
free_disk_space = statvfs.f_frsize * statvfs.f_bfree
disk_usage = (total_disk_space - free_disk_space) * 100.0 / total_disk_space
disk_usage = int(disk_usage)
disk_tip = "硬盘空间使用率(最大100%):" + str(disk_usage) + "%"
return disk_tip
# 获取内存占用信息
def mem_info():
mem_usage = get_mem_usage_percent()
mem_usage = int(mem_usage[0])
mem_tip = "物理内存使用率(最大100%):" + str(mem_usage) + "%"
return mem_tip
# 获取CPU占用信息
def cpu_info():
cpu_usage = int(get_cpu() * 100)
cpu_tip = "CPU使用率(最大100%):" + str(cpu_usage) + "%"
return cpu_tip
# 获取系统占用信息
def sys_info():
load_average = os.getloadavg()
load_tip = "系统负载(三个数值中有一个超过3就是高):" + str(load_average)
return load_tip
# 获取计算机当前时间
def time_info():
now_time = time.strftime('%Y-%m-%d %H:%M:%S')
return "主机的当前时间:%s" %now_time
# 获取计算机主机名称
def hostname_info():
hostnames = os.popen("hostname").read().strip()
return "你的主机名是: %s"%hostnames
# 获取IP地址信息
def ip_info():
ipadd = os.popen("ip a| grep ens192 | grep inet | awk '{print $2}'").read().strip()
return ipadd
# 获取根的占用信息
def disk_info_root():
child = subprocess.Popen(["df", "-h"], stdout=subprocess.PIPE)
out = child.stdout.readlines()
for item in out:
line = item.strip().split()
# 我这里只查看centos的根
if '/dev/mapper/centos-root' in line:
title = [u'-文件系统-',u'--容量-', u'-已用-', u'-可用-', u'-已用-', u'-挂载点--']
content = "\t".join(title)
if eval(line[4][0:-1]) > 60:
line[0] = 'centos-root'
content += '\r\n' + '\t'.join(line)
return content
# 将系统信息发送到指定邮箱
def send_mail(info):
my_sender = '[email protected]' # 发件人邮箱账号
my_pass = 'password' # 发件人邮箱密码
my_user = '[email protected]' # 收件人邮箱账号,我这边发送给自己
ret = True
try:
msg = MIMEText(info, 'plain', 'utf-8')
msg['From'] = formataddr(["发送着", my_sender]) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
msg['To'] = formataddr(["接收者", my_user]) # 括号里的对应收件人邮箱昵称、收件人邮箱账号 昵称无法显示
msg['Subject'] = "服务器资源占用统计"+time.strftime('%Y-%m-%d %H:%M:%S') # 邮件的主题,也可以说是标题
server = smtplib.SMTP_SSL("smtphz.qiye.163.com", 994) # 发件人邮箱中的SMTP服务器,端口是25
server.login(my_sender, my_pass) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(my_sender, [my_user, ], msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit() # 关闭连接
except Exception: # 如果 try 中的语句没有执行,则会执行下面的 ret=False
ret = False
return ret
# 测试程序
if __name__ == "__main__":
disk_information = disk_info()
disk_usage = [int(s) for s in re.findall(r'\b\d+\b', disk_information)]
infomation = [hostname_info(),time_info(),disk_information]
# 如果磁盘占用高于60%就发邮件告警
if disk_usage[1]>60:
send_mail('\r\n'.join(infomation))
# print(hostname_info())
# print(time_info())
# print(ip_info())
# print(sys_info())
# print(cpu_info())
# print(mem_info())
# print(disk_info())
[root@myservice ~]# crontab -e
00 6 * * * python2 ~/disk.py >/dev/null 2>&1
#!/usr/bin/python
# -*- coding:utf8 -*-
import os
from collections import namedtuple
disk_ntuple = namedtuple('partition', 'device mountpoint fstype')
usage_ntuple = namedtuple('usage', 'total used free percent')
# 获取当前操作系统下所有磁盘
def disk_partitions(all=False):
"""Return all mountd partitions as a nameduple.
If all == False return phyisical partitions only.
"""
phydevs = []
f = open("/proc/filesystems", "r")
for line in f:
if not line.startswith("nodev"):
phydevs.append(line.strip())
retlist = []
f = open('/etc/mtab', "r")
for line in f:
if not all and line.startswith('none'):
continue
fields = line.split()
device = fields[0]
mountpoint = fields[1]
fstype = fields[2]
if not all and fstype not in phydevs:
continue
if device == 'none':
device = ''
ntuple = disk_ntuple(device, mountpoint, fstype)
retlist.append(ntuple)
return retlist
# 统计某磁盘使用情况,返回对象
def disk_usage(path):
"""Return disk usage associated with path."""
st = os.statvfs(path)
free = (st.f_bavail * st.f_frsize)
total = (st.f_blocks * st.f_frsize)
used = (st.f_blocks - st.f_bfree) * st.f_frsize
try:
percent = ret = (float(used) / total) * 100
except ZeroDivisionError:
percent = 0
# NB: the percentage is -5% than what shown by df due to
# reserved blocks that we are currently not considering:
# http://goo.gl/sWGbH
return usage_ntuple(total, used, free, round(percent, 1))
print(disk_partitions())
def getPath():
"""
获取磁盘的分区
"""
disklist = []
list = disk_partitions()
for i in list:
disklist.append(i[1])
return disklist
# pathlist = getPath()
# print "path list is ....%s" % pathlist
# print disk_usage('/')
def getDiskTotal():
"""
获取磁盘总的大小
"""
newpathlist = []
pathlist = []
pathlist = getPath()
print("pathlist type is %s ,and the pathlist value is %s" % (type(pathlist), pathlist))
# pathlist.append("/dev/sda1") #可以增加文件系统
totalDiskList = []
usedDiskList = []
# print newpathlist
sum = 0
used = 0
for path in pathlist:
disktotal = disk_usage(path)[0] / 1073741824 + 1
usedtotal = disk_usage(path)[1] / 1073741824 + 1
totalDiskList.append(disktotal)
usedDiskList.append(usedtotal)
for count in totalDiskList:
sum += count
for use in usedDiskList:
used += use
print("磁盘总共空间(G)")
print(sum)
print("磁盘使用空间(G)")
print(used)
getDiskTotal()
Python SMTP发送邮件
通过python查出服务器磁盘容量
Linux服务器CPU使用率、内存使用率、磁盘空间占用率、负载情况的python脚本