其主要目的是:基于 Python 編程語言來監(jiān)控服務(wù)器的 CPU、內(nèi)存、/目錄、/appslog、/bigdata目錄使用率以及網(wǎng)卡接收和發(fā)送情況。
該腳本部署場景分為:服務(wù)端和客戶端。
服務(wù)端:一臺固定 IP 地址的服務(wù)器
客戶端:N 臺指定固定 IP 地址的服務(wù)器
服務(wù)端腳本:
- - coding:utf-8 - -
import io
import os
import sys
import logging
from logging import handlers
import MySQLdb
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
import requests, json
import datetime
import time
import shutil,re
import uuid
import socket
import SocketServer
if sys.getdefaultencoding() != 'utf-8':
reload(sys)
sys.setdefaultencoding('utf-8')
class Logger(object):
level_relations = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'crit': logging.CRITICAL
} # 日志級別關(guān)系映射
def init (self,logname, level='info', when='D', backCount=10, fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
CURRENT_DIR = os.path.dirname(file)
LOG_FILE = os.path.abspath(os.path.join(CURRENT_DIR, logname))
self.logger = logging.getLogger(LOG_FILE)
format_str = logging.Formatter(fmt) # 設(shè)置日志格式
self.logger.setLevel(self.level_relations.get(level)) # 設(shè)置日志級別
sh = logging.StreamHandler() # 往屏幕上輸出
sh.setFormatter(format_str) # 設(shè)置屏幕上顯示的格式
th = handlers.TimedRotatingFileHandler(
filename=LOG_FILE, when=when, backupCount=backCount, encoding='utf-8') # 往文件里寫入#指定間隔時間自動生成文件的處理器
#實例化TimedRotatingFileHandler
#interval是時間間隔,backupCount是備份文件的個數(shù),如果超過這個個數(shù),就會自動刪除,when是間隔的時間單位,單位有以下幾種:
S 秒
M 分
H 小時、
D 天、
W 每星期(interval==0時代表星期一)
midnight 每天凌晨
th.setFormatter(format_str) # 設(shè)置文件里寫入的格式
#self.logger.addHandler(sh) # 把對象加到logger里
if not self.logger.handlers:
self.logger.addHandler(th)
class Analysis(object):
def buildMsg(self,msg):
print('構(gòu)造預(yù)警信息'+str(msg))
icount = 0
if(float(msg[4]) > 90):
icount+=1
CPU ="> CPU預(yù)警:使用率高于90%,使用"+str(msg[4])+"% \\n"
else:
CPU=""
if(float(msg[5]) > 90):
icount+=1
mem ="> 內(nèi)存預(yù)警:使用率高于90%,使用"+str(msg[5])+"% \\n"
else:
mem=""
if(float(msg[6]) > 85):
icount+=1
disk_root ="> 磁盤根目錄預(yù)警:使用率高于85%,使用"+str(msg[6])+"% \\n"
else:
disk_root=""
if(float(msg[7]) > 85):
icount+=1
disk_appslog ="> 業(yè)務(wù)磁盤預(yù)警:使用率高于85%,使用"+str(msg[7])+"% \\n"
else:
disk_appslog=""
if(float(msg[8]) > 3000):
icount+=1
networkRecv ="> 網(wǎng)卡10秒內(nèi)接收數(shù)據(jù)預(yù)警:接收數(shù)據(jù)大于4000M,接收"+str(msg[8])+"M \\n"
else:
networkRecv=""
if(float(msg[9]) > 3000):
icount+=1
networkSend ="> 網(wǎng)卡10秒內(nèi)發(fā)送數(shù)據(jù)預(yù)警:發(fā)送數(shù)據(jù)大于4000M,發(fā)送"+str(msg[9])+"M \\n"
else:
networkSend=""
s= alarmName+"\\n"+msg[2]+":" +msg[3]+"\\n" +CPU+mem+disk_root+disk_appslog+networkRecv+networkSend
#print(s)
log.logger.info('預(yù)警信息:'+s)
#發(fā)送預(yù)警
if(icount>0):
#發(fā)送預(yù)警郵件、企業(yè)微信
if mailconf ==1:
self.send_mail(s,msg[3])
if wxconf ==1:
self.send_WX(s)
def send_mail(self,content,ip):
smtpserver = 'smtp.163.com'
mail_user="xxx@163.com"
mail_pass="passwordxxx"
mail_res=["xxx@163.com","xxx@163.com","xxx@163.com","xxx@163.com","xxx@163.com","xxx@163.com","xxx@163.com"]
sub = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
msg = MIMEText( sub + "\\n"+content, _subtype='plain',_charset='utf-8')
msg['Subject'] = Header(alarmName+':'+ip, 'utf-8' )
#msg['From'] = Header("系統(tǒng)預(yù)警", 'utf-8')
msg['From'] = formataddr(pair=('設(shè)備預(yù)警', mail_user))
msg['To'] = ', '.join(mail_res)
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.starttls()
smtp.login(mail_user, mail_pass)
smtp.sendmail(mail_user, mail_res, msg.as_string())
smtp.quit()
def send_WX(self,msg):
headers = {"Content-Type": "text/plain"}
#s="服務(wù)器預(yù)警:{},驗證碼{}".format({str(printCode)},{str(verifyCode)})
data = {
"msgtype": "text",
"text": {
"content": msg,
}
}
r = requests.post(
url='企業(yè)微信機器人地址(需要根據(jù)實際機器人地址配置)',
headers=headers, json=data)
print(r.text)
def Write_to_Mysql_alarm(self,valuelist):
#log = Logger('all.log',level='debug')
#業(yè)務(wù)監(jiān)控:id,project,tpye,exceptiontype,details(xx,大數(shù)據(jù),無es進程/es集群不健康,)
try:
db = MySQLdb.connect("xxx", "xxx", "xxx", "xxx", charset='utf8' )
log.logger.info("數(shù)據(jù)庫連接成功")
except:
log.logger.info("數(shù)據(jù)庫連接失敗")
創(chuàng)建游標(biāo)
cursor = db.cursor()
uid = uuid.uuid1()
result=0
sql =''
try:
sql = 'insert into test_serverresourcealarm values (%s, %s, %s, %s,%s, %s, %s, %s, %s, %s, %s, %s, %s,%s)'
#val = (str(uid),valuelist[1], valuelist[2], valuelist[3], valuelist[4],valuelist[5], valuelist[6],'',valuelist[7], valuelist[8],valuelist[9],valuelist[10],'','','')
val = (str(uid),valuelist[2], valuelist[3], valuelist[4], valuelist[5],valuelist[6], valuelist[7],'',valuelist[8], valuelist[9],valuelist[10],'','','')
cursor.execute(sql,val)
db.commit()
log.logger.error('設(shè)備預(yù)警信息已入庫!')
#發(fā)送企業(yè)微信預(yù)警信息
self.buildMsg(valuelist)
except:
into = sys.exc_info()
#log.logger.error('插入數(shù)據(jù)失?。?)
log.logger.error('設(shè)備預(yù)警信息入庫失??!'+str(into))
result=0
#str = self.obj_to_string(sys.exc_info(), self)
print('error',into)
# 關(guān)閉游標(biāo)
db.close()
return result
def Write_to_Mysql_temp(self,valuelist):
打開數(shù)據(jù)庫連接
#db = MySQLdb.connect("xxx", "xxx", "xxx", "xxx", charset='utf8' )
try:
db = MySQLdb.connect("xxx", "xxx", "xxx", "xxx", charset='utf8' )
log.logger.info("數(shù)據(jù)庫連接成功")
except:
log.logger.info("數(shù)據(jù)庫連接失敗")
使用cursor()方法獲取操作游標(biāo)
cursor = db.cursor()
uid = uuid.uuid1()
result=0
try:
sql = 'insert into test_serverresourcetemp values (%s, %s, %s, %s,%s, %s, %s, %s, %s, %s, %s, %s, %s,%s)'
val = (str(uid),valuelist[2], valuelist[3], valuelist[4], valuelist[5],valuelist[6], valuelist[7],'',valuelist[8], valuelist[9],valuelist[10],'','','')
cursor.execute(sql,val)
db.commit()
result=1
log.logger.info("臨時表sql執(zhí)行狀態(tài):"+str(result))
except:
into = sys.exc_info()
result = 0
print(into)
log.logger.info('臨時表sql執(zhí)行失敗: '+str(into))
關(guān)閉數(shù)據(jù)庫連接
db.close()
return result
class MyServer(SocketServer.BaseRequestHandler):
def handle(self):
conn = self.request
log.logger.info('... connected from {}'.format(self.client_address))
#print('1多線程監(jiān)控')
Flag = True
while Flag:
data = conn.recv(1024)
#print(data)
if len(data)>10:
log.logger.info('接收到的客戶端數(shù)據(jù):'+data)
conn.sendall('1')
sub = data.strip('\\n')
str = sub.split('|')
#print(str)
a = Analysis()
#報警信息入庫,#將監(jiān)控數(shù)據(jù)寫入臨時表中test_serverresourcetemp_lty
result = a.Write_to_Mysql_temp(str)
if(float(str[4])>90 or float(str[5])>90 or float(str[6])>85 or float(str[7])>85 or float(str[8])>3000 or float(str[9])>3000):
result1 = a.Write_to_Mysql_alarm(str)
#result = 1
if result == 0:
log.logger.info('預(yù)警信息入庫失??!')
else:
log.logger.info('預(yù)警信息入庫完成!')
#發(fā)送預(yù)警郵件、企業(yè)微信
#a.buildMsg(str)
if data =='exit':
log.logger.info('... connecte end ...')
Flag = False
if name == " main ":
#每分鐘執(zhí)行一次
log = Logger('socketservice.logs')
log.logger.info('----start----')
alarmName ='服務(wù)器資源預(yù)警'
#是否開啟郵件報警,1為開啟,0為關(guān)閉
mailconf =1
#是否開啟企業(yè)微信報警,1為開啟,0為關(guān)閉
wxconf =0
server = SocketServer.ThreadingTCPServer(('IP',port),MyServer)
server.serve_forever()
原文鏈接:https://blog.csdn.net/eagle89/article/details/128579002
-
監(jiān)控
+關(guān)注
關(guān)注
6文章
2208瀏覽量
55197 -
服務(wù)器
+關(guān)注
關(guān)注
12文章
9160瀏覽量
85415
發(fā)布評論請先 登錄
相關(guān)推薦
評論