【Ambari】Python调用Rest API 获取集群状态信息并发送钉钉告警
import requests
import json
import time
# 钉钉机器人的Webhook地址
DINGDING_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_ACCESS_TOKEN'
# Ambari的API地址
AMBARI_API = 'http://your-ambari-server/api/v1/clusters/your-cluster-name'
# 发送钉钉机器人消息的函数
def send_dingding_message(message):
headers = {
'Content-Type': 'application/json',
'Charset': 'UTF-8'
}
data = {
"msgtype": "text",
"text": {
"content": message
}
}
response = requests.post(DINGDING_WEBHOOK, headers=headers, data=json.dumps(data))
if response.status_code == 200:
print('消息已发送至钉钉')
else:
print('消息发送失败')
# 获取Ambari集群状态的函数
def get_ambari_cluster_state():
response = requests.get(AMBARI_API)
if response.status_code == 200:
return response.json()
else:
return None
# 主函数
def main():
cluster_state = get_ambari_cluster_state()
if cluster_state:
send_dingding_message(json.dumps(cluster_state, indent=2))
else:
send_dingding_message("获取Ambari集群状态失败")
# 定时执行
if __name__ == '__main__':
while True:
main()
time.sleep(300) # 每5分钟执行一次
这段代码首先定义了钉钉机器人的Webhook地址和Ambari的API地址。然后定义了发送钉钉消息的函数send_dingding_message
和获取集群状态的函数get_ambari_cluster_state
。主函数main
调用get_ambari_cluster_state
获取集群状态,并将其作为消息内容发送到钉钉机器人。最后,在if __name__ == '__main__':
块中,代码被设定为定时执行,每5分钟检查一次集群状态并发送消息。
评论已关闭