监控文件更新时间的python脚本

#!/usr/bin/python
# -*- #coding:cp936

import os
import socket
import time
import datetime
import string
import email
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

authInfo = {}
authInfo['server'] = '******'
authInfo['user'] = '******'
authInfo['password'] = '******'
fromAdd = '<******>'
toaddmon = ['******']

subject = 'Log Error!'

def getip():
    global ip
    if os.name == 'nt':
        ip=socket.gethostbyname(socket.gethostname())
    if os.name == 'posix':
        cmd3 = "/sbin/ifconfig eth0 |grep \"inet addr:\" |awk \'{print $2}\'|cut -c 6-"
        ip = os.popen(cmd3).read().rstrip()
    return ip

def sendemail(authInfo, fromAdd, toAdd, subject, body):
    strFrom = fromAdd
    strTo = ', '.join(toAdd)
    server = authInfo.get('server')
    user = authInfo.get('user')
    passwd = authInfo.get('password')
    if not (server and user and passwd) :
        print 'incomplete login info, exit now'
        return
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)
    msgText = MIMEText(body, 'html', 'gb2312')
    msgAlternative.attach(msgText)
    smtp = smtplib.SMTP()
    smtp.set_debuglevel(1)
    smtp.connect("mail.xyz.com")
    smtp.login(user, passwd)
    smtp.sendmail(strFrom, strTo, msgRoot.as_string())
    smtp.quit()
    return

def gettimediff(path):
    temptime = time.ctime(os.stat(path).st_mtime)
    modifiedth = temptime.split(':')[0][len(temptime.split(':')[0])-2:len(temptime.split(':')[0])]
    modifiedtm = temptime.split(':')[1][0:2]
    now = time.strftime("%H:%M:%S",time.localtime())
    nowth = now.split(':')[0]
    nowtm = now.split(':')[1]
    tempm = int(nowth)*60 + int(nowtm) - (int(modifiedth)*60 + int(modifiedtm))
    tempm = abs(tempm)
    print tempm
    body = ip + ' ' + path + ' ' + str(tempm) + ' '
    if tempm > 5:
        sendemail(authInfo, fromAdd, toaddmon, subject, body)

def main ():
    today = (datetime.date.today().isoformat())
    timestamp = datetime.datetime.strftime(datetime.datetime.today(),"%y%m%d")
    getip()
    gettimediff('/usr/local/apache/logs/access/access_log.' + timestamp + '.txt')

main()

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注