其他分享
首页 > 其他分享> > falcon的api

falcon的api

作者:互联网

一、判断session是否有效

# -*- coding: UTF-8 -*-
#!/usr/bin/env python
# Created by Administrator on 2017/12/15
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': 30
}
res1 = requests.get(**params)
data1 = json.loads(res1.text)
print(data1)
View Code

 2、获取session

# -*- coding: UTF-8 -*-
# !/usr/bin/env python
import json
import time
import requests

ip = '172.20.16.5'
user = 'admin'
api_port = '8080'  # 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': 30
}

payload = {
    # "startTime": 1466956800,
    "endTime": int(time.time()),
    "status": "PROBLEM",
    "process_status": "ignored,unresolved",

}
print params['headers']['sig']
View Code

 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()
View Code

 3)更新

# -*- 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
        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': 30
        }
        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 = 1
        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': 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()
        oneday = 86400
        alarm_url = falcon_base.url + '/api/v1/alarm/event_note'
        print alarm_url
        params = {
            'url': alarm_url,
            'headers': falcon_header,
            'timeout': 30,
            # "startTime": int(time.time() - oneday * 2),
            # "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 = 86400
        params = {
            'url': eventcases_url,
            'headers': falcon_header,
            'timeout': 30
        }
        payload = {
            "startTime": int(time.time() - oneday*5),
            "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] = 1
            else:
                template_count[template_id] += 1
            if metric in proble_count:
                proble_count[metric] += 1
            else:
                proble_count[metric] = 1
            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()
View Code

 4)添加模板

# -*- coding: UTF-8 -*-

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': 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 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': 30
        }
        payload = {
            "parent_id": 0, # 继承现有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': 30
        }
        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 = 1
        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': 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 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': 30
        }
        res = requests.get(**params)
        data = json.loads(res.text)
        print data

    def get_alarm(self):
        falcon_header = self.falconbase.get_falcon_header()
        oneday = 86400
        alarm_url = falcon_base.url + '/api/v1/alarm/event_note'
        print alarm_url
        params = {
            'url': alarm_url,
            'headers': falcon_header,
            'timeout': 30,
            # "startTime": int(time.time() - oneday * 2),
            # "endTime": int(time.time()),
        }
        res = requests.get(**params)
        print res
        data = json.loads(res.text)
        print data

    def get_strategy(self):
        # 获取模板监控项目
        id = 4
        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': 30
        }
        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': 30
        }
        for strategy in strategy_dic:
            payload = {
                  "tpl_id": 10,          # 对应模板的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-8 -*-

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': 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 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': 30
        }
        payload = {
            "parent_id": 0, # 继承现有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': 30
        }
        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 = 1
        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': 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 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': 30
        }
        res = requests.get(**params)
        data = json.loads(res.text)
        print data

    def get_alarm(self):
        falcon_header = self.falconbase.get_falcon_header()
        oneday = 86400
        alarm_url = falcon_base.url + '/api/v1/alarm/event_note'
        print alarm_url
        params = {
            'url': alarm_url,
            'headers': falcon_header,
            'timeout': 30,
            # "startTime": int(time.time() - oneday * 2),
            # "endTime": int(time.time()),
        }
        res = requests.get(**params)
        print res
        data = json.loads(res.text)
        print data

    def get_strategy(self):
        # 获取模板监控项目
        id = 4
        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': 30
        }
        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': 30
        }
        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 = '999'
            if float_value < 0:
                str_value = '999'
            payload = {
                "tpl_id": 14,  # 对应模板的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()
View Code

 

标签:get,url,self,header,api,falcon,data
来源: https://www.cnblogs.com/linu/p/11233790.html