python连接服务器api获取token获取数据_Python3通过Zabbix API获取数据

#!/usr/bin/env python

#For Python3

import urllib.request,urllib.parse,json,sys,importlib,argparse

importlib.reload(sys)

class zbxAPI():

def __init__(self):

self.url = "http://10.10.2.2/zabbix/api_jsonrpc.php"

self.headers = {

'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',

'Content-Type':'application/json'

}

self.authdata = {

"jsonrpc":"2.0",

"method":"user.login",

"params":

{

"user":"uname",

"password":"password"

},

"id":0

}

#获取Token(auth data)

def get_token(self):

res = self.post_request(self.authdata)

if 'result' in res:

token = res['result']

return token

else:

return res['error']['data']

#发送参数到Zabbix服务器端请求数据

def post_request(self,postdata):

postdata = bytes(json.dumps(postdata),'utf8')

try:

request = urllib.request.Request(self.url,postdata,headers=self.headers)

reponse = urllib.request.urlopen(request).read()

content = json.loads(reponse.decode('utf8'))

return content

except Exception as ErrorMsg:

return ErrorMsg

exit()

#获取host列表

def list_hosts(self):

host_list=[]

get_data = {

"jsonrpc":"2.0",

"method":"host.get",

"params":{

"output": "extend",

},

"auth":self.get_token(),

"id":1,

}

res = self.post_request(get_data)

reslist = res['result']

for res in reslist:

host_list.append(res['host'])

return(host_list)

#获取template列表

def list_templates(self):

template_list=[]

get_data = {

"jsonrpc":"2.0",

"method":"template.get",

"params":{

"output": "extend",

},

"auth":self.get_token(),

"id":1,

}

res = self.post_request(get_data)

reslist = res['result']

for res in reslist:

print(res['templateid'] + ',' + res['host'])

#测试认证是否成功,成功则打印auth data

def Auth_test(self):

print(self.get_token())

m=zbxAPI()

# m.Auth_test()

# print(m.list_hosts())

m.list_templates()

标签:get,res,self,request,host,list,获取数据,Zabbix,API

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值