python中用psutil模块,yagmail模块监控CPU、硬盘、内存使用,阈值后发送邮件

时间:2022-02-21 15:16:43
import yagmail
import psutil
def sendmail(subject,contents):
#连接邮箱服务器
yag = yagmail.SMTP(user='邮箱名称@163.com',password='邮箱客户端授权密码',host='smtp.163.com')
#发送邮件
yag.send(to='收件方邮箱地址',subject=subject, contents=contents)
#断开连接
yag.close() def cpu_info():
cpu = psutil.cpu_percent(1)
return cpu def mem_info():
mem = psutil.virtual_memory()
total_mem = int(mem[0]/1024/1024)
free_mem = int(mem[1]/1024/1024)
percent_mem = mem[2]
used_mem = int(mem[3]/1024/1024)
mem_dict = {
'total_mem':total_mem,
'free_mem':free_mem,
'percent_mem':percent_mem,
'used_mem':used_mem
}
return mem_dict def disk_info():
disk = psutil.disk_usage('c:')
total_disk = int(disk[0]/1024/1024/1024)
used_disk = int(disk[1]/1024/1024/1024)
free_disk = int(disk[2]/1024/1024/1024)
percent_disk = disk[3]
disk_dict = {
'total_disk':total_disk,
'used_disk':used_disk,
'free_disk':free_disk,
'percent_disk':percent_disk
}
return disk_dict def main():
cpu = cpu_info()
mem = mem_info()
disk = disk_info()
msg = '''
cpu利用率:%s%%
内存总大小:%sM
内存剩余大小:%sM
内存使用大小:%sM
内存使用率:%s%%
硬盘总大小:%sG
硬盘使用大小:%sG
硬盘剩余大小:%sG
硬盘使用率:%s%%
''' % (cpu,mem.get('total_mem'),mem.get('free_mem'),mem.get('used_mem'),mem.get('percent_mem'),disk.get('total_disk'),disk.get('used_disk'),disk.get('free_disk'),disk.get('percent_disk'))
if cpu > 1:
print('cpu过高')
sendmail('cpu报警',msg)
else:
print('cpu正常') if __name__ == '__main__':
main()