falcon的api
一、判断session是否有效
# -*- coding: UTF- -*-
#!/usr/bin/env python
# Created by Administrator on //
import json
import requests user = 'admin'
sig = '1a7521abad6c11e9b4b3000c29a13d5d'
domain = 'http://172.20.16.5:8080'
api_token = '{"name":"' + user + '", "sig":"' + sig + '"}'
directiry = "/api/v1/user/auth_session"
print directiry
falcon_header = {
"Apitoken": api_token,
"X-Forwarded-For": "127.0.0.1",
"Content-Type": "application/json",
"name": user,
"sig": sig
} params = {
'url': domain + directiry,
'headers': falcon_header,
'timeout':
}
res1 = requests.get(**params)
data1 = json.loads(res1.text)
print(data1)
2、获取session
# -*- coding: UTF- -*-
# !/usr/bin/env python
import json
import time
import requests ip = '172.20.16.5'
user = 'admin'
api_port = '' # api对应端口为8080
login_path = '/api/v1/user/login'
login_url = 'http://' + ip + ':' + api_port + login_path
eventcases_path = "/api/v1/alarm/eventcases"
eventcases_url = 'http://' + ip + ':' + api_port + eventcases_path
s = requests.Session()
login_res = s.post(url=login_url,
data={'name': 'admin', 'password': 'password'}) login_data = json.loads(login_res.text)
# print(login_data['sig'])
sig = login_data['sig']
# print(sig)
api_token = '{"name":"' + user + '", "sig":"' + sig + '"}' # get event cases by api
falcon_header = {
"Apitoken": api_token,
"X-Forwarded-For": "127.0.0.1",
"Content-Type": "application/json",
"name": user,
"sig": sig } params = {
'url': eventcases_url,
'headers': falcon_header,
'timeout':
} payload = {
# "startTime": ,
"endTime": int(time.time()),
"status": "PROBLEM",
"process_status": "ignored,unresolved", }
print params['headers']['sig']
https://blog.csdn.net/jb19900111/article/details/85064362
二、深入完善 falcon_api
1)获取基本的用户session,请求头信息,以及用户所在的id
# -*- coding: UTF-8 -*-
# !/usr/bin/env python
import json, time
import requests url = "http://172.20.16.5:8080"
user = 'admin'
password = 'password'
hostname = 'Yuanjin' class falcon_base():
def __init__(self,user,password):
self.user = user
self.password = password def get_sig(self):
login_url = url + "/api/v1/user/login"
s = requests.Session()
login_res = s.post(url=login_url,
data={'name': self.user, 'password': self.password})
login_data = json.loads(login_res.text)
return login_data['sig'] def get_falcon_header(self):
sig = self.get_sig()
api_token = '{"name":"' + user + '", "sig":"' + sig + '"}'
falcon_header = {
"Apitoken": api_token,
"X-Forwarded-For": "127.0.0.1",
"Content-Type": "application/json",
"name": self.user,
"sig": sig
}
return falcon_header def get_user_id(self):
user_url = url + "/api/v1/graph/endpoint?q=%s"%(hostname)
params = {
'url': user_url,
'headers': self.get_falcon_header(),
'timeout': 30
}
res = requests.get(**params)
data = json.loads(res.text)
user_id = data[0]["id"]
return user_id
falcon_base 类
2)获取监控指标。需引入基本信息
class falcon_info():
def __init__(self,user,password):
self.user = user
self.password = password
self.falconbase = falcon_base(self.user,self.password) def get_graph(self):
# 得到具体监控项
falcon_header = self.falconbase.get_falcon_header()
uid = self.falconbase.get_user_id()
graph_url = url + '/api/v1/graph/endpoint_counter?eid=%s' %(uid)
params = {
'url': graph_url,
'headers': falcon_header,
'timeout': 30
}
res = requests.get(**params)
data = json.loads(res.text)
counters = [counter["counter"] for counter in data]
return counters def get_graph_history(self):
# 得到指定监控项的历史记录
falcon_header = self.falconbase.get_falcon_header()
graph_history_url = url + "/api/v1/graph/history"
end_time = int(time.time()) # 必须要整形
start_time = end_time - 1800 # 30分钟
counters = self.get_graph()
params = {
'url': graph_history_url,
'headers': falcon_header,
'timeout': 30
}
payload = {
"step": 60,
"start_time": start_time,
"hostnames": [hostname, ],
"end_time": end_time,
"counters": counters,
"consol_fun": "AVERAGE"
}
params['data'] = json.dumps(payload)
res = requests.post(**params)
data = json.loads(res.text)
print data
data = dict([(iter["counter"], iter["Values"]) for iter in data])
for key in data:
values = data[key]
data[key] = [{"timestamp": time.strftime('%H:%M', time.localtime(k["timestamp"])), "value": k["value"]} for
k in
values if k["value"]] data["in_ip"] = hostname
print(data) if __name__ == '__main__':
falconinfo = falcon_info(user,password)
falconinfo.get_graph_history()
falcon_info 类
更新
# -*- coding: UTF-8 -*- import json, time
import requests
import falcon_base class falcon_info():
def __init__(self, user, password):
self.user = user
self.password = password
self.falconbase = falcon_base.falcon_base(self.user, self.password) def get_graph(self):
# 得到具体监控项
falcon_header = self.falconbase.get_falcon_header()
uid = self.falconbase.get_user_id()
graph_url = falcon_base.url + '/api/v1/graph/endpoint_counter?eid=%s' % (uid)
params = {
'url': graph_url,
'headers': falcon_header,
'timeout': 30
}
res = requests.get(**params)
data = json.loads(res.text)
counters = [counter["counter"] for counter in data]
return counters def get_graph_history(self):
# 得到指定监控项的历史记录
falcon_header = self.falconbase.get_falcon_header()
graph_history_url = falcon_base.url + "/api/v1/graph/history"
end_time = int(time.time()) # 必须要整形
start_time = end_time - 1800 # 30分钟
counters = self.get_graph()
params = {
'url': graph_history_url,
'headers': falcon_header,
'timeout': 30
}
payload = {
"step": 60,
"start_time": start_time,
"hostnames": [falcon_base.hostname, ],
"end_time": end_time,
"counters": counters,
"consol_fun": "AVERAGE"
}
params['data'] = json.dumps(payload)
res = requests.post(**params)
data = json.loads(res.text)
data = dict([(iter["counter"], iter["Values"]) for iter in data])
for key in data:
values = data[key]
data[key] = [{"timestamp": time.strftime('%H:%M', time.localtime(k["timestamp"])), "value": k["value"]} for
k in
values if k["value"]] data["in_ip"] = falcon_base.hostname
print(data) def get_user_info(self):
# 获取用户信息
falcon_header = self.falconbase.get_falcon_header()
alarm_url = falcon_base.url + '/api/v1/user/users'
params = {
'url': alarm_url,
'headers': falcon_header,
'timeout': 30
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_template(self):
# 获取模板信息
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template'
params = {
'url': template_url,
'headers': falcon_header,
'timeout': 30
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_screens(self):
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/dashboard/screens'
print strategy_url
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout': 30
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_alarm(self):
falcon_header = self.falconbase.get_falcon_header()
alarm_url = falcon_base.url + '/api/v1/alarm/event_note'
# end_time = int(time.time()) # 必须要整形
# start_time = end_time - 1800 # 30分钟
params = {
'url': alarm_url,
'headers': falcon_header,
'timeout': 30,
}
res = requests.get(**params)
data = json.loads(res.text)
print data def eventcases(self):
# 获取每天的报警信息
eventcases_url = falcon_base.url + '/api/v1/alarm/eventcases'
falcon_header = self.falconbase.get_falcon_header()
s = requests.Session()
oneday = 86400
params = {
'url': eventcases_url,
'headers': falcon_header,
'timeout': 30
}
payload = {
"startTime": int(time.time() - oneday*2),
"endTime": int(time.time()),
"status": "PROBLEM",
"process_status": "ignored,unresolved",
}
params['data'] = json.dumps(payload)
eventcases_res = s.post(**params)
eventcases_data = json.loads(eventcases_res.text)
for proble in eventcases_data:
print proble['endpoint'],proble['timestamp'],proble['metric'],proble['note'] if __name__ == '__main__':
falconinfo = falcon_info(falcon_base.user, falcon_base.password)
falconinfo.eventcases()
3)更新
# -*- coding: UTF- -*- import json, time
import requests
import falcon_base class falcon_info():
def __init__(self, user, password):
self.user = user
self.password = password
self.falconbase = falcon_base.falcon_base(self.user, self.password) def get_graph(self):
# 得到具体监控项
falcon_header = self.falconbase.get_falcon_header()
uid = self.falconbase.get_user_id()
graph_url = falcon_base.url + '/api/v1/graph/endpoint_counter?eid=%s' % (uid)
params = {
'url': graph_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
counters = [counter["counter"] for counter in data]
return counters def get_graph_history(self):
# 得到指定监控项的历史记录
falcon_header = self.falconbase.get_falcon_header()
graph_history_url = falcon_base.url + "/api/v1/graph/history"
end_time = int(time.time()) # 必须要整形
start_time = end_time - # 30分钟
counters = self.get_graph()
params = {
'url': graph_history_url,
'headers': falcon_header,
'timeout':
}
payload = {
"step": ,
"start_time": start_time,
"hostnames": [falcon_base.hostname, ],
"end_time": end_time,
"counters": counters,
"consol_fun": "AVERAGE"
}
params['data'] = json.dumps(payload)
res = requests.post(**params)
data = json.loads(res.text)
data = dict([(iter["counter"], iter["Values"]) for iter in data])
for key in data:
values = data[key]
data[key] = [{"timestamp": time.strftime('%H:%M', time.localtime(k["timestamp"])), "value": k["value"]} for
k in
values if k["value"]] data["in_ip"] = falcon_base.hostname
print(data) def get_user_info(self):
# 获取用户信息
falcon_header = self.falconbase.get_falcon_header()
alarm_url = falcon_base.url + '/api/v1/user/users'
params = {
'url': alarm_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_template(self):
# 获取模板列表
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template'
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
# print data
templates_list = []
for i in data['templates']:
templates = {}
uid = i['template']['id']
action_id = i['template']['action_id']
template = i['template']['tpl_name']
templates['uid'] = uid
templates['template'] = template
templates['action_id'] = action_id
templates_list.append(templates)
# print '模板列表',templates_list
return templates_list def get_team(self):
# 获取用户组
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/team'
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data
teams = {}
for i in data:
team_id = i['team']['id']
team_name = i['team']['name']
# teams['team_id']= team_id
teams[team_id]= team_name
# team_list.append(teams)
print teams
return teams def get_template_id(self):
# 根据模板id 获取模板详细信息
id =
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template/%s' %(id)
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_screens(self):
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/dashboard/screens'
print strategy_url
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_alarm(self):
falcon_header = self.falconbase.get_falcon_header()
oneday =
alarm_url = falcon_base.url + '/api/v1/alarm/event_note'
print alarm_url
params = {
'url': alarm_url,
'headers': falcon_header,
'timeout': ,
# "startTime": int(time.time() - oneday * ),
# "endTime": int(time.time()),
}
res = requests.get(**params)
print res
data = json.loads(res.text)
print data def eventcases(self):
# 获取每天的报警信息
eventcases_url = falcon_base.url + '/api/v1/alarm/eventcases'
falcon_header = self.falconbase.get_falcon_header()
s = requests.Session()
oneday =
params = {
'url': eventcases_url,
'headers': falcon_header,
'timeout':
}
payload = {
"startTime": int(time.time() - oneday*),
"endTime": int(time.time()),
"status": "PROBLEM",
"process_status": "ignored,unresolved",
}
params['data'] = json.dumps(payload)
eventcases_res = s.post(**params)
eventcases_data = json.loads(eventcases_res.text)
# print eventcases_data
proble_list = []
template_count = {}
for proble in eventcases_data:
proble_count = {}
template_id = proble['template_id']
metric = proble['metric']
if template_id not in proble_count:
proble_count['template_id'] = template_id if template_id not in template_count:
template_count[template_id] =
else:
template_count[template_id] +=
if metric in proble_count:
proble_count[metric] +=
else:
proble_count[metric] =
proble_list.append(proble_count) print proble_list
print template_count
return proble_list,template_count def info(self):
templates_list = self.get_template()
proble_list,template_count = self.eventcases()
team_list = self.get_team()
action_info = {}
print team_list
for i in template_count: # 循环报警的模板 id
for j in templates_list:
if j['uid'] == i: # 根据模板id 找到对应的 模板信息
template = j['template'] # 确定了告警的模板
action_id = j['action_id']
actions = team_list[action_id] # 确定了报警的模板对应的接收组
action_info['template'] = template
action_info['actions'] = actions
action_info['count'] = template_count[i]
print action_info if __name__ == '__main__':
falconinfo = falcon_info(falcon_base.user, falcon_base.password)
falconinfo.eventcases()
4)添加模板
# -*- coding: UTF- -*- import json, time
import requests
import falcon_base timestr = str(time.strftime('%Y_%m_%d'))
'''
第一步:先在原来的环境获取对应模板的监控项目,写入文件。需要给指定模板的id
第二步:在新环境创建相应的模板监控项目。需要指定对应模板的id 详细过程:
在falcon_base.py指定ip,用户名,密码,来获取相应的token 老环境中执行函数 get_template_id() 获取到的 template.json文件 新环境中执行函数 create_strategy() 创建监控项目 特别强调:注意:id
'''
class falcon_template():
def __init__(self, user, password):
self.user = user
self.password = password
self.falconbase = falcon_base.falcon_base(self.user, self.password) def get_graph(self):
# 得到具体监控项
falcon_header = self.falconbase.get_falcon_header()
uid = self.falconbase.get_user_id()
graph_url = falcon_base.url + '/api/v1/graph/endpoint_counter?eid=%s' % (uid)
params = {
'url': graph_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
counters = [counter["counter"] for counter in data]
return counters def get_graph_history(self):
# 得到指定监控项的历史记录
falcon_header = self.falconbase.get_falcon_header()
graph_history_url = falcon_base.url + "/api/v1/graph/history"
end_time = int(time.time()) # 必须要整形
start_time = end_time - # 30分钟
counters = self.get_graph()
params = {
'url': graph_history_url,
'headers': falcon_header,
'timeout':
}
payload = {
"step": ,
"start_time": start_time,
"hostnames": [falcon_base.hostname, ],
"end_time": end_time,
"counters": counters,
"consol_fun": "AVERAGE"
}
params['data'] = json.dumps(payload)
res = requests.post(**params)
data = json.loads(res.text)
data = dict([(iter["counter"], iter["Values"]) for iter in data])
for key in data:
values = data[key]
data[key] = [{"timestamp": time.strftime('%H:%M', time.localtime(k["timestamp"])), "value": k["value"]} for
k in
values if k["value"]] data["in_ip"] = falcon_base.hostname
print(data) def get_user_info(self):
# 获取用户信息
falcon_header = self.falconbase.get_falcon_header()
alarm_url = falcon_base.url + '/api/v1/user/users'
params = {
'url': alarm_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_template(self):
# 获取模板列表
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template'
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def create_template(self):
# 创建模板
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template'
s = requests.Session()
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
payload = {
"parent_id": , # 继承现有Template
"name": "Test_template" # 创建模板的名字
}
params['data'] = json.dumps(payload)
template = s.post(**params)
print template.text def get_team(self):
# 获取用户组
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/team'
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data
teams = {}
for i in data:
team_id = i['team']['id']
team_name = i['team']['name']
# teams['team_id']= team_id
teams[team_id]= team_name
# team_list.append(teams)
print teams
return teams def get_template_id(self):
# 根据模板id 获取模板详细信息
id =
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template/%s' %(id)
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.content) res = json.dumps(data)
with open('template.json', mode='w') as f:
f.write(res)
print res def get_screens(self):
falcon_header = self.falconbase.get_falcon_header()
screens_url = falcon_base.url + '/api/v1/dashboard/screens'
print screens_url
params = {
'url': screens_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_alarm(self):
falcon_header = self.falconbase.get_falcon_header()
oneday =
alarm_url = falcon_base.url + '/api/v1/alarm/event_note'
print alarm_url
params = {
'url': alarm_url,
'headers': falcon_header,
'timeout': ,
# "startTime": int(time.time() - oneday * ),
# "endTime": int(time.time()),
}
res = requests.get(**params)
print res
data = json.loads(res.text)
print data def get_strategy(self):
# 获取模板监控项目
id =
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/strategy/%s'%id
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def open_strategy(self):
with open('template.json','r') as f:
res=f.read()
dic=json.loads(res)
strategy = dic['stratges']
return strategy def create_strategy(self):
strategy_dic = self.open_strategy()
# print strategy_dic
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/strategy'
s = requests.Session()
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout':
}
for strategy in strategy_dic:
payload = {
"tpl_id": , # 对应模板的id
"tags": strategy['tags'],
"run_end": strategy['run_end'],
"run_begin": strategy['run_begin'],
"right_value": strategy['right_value'],
"priority": strategy['priority'],
"op": strategy['op'],
"note": strategy['note'],
"metric": strategy['metric'],
"max_step": strategy['max_step'],
"func": strategy['func']
}
params['data'] = json.dumps(payload)
template = s.post(**params)
print template.text if __name__ == '__main__':
falconinfo = falcon_template(falcon_base.user, falcon_base.password)
falconinfo.create_strategy()
上面代码存在bug。right_value小于0或者 为小数时无法添加。下面修改为固定值后,再做修改
# -*- coding: UTF- -*- import json, time
import requests
import falcon_base timestr = str(time.strftime('%Y_%m_%d'))
'''
第一步:先在原来的环境获取对应模板的监控项目,写入文件。需要给指定模板的id
第二步:在新环境创建相应的模板监控项目。需要指定对应模板的id 详细过程:
在falcon_base.py指定ip,用户名,密码,来获取相应的token 老环境中执行函数 get_template_id() 获取到的 template.json文件 新环境中执行函数 create_strategy() 创建监控项目 特别强调:注意:id 和 "right_value" 负数,小数创建失败,类型 为 字符串的整数 '''
class falcon_template():
def __init__(self, user, password):
self.user = user
self.password = password
self.falconbase = falcon_base.falcon_base(self.user, self.password) def get_graph(self):
# 得到具体监控项
falcon_header = self.falconbase.get_falcon_header()
uid = self.falconbase.get_user_id()
graph_url = falcon_base.url + '/api/v1/graph/endpoint_counter?eid=%s' % (uid)
params = {
'url': graph_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
counters = [counter["counter"] for counter in data]
return counters def get_graph_history(self):
# 得到指定监控项的历史记录
falcon_header = self.falconbase.get_falcon_header()
graph_history_url = falcon_base.url + "/api/v1/graph/history"
end_time = int(time.time()) # 必须要整形
start_time = end_time - # 30分钟
counters = self.get_graph()
params = {
'url': graph_history_url,
'headers': falcon_header,
'timeout':
}
payload = {
"step": ,
"start_time": start_time,
"hostnames": [falcon_base.hostname, ],
"end_time": end_time,
"counters": counters,
"consol_fun": "AVERAGE"
}
params['data'] = json.dumps(payload)
res = requests.post(**params)
data = json.loads(res.text)
data = dict([(iter["counter"], iter["Values"]) for iter in data])
for key in data:
values = data[key]
data[key] = [{"timestamp": time.strftime('%H:%M', time.localtime(k["timestamp"])), "value": k["value"]} for
k in
values if k["value"]] data["in_ip"] = falcon_base.hostname
print(data) def get_user_info(self):
# 获取用户信息
falcon_header = self.falconbase.get_falcon_header()
alarm_url = falcon_base.url + '/api/v1/user/users'
params = {
'url': alarm_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_template(self):
# 获取模板列表
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template'
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def create_template(self):
# 创建模板
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template'
s = requests.Session()
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
payload = {
"parent_id": , # 继承现有Template
"name": "Test_template" # 创建模板的名字
}
params['data'] = json.dumps(payload)
template = s.post(**params)
print template.text def get_team(self):
# 获取用户组
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/team'
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data
teams = {}
for i in data:
team_id = i['team']['id']
team_name = i['team']['name']
# teams['team_id']= team_id
teams[team_id]= team_name
# team_list.append(teams)
print teams
return teams def get_template_id(self):
# 根据模板id 获取模板详细信息
id =
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template/%s' %(id)
params = {
'url': template_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.content) res = json.dumps(data)
with open('template.json', mode='w') as f:
f.write(res)
print res def get_screens(self):
falcon_header = self.falconbase.get_falcon_header()
screens_url = falcon_base.url + '/api/v1/dashboard/screens'
print screens_url
params = {
'url': screens_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def get_alarm(self):
falcon_header = self.falconbase.get_falcon_header()
oneday =
alarm_url = falcon_base.url + '/api/v1/alarm/event_note'
print alarm_url
params = {
'url': alarm_url,
'headers': falcon_header,
'timeout': ,
# "startTime": int(time.time() - oneday * ),
# "endTime": int(time.time()),
}
res = requests.get(**params)
print res
data = json.loads(res.text)
print data def get_strategy(self):
# 获取模板监控项目
id =
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/strategy/%s'%id
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def open_strategy(self):
with open('template2.json','r') as f:
res=f.read()
dic=json.loads(res)
strategy = dic['stratges']
return strategy def create_strategy(self):
strategy_dic = self.open_strategy()
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/strategy'
s = requests.Session()
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout':
}
for strategy in strategy_dic:
unicode_value = strategy['right_value']
str_value = unicode_value.encode("utf-8")
float_value = float(str_value)
if not float_value.is_integer():
str_value = ''
if float_value < :
str_value = ''
payload = {
"tpl_id": , # 对应模板的id
"tags": strategy['tags'],
"run_end": strategy['run_end'],
"run_begin": strategy['run_begin'],
"right_value": str_value,
"priority": strategy['priority'],
"op": strategy['op'],
"note": strategy['note'],
"metric": strategy['metric'],
"max_step": strategy['max_step'],
"func": strategy['func']
}
params['data'] = json.dumps(payload)
template = s.post(**params)
print template.text if __name__ == '__main__':
falconinfo = falcon_template(falcon_base.user, falcon_base.password)
falconinfo.create_strategy()
4)模板优化,分开
4.1)获取模板,传参方式,传模板id
# -*- coding: UTF-8 -*-
import json,sys
import requests
import falcon_base class falcon_template():
def __init__(self, user, password):
self.user = user
self.password = password
self.falconbase = falcon_base.falcon_base(self.user, self.password) def get_template_id(self,template_id):
# 根据模板id 获取模板详细信息
falcon_header = self.falconbase.get_falcon_header()
template_url = falcon_base.url + '/api/v1/template/%s' %(template_id)
params = {
'url': template_url,
'headers': falcon_header,
'timeout': 30
}
res = requests.get(**params)
data = json.loads(res.content) res = json.dumps(data)
with open('template.json', mode='w') as f:
f.write(res)
print res def main(self,template_id):
if template_id.isdigit():
print 'get template'
template_id = int(template_id)
self.get_template_id(template_id)
else:
print 'template_id is wrong,you should get right template_id' if __name__ == '__main__':
get_template = falcon_template(falcon_base.user, falcon_base.password)
if len(sys.argv) == 2:
template_id = sys.argv[1]
get_template.main(template_id)
else:
print "please input template_id"
get_template
4.2) 创建模板,需要有上面个脚本创建的 template.json 文件,传参方式,传模板id
# -*- coding: UTF-8 -*-
import json,sys
import requests
import falcon_base class falcon_template():
def __init__(self, user, password):
self.user = user
self.password = password
self.falconbase = falcon_base.falcon_base(self.user, self.password) def open_strategy(self):
with open('template.json', 'r') as f:
res = f.read()
dic = json.loads(res)
strategy = dic['stratges']
return strategy def create_strategy(self,template_id):
strategy_dic = self.open_strategy()
# print strategy_dic
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/strategy'
s = requests.Session()
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout': 30
}
for strategy in strategy_dic:
payload = {
"tpl_id": template_id, # 对应模板的id
"tags": strategy['tags'],
"run_end": strategy['run_end'],
"run_begin": strategy['run_begin'],
"right_value": strategy['right_value'],
"priority": strategy['priority'],
"op": strategy['op'],
"note": strategy['note'],
"metric": strategy['metric'],
"max_step": strategy['max_step'],
"func": strategy['func']
}
params['data'] = json.dumps(payload)
template = s.post(**params)
print template.text def main(self,template_id):
if template_id.isdigit():
print 'crete template'
template_id = int(template_id)
self.create_strategy(template_id)
else:
print 'template_id is wrong,you should get right template_id'
pass if __name__ == '__main__':
get_template = falcon_template(falcon_base.user, falcon_base.password)
if len(sys.argv) == 2:
template_id = sys.argv[1]
get_template.main(template_id)
else:
print "please input template_id"
create_template
5)nodata创建
def get_nodata(self):
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/nodata'
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
print data def create_nodata(self):
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/nodata/'
print strategy_url
s = requests.Session()
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout': ,
}
payload = { "tags": "",
"step": ,
"obj_type": "host",
"obj": "docker-agent",
"name": "testndata111",
"mock": -,
"metric": "test.metric",
"dstype": "GAUGE" }
params['data'] = json.dumps(payload)
result = s.post(**params)
print result.text
[root@node02 db_schema]# diff 2_portal-db-schema.sql 2_portal-db-schema.sql.bak
5a6
>
182c183
< `t_create` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', # 修改后的
---
> `t_create` DATETIME NOT NULL COMMENT 'create time', # 原来的
完善自动化获取并创建 nodata
# -*- coding: UTF- -*- import json, time
import requests
import falcon_base
get_nodata_creator = "admin" class falcon_template():
def __init__(self, user, password):
self.user = user
self.password = password
self.falconbase = falcon_base.falcon_base(self.user, self.password) def get_nodata(self):
falcon_header = self.falconbase.get_falcon_header()
strategy_url = falcon_base.url + '/api/v1/nodata'
params = {
'url': strategy_url,
'headers': falcon_header,
'timeout':
}
res = requests.get(**params)
data = json.loads(res.text)
res = json.dumps(data)
with open('nodata.json', mode='w') as f:
f.write(res)
print res def open_nodata(self):
with open('nodata.json','r') as f:
res=f.read()
dic = json.loads(res)
return dic def create_nodata(self):
nodata_list = self.open_nodata()
falcon_header = self.falconbase.get_falcon_header()
create_nodata = falcon_base.url + '/api/v1/nodata/'
s = requests.Session()
params = {
'url': create_nodata,
'headers': falcon_header,
'timeout': ,
} for nodata in nodata_list:
if nodata['creator'] == get_nodata_creator:
payload = {
"tags": nodata['tags'],
"step": nodata['step'],
"obj_type": nodata['obj_type'],
"obj": nodata['obj'],
"name": nodata['name'],
"mock": nodata['mock'],
"metric": nodata['metric'],
"dstype": nodata['dstype'] }
params['data'] = json.dumps(payload)
result = s.post(**params)
print result.text if __name__ == '__main__':
falconinfo = falcon_template(falcon_base.user, falcon_base.password)
falconinfo.create_nodata()
falcon的api的更多相关文章
- 使用open-falcon监控Nginx
一.介绍 前段时间部署试用了open-falcon v0.2,官方文档很详细,难度也不是很大.监控Nginx也参考了文档推荐的方式,文档地址:http://book.open-falcon.org/z ...
- open-falcon监控nginx
主要逻辑:通过lua nginx module的log_by_lua_file实时记录nginx请求数据,通过外部python脚本定时获取数据解析为Open-Falcon支持的数据类型. Nginx编 ...
- python三大web框架Django,Flask,Flask,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架
Python几种主流框架 从GitHub中整理出的15个最受欢迎的Python开源框架.这些框架包括事件I/O,OLAP,Web开发,高性能网络通信,测试,爬虫等. Django: Python We ...
- Django,Flask,Tornado三大框架对比,Python几种主流框架,13个Python web框架比较,2018年Python web五大主流框架
Django 与 Tornado 各自的优缺点Django优点: 大和全(重量级框架)自带orm,template,view 需要的功能也可以去找第三方的app注重高效开发全自动化的管理后台(只需要使 ...
- 从 falcon api 中获取数据
import json import time import requests openfalcon = 'http://ip:port/api/v1' user = 'user' password ...
- 【nodejs】使用Node.js实现REST Client调用REST API
最近在产品中开发基于REST的API接口,结合自己最近对Node.js的研究,想基于它开发一个REST Client做测试之用. 通过初步研究,Node.js开发HTTP Client还是挺方便的. ...
- 为你的机器学习模型创建API服务
1. 什么是API 当调包侠们训练好一个模型后,下一步要做的就是与业务开发组同学们进行代码对接,以便这些‘AI大脑’们可以顺利的被使用.然而往往要面临不同编程语言的挑战,例如很常见的是调包侠们用Pyt ...
- centos安装 Falcon+
1:环境 准备 : 安装 go环境 :下载 - Golang中国 参照 :http://www.cnblogs.com/Amos-Turing/p/8494250.html 安装 mysql 安装 r ...
- 设计 REST API 的13个最佳实践
写在前面 之所以翻译这篇文章,是因为自从成为一名前端码农之后,调接口这件事情就成为了家常便饭,并且,还伴随着无数的争论与无奈.编写友好的 restful api 不论对于你的同事,还是将来作为第三方服 ...
随机推荐
- process-hacker
https://github.com/processhacker/processhacker#process-hacker // begin_phapppub typedef enum _PH_KNO ...
- 学习python os commands socket模块
import os print(os.getcwd()) #获取当前路径, 导包也是从这个路径下面才能找到 # os.chdir('./..') #返回上一级路径,再获取路径看看 # print(os ...
- thinkphp 项目不能直接域名访问 而要加index.php 才能访问
一.apache 服务器配置问题 vim /usr/local/apache2/conf/httpd.conf 在ifModule这里加入index.php <IfModule dir_modu ...
- JavaScript 工作原理之十-使用 MutationObserver 监测 DOM 变化
原文请查阅这里,略有删减,本文采用知识共享署名 4.0 国际许可协议共享,BY Troland. 本系列持续更新中,Github 地址请查阅这里. 这是 JavaScript 工作原理的第十章. 网络 ...
- NODE升级到V12.X.X
Node.js 是一个基于Chrome JavaScript运行时的平台,可轻松构建快速,可扩展的网络应用程序.最新版本 node.js yum存储库 由其官方网站维护.使用本教程添加yum存储库,并 ...
- JavaScript 复杂判断的更优雅写法借鉴
前言: 我们编写js代码时经常遇到复杂逻辑判断的情况,通常大家可以用if/else或者switch来实现多个条件判断,但这样会有个问题,随着逻辑复杂度的增加,代码中的if/else/switch会变得 ...
- js执行上下文与执行上下文栈
一.什么是执行上下文 简单说就是代码运行时的执行环境,必须是在函数调用的时候才会产生,如果不调用就不会产生这个执行上下文.在这个环境中,所有变量会被事先提出来(变量提升),有的直接赋值,有的为默认值 ...
- linux运维、架构之路-Zabbix自动化
一.Zabbix自定义监控 web01客户端修改/etc/zabbix/zabbix_agentd.conf [root@m01 tools]# echo "UserParameter=lo ...
- java通配符写法
有时候我们会遇到这样的需求,需要把一个报文里的某些参数项通过通配符的形式配置成我们需要的结果值插入回报文中. String filetext = "<cn>#用户身份ID(主账号 ...
- WEB前端开发的思考与感悟
当我想要认真写一篇文章向大家分享我对前端的认识与感悟的时候,突然就深刻的体会到了这句话确实太有道理了. 最近几年对于web前端的传闻很多,比如人才稀缺,简单易学,待遇丰厚,整体势头发展良好等等.遇到过 ...