磁盤容量監控python腳本實作
需求:檢測
/data
路徑下的磁盤容量是否超出門檻值,超出門檻值,發送郵件通知。
代碼:
diskcheck.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
import socket
from email.mime.text import MIMEText
from email.header import Header
import psutil
# 磁盤門檻值
disk_limit = 80
# 監控磁盤的路徑
disk_path = "/data"
def get_host_ip():
"""
查詢本機ip位址
:return: ip
"""
global s
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
def send_email():
"""
發送郵件代碼
"""
ip = get_host_ip()
print(ip)
# 發送者的郵箱
sender = '[email protected]'
# 接受者的郵箱
receivers = ['[email protected]']
message = MIMEText('%s 機器磁盤超出門檻值' % ip, 'plain', 'utf-8')
message['From'] = Header("磁盤容量超出門檻值警告", 'utf-8')
message['To'] = Header("Admin", 'utf-8')
message['Subject'] = Header('磁盤容量超出門檻值警告', 'utf-8')
try:
smtpObj = smtplib.SMTP()
# domain指公司域名
smtpObj.connect("mail.domain.com", 25)
# smtp的使用者登入賬号
smtpObj.login("user", "password")
smtpObj.sendmail(sender, receivers, message.as_string())
print "郵件發送成功"
except smtplib.SMTPException:
print "Error: 無法發送郵件"
def monitor_disk():
"""
disk_usage判斷是否超出界限值
"""
global disk_limit
global disk_path
disk_percent = psutil.disk_usage(disk_path).percent
if disk_percent > disk_limit:
send_email()
else:
print("Disk space usage: {}%".format(disk_percent))
if __name__ == '__main__':
monitor_disk()
每天9點30分定時執行任務:
30 9 * * * python /opt/diskcheck.py