如果頻繁使用api,建議先調用z.access(),登錄失敗後再調用z.user_login()生成先的sessionis。
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import json
import ssl
import urllib.parse
import urllib.request
class zabbix_login:
def __init__(self):
self.url = 'https://10.200.2.2/zabbix/api_jsonrpc.php'
self.header = {"Content-Type": "application/json"}
def user_login(self):
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "Admin",
"password": "zabbix"
},
"id": 0
})
ssl._create_default_https_context = ssl._create_unverified_context
postdata=data.encode('utf8')
request=urllib.request.Request(self.url,postdata,self.header)
result=urllib.request.urlopen(request)
response = json.loads(result.read())
result.close()
try:
f = response['result']
fo = open("access.log", "w")
fo.writelines(f)
self.login=response['result']
return self.login
except KeyError as e:
print ("please check zabbix password")
def access(self):
file = 'access.log'
try:
f = open(file,'r+')
access_token = f.read()
#print('get success %s' % access_token)
f.close()
return access_token
except Exception as e:
print(e)
if __name__ == "__main__":
z = zabbix_login()
print(z.access())