python釘釘機器人告警

  1. 獲取Webhook
    釘釘裏新建個羣,添加個機器人,獲取Webhook。

  2. 腳本

# !/usr/bin/env/python3
# _*_coding:utf-8_*_
# @__Data__:2021-05-27
# @__Auther__:lalone
# @__PythonVersion__:python3
# @__name__:dingding_website.py

"""
# 發送消息到釘釘
"""
try:
	import sys
	import json
	import time
	# import sched
	import requests
	from datetime import datetime
	from apscheduler.schedulers.blocking import BlockingScheduler
except Exception as e:
	print(e)

# dingidng notification
class Dingding(object):
	def __init__(self, access_token, content='', at_people=''):
		self.access_token = access_token
		self.content = content
		self.at_people = at_people

	def get_token(self):
		'''
		釘釘管理後臺 : http://open-dev.dingtalk.com
		'''
		access_token = 'https://oapi.dingtalk.com/robot/send?access_token=%s' % self.access_token
		return access_token

	def send_dingding(self):
		'''
		access_token: 網站
		content: 發送的內容
		msgtype : 類型
		'''
		msgtype = 'text'
		if self.at_people == '':
			values = {
					  'msgtype': 'text',
					  msgtype: {
								'content': self.content
					  },
					  'at': {
							  'atMobiles': self.at_people,
					  },
			}
		else:
			values = {
					  'msgtype': 'text',
					  msgtype: {
								'content': self.content
					  },
					  'at': {
							  'atMobiles': [self.at_people]
					  },
			}

		headers = {'Content-Type': 'application/json; charset=UTF-8'}
		values = json.dumps(values)
		res = requests.post(self.get_token(), values, headers=headers)
		errmsg = json.loads(res.text)['errmsg']

		if errmsg == 'ok':
			return 'ok'

		return 'fail: %s' % res.text

# 判斷網站是否正常
def judge_website_survival(url):
	'''
	@ param : url(str)
	@ return : True/False(boole)
	'''
	# 循環判斷5次
	for i in range(5):
		try:
			# 如果出現正常,返回True
			res = requests.get(url, timeout=10)
			if res.status_code == 200:
				return True
		except requests.RequestException:
			pass
		# 每次不正常就暫停1分鐘
		time.sleep(60)
	# 如果5次錯誤,返回False
	return False

# 發送釘釘消息
def send_message(url):
	# access_token
	# Webhook中,替換到下面{access_token}
	WEBHOOK = '{access_token}'
	content = 'warning : ' + url + ' 訪問不正常,請儘快檢查!!! 時間:' + datetime.now().strftime("%Y-%m-%d %H:%M:%S")
	obj = Dingding(WEBHOOK, content)
	obj.send_dingding()

# 任務函數
def url_task():
	# 網站列表
	web = ["https://blog.csdn.net",
		"https://www.baidu.com/"
	]
	
	# 循環判斷
	for url in web:
		flag = judge_website_survival(url)
		if not flag:
			send_message(url)

# 主函數,定時執行
def main():
	try:
		# 運行時執行
		url_task()
		# 初始化 apscheduler 庫的 BlockingScheduler 類
		scheduler = BlockingScheduler()
		# 增加調度任務
		# 每6個小時,執行一次
		scheduler.add_job(url_task, 'interval', hours=6)
		# 運行任務
		scheduler.start()
	except (KeyboardInterrupt, SystemExit):
		sys.exit("程序退出~")

if __name__ == '__main__':
	main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章