1. 程式人生 > >Python3 獲取RDS slowlog+微信介面報警

Python3 獲取RDS slowlog+微信介面報警

#!/usr/bin/python
#-*- conding:utf-8 -*-
from aliyunsdkcore.client import AcsClient
from aliyunsdkrds.request.v20140815 import DescribeDBInstanceAttributeRequest
from aliyunsdkrds.request.v20140815 import DescribeSlowLogRecordsRequest
import requests
import json
import os
import time
import logging
import subprocess #ali key client = AcsClient( "", "", "" ); log_file = "/tmp/rdsslowinfo.log" logging.basicConfig(filename=log_file,filemode='a',level=logging.DEBUG) def WARNING(*objs): print("[%s] : " % time.strftime("%y-%m-%d %H:%M:%S", time.localtime()), *objs, file=sys.stderr)
class rdsInfo(object): ''' ali rds slow log get''' def __init__(self,dbId,startTime,endTime): self.dbId = dbId self.startTime = startTime self.endTime = endTime def slowlogGet(self): request = DescribeSlowLogRecordsRequest.DescribeSlowLogRecordsRequest() request.set_accept_format(
'json') request.set_DBInstanceId(self.dbId) request.set_StartTime(self.startTime) request.set_EndTime(self.endTime) response = client.do_action_with_exception(request) data = json.loads(response) return data def instanceGet(self): request = DescribeDBInstanceAttributeRequest.DescribeDBInstanceAttributeRequest() request.set_accept_format('json') request.set_DBInstanceId(self.dbId) response = client.do_action_with_exception(request) data = json.loads(response) #print (data['Items']) return data class WeChat: '''微信介面''' def __init__(self,user): self.CORPID = '' #企業ID, 登陸企業微信,在我的企業-->企業資訊裡檢視 self.CORPSECRET = '' #自建應用,每個自建應用裡都有單獨的secret self.AGENTID = '' #應用程式碼 self.TOUSER = user # 接收者使用者名稱, @all 全體成員 def _get_access_token(self): url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken' values = {'corpid': self.CORPID, 'corpsecret': self.CORPSECRET, } req = requests.post(url, params=values) data = json.loads(req.text) # print (data) return data["access_token"] def get_access_token(self): try: with open('access_token.conf', 'r') as f: t, access_token = f.read().split() except: with open('access_token.conf', 'w') as f: access_token = self._get_access_token() cur_time = time.time() f.write('\t'.join([str(cur_time), access_token])) return access_token else: cur_time = time.time() if 0 < cur_time - float(t) < 7200: #token的有效時間7200s return access_token else: with open('access_token.conf', 'w') as f: access_token = self._get_access_token() f.write('\t'.join([str(cur_time), access_token])) return access_token def send_data(self, msg): send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token() send_values = { "touser": self.TOUSER, "msgtype": "text", "agentid": self.AGENTID, "text": { "content": msg }, "safe": "0" } send_msges=(bytes(json.dumps(send_values), 'utf-8')) respone = requests.post(send_url, send_msges) respone = respone.json()#當返回的資料是json串的時候直接用.json即可將respone轉換成字典 # print (respone["errmsg"]) return respone["errmsg"] def dataInit(): ''' get data info''' instanceInfo = { 'rm-阿里域名':'業務線', 'rm-':'', 'rm-':'', 'rm-':'', 'rm-':'', } alarmList = ['','','','','']#收報警人列表 for dbUrl in instanceInfo.keys(): nowTime = time.strftime("%Y-%m-%dT%H:%MZ") second = time.time() - 24*60*60 #查詢間隔 自己定義 tago = time.strftime('%Y-%m-%dT%H:%MZ', time.localtime(second)) rdsinfo = rdsInfo(dbUrl,tago,nowTime) slowlog_data = rdsinfo.slowlogGet() instance_data = rdsinfo.instanceGet() try: for recode in slowlog_data['Items']['SQLSlowRecord']: #print(recode) ParseRowCounts = recode['ParseRowCounts'] ReturnRowCounts = recode['ReturnRowCounts'] QueryTimes = recode['QueryTimes'] HostAddress = recode['HostAddress'] LockTimes = recode['LockTimes'] ExecutionStartTime = recode['ExecutionStartTime'] SQLText = recode['SQLText'] DBName = recode['DBName'] content = ''' 業務線 :{url} SQL來源:{HostAddress} 執行時間:{ExecutionStartTime} 資料庫名:{DBName} 執行時長:{QueryTimes} 鎖定時長:{LockTimes} 解析行數:{ParseRowCounts} 返回行數:{ReturnRowCounts} SQL詳情:{SQLText} ''' .format(url=instanceInfo[dbUrl],HostAddress=HostAddress,ExecutionStartTime\ =ExecutionStartTime,DBName=DBName,QueryTimes=QueryTimes,LockTimes=LockTimes,\ ParseRowCounts=ParseRowCounts,ReturnRowCounts=ReturnRowCounts,SQLText=SQLText) #print(content) logging.info(content) for alarm in alarmList: wx = WeChat(alarm) wx.send_data(msg=content) except Exception as e: WARNING('[%s]')%(e) class Daemon: ''' Daemon ''' def createDaemon(self): try: if os.fork() > 0: os._exit(0) # exit father… except OSError as error: print ('fork #1 failed: %d (%s)' % (error.errno, error.strerror)) os._exit(1) # it separates the son from the father os.chdir('/') os.setsid() os.umask(0) # create - fork 2 try: pid = os.fork() if pid > 0: print ('Daemon PID %d' % pid) logging.info('Daemon PID %d' % pid) os._exit(0) except OSError as error: print ('fork #2 failed: %d (%s)' % (error.errno, error.strerror)) os._exit(1) self.run() # function demo def run(self): while True: dataInit() time.sleep(24*60*60) #deamon執行間隔時間 #time.sleep(5) #except Exception,e: # traceback.print_exc() if __name__ == '__main__': daemon = Daemon() daemon.createDaemon()

