#!/usr/bin/env python # -*- coding: utf-8 -*- # 作者:昨夜星辰 # 脚本作用:检查服务器的所有分区,如果分区已使用空间占总空间的百分比超过阀值便发送邮件到告警邮箱。 # 注意事项:该脚本只能在Linux系统下执行,适用于Python 2。 import os import re import smtplib import string # 获取系统所有分区 def getAllPartitionOfSystem(): result = [] f = os.popen(‘mount‘) text = f.readlines() f.close() for line in text: if re.search(r‘\bext\d‘, line): result.append(line.split()[2]) return result # 获取分区已使用空间占总空间的百分比 def getUsedOfPartition(path): sv = os.statvfs(path) free = (sv.f_bavail * sv.f_frsize) total = (sv.f_blocks * sv.f_frsize) used = (sv.f_blocks - sv.f_bfree) * sv.f_frsize return (float(used) / total) * 100 # 发送邮件 def sendmail(ACCOUNT, PASSWORD, HOST, SUBJECT, TO, FROM, TEXT): BODY = string.join(( ‘From: %s‘ % FROM, ‘To: %s‘ % TO, ‘Subject: %s‘ % SUBJECT, ‘‘, TEXT ), ‘\n‘) server = smtplib.SMTP() server.connect(HOST, ‘25‘) server.login(ACCOUNT, PASSWORD) server.sendmail(FROM, [TO], BODY) server.quit() if __name__ == ‘__main__‘: server = ‘XX服务器‘ partitionList = getAllPartitionOfSystem() for partition in partitionList: percent = getUsedOfPartition(partition) if percent > 80: ACCOUNT = ‘[email protected]‘ PASSWORD = ‘xxx‘ HOST = ‘smtp.163.com‘ SUBJECT = ‘%s的%s分区已使用空间占总空间的百分比超过了80%%,请登录服务检查!‘ % (server, partition) TO = ‘[email protected]‘ FROM = ‘[email protected]‘ TEXT = ‘RT‘ sendmail(ACCOUNT, PASSWORD, HOST, SUBJECT, TO, FROM, TEXT)
时间: 2024-10-10 01:01:48