服务器巡检脚本python (python自动分析错误日志)

#!/usr/bin/env python2

# -*- coding: UTF-8 -*-

import socket

import time

import requests

import fcntl

import struct

import os

import urllib

import sys

reload(sys)

sys.setdefaultencoding('utf8')

users = {

'xxxx': {

'phone': '111111111',

'mail': 'xxx@asiainfo.com'

}

}

logFiles = {

"/Users/lizhi/welcome.txt": {

'users':['xxx', 'zh'],

'mtime': ''

},

"/Users/lizhi/wget-log": {

'users': ['xxx'],

'mtime': ''

}

}

def get_ip_address(ifname):

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

return socket.inet_ntoa(fcntl.ioctl(

s.fileno(),

0x8915, # SIOCGIFADDR

struct.pack('256s', ifname[:15])

)[20:24])

def MSG(msg):

nowtime = datetime.now()

now = nowtime.strftime('%Y-%m-%d %H:%M:%S')

today = nowtime.strftime( '%Y%m%d')

#定义写入日志写入路径和文件名

logfile = os.getcwd() + '/monitor_url.log'

#print logfile #打印输出位置和文件名 os.linesep 作用是换行

line = now + ' [MONITOR] ' + str(msg)

try:

with open(logfile,'a+') as fh:

fh.write(line)

except Exception, e:

pass

def get_ip_address(ifname):

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

return socket.inet_ntoa(fcntl.ioctl(

s.fileno(),

0x8915, # SIOCGIFADDR

struct.pack('256s', ifname[:15])

)[20:24])

def sendMsg(hostname, fileName, rec):

message = '服务器:{} 在:{} 错误日志:{}有变更!请及时检查!!'.format(hostname, rec['mtime'], fileName)

message = urllib.quote(message.encode('gbk'))

for user in rec['users']:

phone = users[user]['phone']

#短信接口

url = 'http://127.0.0.1:8888/msg/?tos={phone}\&content={message}'.format(phone=phone, message=message)

print url

s=requests.Session()

try:

s.get(url,timeout=5)

except requests.exceptions.RequestException as e:

message="监控短信发送失败,报错内容如下:%s" %(e)

MSG(message) #记录日志

if __name__ == "__main__":

init = True

#hostname = socket.gethostbyname(socket.gethostname())

hostname = get_ip_address('eth0')

while True:

for key, value in logFiles.items():

mtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.stat(key).st_mtime))

if mtime != value['mtime'] and init == False:

value['mtime'] = mtime

sendMsg(hostname, key, value)

value['mtime'] = mtime

init = False

print time.strftime('%Y-%m-%d %H:%M:%S')

time.sleep(5)