使用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腳本