David Hsu

    DevOps Engineering / AWS / Cloud Native

David

退伍已經過了一個多月,生活漸漸步入軌道

狂寫python練技術,卻有點不知道目標是什麼

為了技術,有的人願意放棄80k月薪

不禁讓我思考,出社會後如此庸庸碌碌真的是我要的生活嗎

每天沈浸在程式海中,最後想得到什麼呢?

我想得到的到底是技術還是高薪,如果兩者取其重,我會選哪個?

人生真難阿

因應最近公司SAP簡訊系統故障,業務又不回信

只好利用原本Nagios發警告簡訊的機制去寫一個新程式發送警告訊息

雖然還是不懂為何公司要用釘釘,既不安全也不可靠,或許這就是cost down的副作用吧

程式放在github


原理是透過原本簡訊的log去抓關鍵字來發送訊息
然後透過釘釘oapi用POST去發送消息

或許將來哪天Nagios不用了,這程式也就失效了,未來可能需要再修正。

"""
* Nagios Alert Message SMS to Dingtalk
*
* @author David
* Version 1.0 , 2017-06-23
"""
# !/usr/bin/env python3
import re
import time , datetime
import requests
import json

由於nagios admin可以收到全部alert SMS,為了不重複發送訊息,只取這一筆num
# nagios admin's phone number
nagios_admin_num = "09" # David
# read sms_service log file
f = open('D:\david_hsu\Desktop\message.txt','r')
line = f.read()
利用python regex去抓出我們要的key word : SMS內容以及phone num
# find alert message and phone number
msg = re.findall('Src = \[KBT]\w+.+\n SMS Phone Number = \d{10}',line)
利用loop將每筆訊息分別存入記憶體並切掉Src等多餘的字
# split src
alert_msg = list()
for i in msg:
alert_msg.append(i.replace('Src = ', ''))
因要計算時間差距,自己寫一個function來以秒為單位做計算
# definite function for transfer date to second
def get_sec(time_str):
struct_time = time.strptime(time_str , "%Y/%m/%d %H:%M")
sec = time.mktime(struct_time)
return sec
# get now time
nowtime = time.strftime("%Y/%m/%d %H:%M")
now_time = get_sec(nowtime)
釘釘發送消息可以透過oapi以及corpid以及密碼
# get access token from dingtalk
headers = {'Content-Type': 'application/json'}
r = requests.get('https://oapi.dingtalk.com/gettoken?corpid=',headers=headers)
accessToken = json.loads(r.text)['access_token']
# send alert message during 60s and write log
for i in alert_msg:
if i[-10:] == nagios_admin_num:
log_time = get_sec((time.strftime("%Y/"))+i[-42:-31])
if now_time - log_time <= 60:
payload={
"chatid":"chat0", # chatid is Linux Alert Group in Dingtalk
"msgtype": "text",
"text": {
"content": i[:-42]
}
}
r = requests.post('https://oapi.dingtalk.com/chat/send?access_token={0}'.format(accessToken),data=json.dumps(payload),headers=headers)
# write message log
f = open('D:\david_hsu\Desktop\send_log.txt','a')
f.write("===================Log Start===================\n")
f.write("Time = "+time.strftime("%Y/%m/%d %H:%M:%S")+'\n')
f.write("Payload = "+json.dumps(payload)+'\n')
f.write("Response = "+r.text+'\n')
f.write("Access Token = "+accessToken+'\n')
f.write("Src = "+i+'\n')
f.write("====================Log End====================\n")
f.close()



2017-07-08 12:15 David in Taipei 



comments powered by Disqus

Categories

Recent posts