相關推薦

Python3 獲取RDS slowlog+介面報警

#!/usr/bin/python #-*- conding:utf-8 -*- from aliyunsdkcore.client import AcsClient from aliyunsdkrds.request.v20140815 import DescribeDBInstanceAttri

vue如何通過NodeJs本地獲取access_token及簽名,並呼叫介面

一直都想搞一下微信公眾號網頁開發,公司忙沒有時間自己也沒開發過所以也沒有頭緒,前兩天通過自己的摸索以及自行查詢的資料,終於通過nodejs在本地成功的獲取到了微信的access_token及簽名,以及呼叫微信的介面.因為筆者自己在做的時候費了挺長時間,沒有找到一個相

weixin://dl/business/?ticket=怎麼生成獲取的?介面api公開

weixin://dl/business/?ticket=  到底怎麼生成的?呼叫以下介面 weixin://dl/scan 掃一掃weixin://dl/feedback 反饋weixin://dl/moments 朋友圈weixin://dl/settings 設定weixin://dl/

請求介面獲取小程式碼

public Map<String,Object> getSharePhoto(Map<String, Object> conditions){ Map<String, Object> results = ne

通過介面上傳圖片並獲取到自己的伺服器

       我們需要使用者在企業號上傳圖片後,該圖片儲存在我們自己的資料庫裡。        所以我們要用到微信JSSDK中的“拍照或選擇手機相簿照片”、“上傳圖片介面”以及“獲取臨時素材介面”。        一開始以為有了media_id就用CURL去請求“獲取臨時素

spring boot項目之賣家掃碼登陸獲取openid(身份驗證id)

能夠 style png info 提示 行處理 The 使用 src 賣家掃碼登陸獲取openid 註:此功能只能是微信公眾帳號能夠使用,個人賬號無此功能。 一、打開微信開放平臺(與支付階段不同,特別註意!!!),進入網站應用的網站應用微信登陸開發指南。 二、你會發

完整的介面類 (轉)

  本類包含了微信官方公佈的所有可使用的介面,包括了普通介面及高階介面,具體哪些介面可用還是要看您的賬號級別。 具體介面如下:

瀏覽器網頁授權獲取使用者openid 瀏覽器支付

### 配置 1. appid 2. appsecret 3. merchid 4. apikey 5. 微信公眾號,介面許可權,網頁授權域名填寫 ### 獲取code ``` function getWxCode($url){ $appid = ""; $appsecret =

帶你使用wxpy建立自己的聊天機器人(外加介面基本資料視覺化)

往期好文:你的微信暱稱,可能正在出賣你 本文目錄 一、wxpy基本介紹與安裝 1.wxpy基本介紹 2.wxpy安裝

小程式--獲取已釋出小遊戲和小程式原始碼

最近一直在做微信小遊戲的開發,發現了一個好玩的事 ,在這裡記錄一下。 這段時間一直在做一些小遊戲 ,小程式的開發,但有的時候會發現效能上總是不那麼的盡如人意(畢竟我這小菜鳥水平有限),於是就想到,想要看看別的大神們是怎麼處理這些問題的(其實就是想看一下大神們的程式碼怎麼寫!)。但是,有一個問題就

python --itchat實現呼叫介面的方法

1.在樹莓派中輸入sudo pip3 install itchat 安裝itchat。 2.登入微信 itchat.auto_login() 這種方法將會通過微信掃描二維碼登入,但是這種登入的方式確實短時間的登入,並不會保留登入的狀態,也就是下次登入時還是需要掃描二維碼,如果加上

Android 仿介面 使用RadioGroup+ViewPager實現底部按鈕切換以及滑動

先來效果圖哈哈 ![在這裡插入圖片描述](https://img-blog.csdn.net/2018100916182717?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjMwNjcwN

呼叫介面實現網頁分享小功能

// 獲取access_token  *注意* 經過實際開發測試,微信分享不支援跨域請求,因此獲取access_token的請求必須從伺服器發起,否則無法獲取到access_token所以以下都是服務端操作 一、微信util類 public class Share

ViewPager + Fragment 實現類介面

在如今的網際網路時代,微信已是一個超級App。這篇通過ViewPager + Fragment實現一個類似於微信的介面,之前有用FragmentTabHost實現過類似介面,ViewPager的實現方式相對於FragmentTabHost的方式更簡單明瞭。 ViewPage

zabbix 定義觸發器,並使用郵件,訊息報警

觸發器可根據監控項獲取到的值來進行一些操作,如監控項獲取到的values為0,觸發器可判斷為正常,如果獲取到了1,就觸發報警。 定義報警方式比較簡單,但是用shell指令碼實現起來,總是有格式問題,所以我用python語言寫了簡單的程式[發郵件,發到微訊號上],zabbix執行python程式時,傳入幾個引

html5聊天案例|趣聊h5|仿介面聊天|紅包|語音聊天|地圖

之前有開發過一個h5微直播專案,當時裡面也用到過聊天模組部分,今天就在之前聊天部分的基礎上重新抽離模組,開發了這個h5趣聊專案,功能效果比較類似微信聊天介面。採用html5+css3+Zepto+swiper+wcPop+flex等技術融合開發,實現了傳送訊息、表情(動圖),圖片、視訊預覽,新增好友/群聊,右

介面開發【php程式碼】

首先準備一個api.php檔案 這個檔案可以再微信開發平臺網站手冊裡面下載到 需要配置的是token 微信測試地址 https://mp.weixin.qq.com/debug/ <?php /** * wechat php test */ //define yo

Python3.6】生成好友個性簽名詞雲

程式碼連結:https://gitee.com/AI-Echo/codes/4bk0tsqczpe6dfyhu7mlo12 思路: 1.通過itchat爬取微信好友資訊,獲取好友簽名Signature 2.將Signature拼接成Str,並去掉預先設定的一些停用詞(如的、是、有等

呼叫介面token的問題

前言 微信的影響力眾所周知,越來越多的人也都離不開它,工作,生活,社交的好幫手。相信大家對微信公眾號,小程式也都不陌生,那麼在開發公眾號,小程式的時候需要呼叫到微信的介面,固然就會遇到token的問題,有哪些問題,以及怎麼解決的呢,我們繼續往下看。 問題一:微信介面返回"errcod

五、介面

在res裡邊建drawable,drawable裡邊建selector下的sel_r.xml:             <?xml version="1.0" encod