初始化zabbixApi
所需要的常量及插件
import urllib.request
import json
ZABBIX_URL = 'http://zabbix.xxx.com/zabbix/api_jsonrpc.php'
ZABBIX_USERNAME = 'Admin'
ZABBIX_PASSWORD = 'xxx'
init
def __init__(self):
self.url = ZABBIX_URL
self.username = ZABBIX_USERNAME
self.password = ZABBIX_PASSWORD
self.auth = self.authenticate(self.username, self.password)
def requestJson(self, values):
data = json.dumps(values).encode('utf-8')
req = urllib.request.Request(self.url, data, {'Content-Type': 'application/json-rpc'})
response = urllib.request.urlopen(req, data)
a = response.read().decode(encoding='utf-8')
output = json.loads(a)
try:
message = output['result']
except:
message = output['error']['data']
quit()
return output['result']
获取权限auth
登录api
def authenticate(self, username, password):
values = {'jsonrpc': '2.0',
'method': 'user.login',
'params': {
'user': username,
'password': password
},
'id': '0'
}
idvalue = self.requestJson(values)
return idvalue
创建host
def host_create(self, hostname, hostip, hostGroupName, templateName):
'''
创建host,并分配分组,关联模版
host_create('host3','1.1.2.1','gp1 test,gp2 test','Template App FTP Service,Template App HTTP Service')
:param hostname: 'host3'
:param hostip: '1.1.2.1'
:param hostGroupName: 多个组逗号分割'gp1 test,gp2 test'
:param templateName: 多个模版都逗号分割'Template App FTP Service,Template App HTTP Service'
:return:
'''
# 判断主机名是否重复。 zabbix不允许主机名重复
find_hostname = self.host_get(hostname)
if len(find_hostname):
print("###recheck### hostname[%s] exists and return" % hostname)
return 1
# 判断template是否存才,不存在退出。 否则初始化备用
template_list = []
for t in templateName.split(','):
find_template = self.template_get(t)
if not len(find_template):
# template不存在退出 # 一般因为输错关系
print("###recheck### template[%s] not find and return " % t)
return 1
tid = self.template_get(t)[0]['templateid']
template_list.append({'templateid': tid})
# 判断hostgroup是否存在。 不存在则创建。 并初始化hostgroup_list备用
hostgroup_list = []
for g in hostGroupName.split(','):
find_hostgroupname = self.hostgroup_get(g)
if not len(find_hostgroupname):
# hostgroupname 不存在,创建
self.hostgroup_create(g)
# {'jsonrpc': '2.0', 'result': [{'groupid': '15', 'name': 'linux group 1', 'internal': '0', 'flags': '0'}],'id': 1}
gid = self.hostgroup_get(g)[0]['groupid']
hostgroup_list.append({'groupid': gid})
values = {
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": hostname,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": hostip,
"dns": "",
"port": "10050"
}
],
"groups": hostgroup_list,
"templates": template_list,
},
"auth": self.auth,
"id": 1
}
output = self.requestJson(values)
return output
测试
if __name__ == '__main__':
zabbix = ZabbixApi()
print("...login success...")
zabbix.host_create('host7','1.1.2.1','gp1 test,gp2 test','Template App FTP Service,Template App HTTP Service')