背景:python實現linux檔案系統監控,當某個目錄使用達到某個閾值的時候,自動傳送檔案告警
實現工具:
python 2.7
linux shell
ansible 2.5.0
**實現:
# -*- coding:utf-8 -*-
import os
import commands
import json
import smtplib
from email.mime.text import mimetext
from email.header import header
'''fsmon.sh 內容
#df -m|grep -v system
#df -m|grep sd|awk ''|grep -eo [0-9]+
hostname
df -m|grep sd
'''def sendmail(mailcontent):
# 配置傳送方和接收方
sender = '***@***.com'
receiver = '***@***.com'
# acc = '***@***.com'
subject = "caution: linux檔案系統監控告警 !!"
smtpserver = 'mail.***xx.com'
username = 'oakefe'
password = 'abcd1234'
# 定義傳送郵件的內容 和 主題
mailcontent = mailcontent
msg = mimetext(mailcontent, 'plain', 'utf-8')
msg['from'] = header(sender, 'utf-8')
msg['to'] = header(receiver, 'utf-8')
msg['subject'] = header(subject, 'utf-8')
# 執行傳送動作
try:
smtp = smtplib.smtp()
smtp.connect(smtpserver)
smtp.login(user=sender, password=password)
# smtp.sendmail(from_addr=sender, to_addrs=receiver.split(',') + acc.split(','), msg=msg.as_string())
smtp.sendmail(from_addr=sender, to_addrs=receiver.split(','), msg=msg.as_string())
smtp.quit()
print "告警郵件傳送成功"
except exception, e:
print "告警郵件傳送失敗" + str(e)
#################
### 主操作流程
#################
(status, output) = commands.getstatusoutput("ansible 10.1.19.6 -m script -a '/tmp/wmpmon/fsmon.sh' --tree '/tmp'") #測試status
file = open("/tmp/10.1.19.6","r")
file_fact = json.loads(file.read(), 'utf-8')
## print file_fact
contentlist = file_fact["stdout_lines"]
#主機名
hostname = contentlist[0]
# [0] 掛載的磁碟 [4]使用百分比 [5]掛載的作業系統目錄
# /dev/sda1 1014 172 843 17% /boot
for i in range(1,len(contentlist)):
filesystemfact = contentlist[i].split()[0]
totalfact = contentlist[i].split()[1]
usedfact = contentlist[i].split()[2]
freefact = contentlist[i].split()[3]
usedpercentfact = contentlist[i].split()[4].split("%")[0]
mounteddi***ct = contentlist[i].split()[5]
mailcontent = u"主機名:" + hostname +u", 檔案系統: "+ filesystemfact + u",使用百分比: " + usedpercentfact + u"%,掛載目錄: " + mounteddi***ct
if int(usedpercentfact) >= 85:
sendmail(mailcontent)
82 2 監控檔案系統
誰開啟了該檔案?顯示開啟檔案filename的程序 lsof filename列出某個目錄下被開啟的檔案 lsof tmp command pid user fd type device size off node name seahorse 4158 neo cwd dir 8,2 53248 1...
監控檔案系統的變化
首先安裝aide檔案監控工具 yum install aide y etc aide.conf 配置檔案 3 define dbdir var lib aide 4 define logdir var log aide 以上是它的變數 7 database file aide.db.gz 是以.gz...
監控檔案系統的變化
首先安裝aide檔案監控工具 yum install aide y etc aide.conf 配置檔案 3 define dbdir var lib aide 4 define logdir var log aide 以上是它的變數 7 database file aide.db.gz 是以.gz...