# /usr/bin/env python3
# -*- coding:utf-8 -*-
import requests
import json
import os
ip = ‘172.22.25.50‘
user = ‘Admin‘
password = ‘N1i2H3a,o.‘
class ZabbixApi:
def __init__(self, ip, user, password):
self.url = ‘http://‘ + ip + ‘/api_jsonrpc.php‘ # ‘http://ip/zabbix/api_jsonrpc.php‘
self.headers = {"Content-Type": "application/json",
}
self.user = user
self.password = password
self.auth = self.__login()
def __login(self):
‘‘‘
zabbix登陆获取auth
‘‘‘
data = json.dumps({
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": self.user,
"password": self.password
},
"id": 10,
})
try:
response = requests.post(url=self.url, headers=self.headers, data=data, timeout=2)
# {"jsonrpc":"2.0","result":"bdc64373690ab9660982e0bafe1967dd","id":10}
auth = response.json().get(‘result‘, ‘‘)
return auth
except Exception as e:
print("\033[0;31;0m Login error check: IP,USER,PASSWORD\033[0m")
raise Exception
def host_get(self, hostname=‘‘):
‘‘‘
获取主机。不输入hostname 则获取所有
:param hostName: zabbix主机名不允许重复。(IP允许重复)。#host_get(hostname=‘gateway1‘)
:return: {‘jsonrpc‘: ‘2.0‘, ‘result‘: [], ‘id‘: 21}
:return: {‘jsonrpc‘: ‘2.0‘, ‘result‘: [{‘hostid‘: ‘10277‘, ... , ‘host‘: ‘gateway‘, ...}], ‘id‘: 21}
‘‘‘
if hostname == ‘‘:
# print("no hostname and find all host")
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": [
"hostid",
"host"
],
"selectInterfaces": [
"interfaceid",
"ip"
]
},
"id": 20,
"auth": self.auth
})
else:
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {"output": "extend",
"filter": {"host": hostname},
},
"id": 21,
"auth": self.auth
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get(‘result‘,‘‘))
# print(‘l‘,hosts)
return response.json() # len(ret.get(‘result‘))为1时获取到,否则未获取到。
except Exception as e:
print("\033[0;31;0m HOST GET ERROR\033[0m")
raise Exception
def hostgroup_get(self,hostGroupName=‘‘):
‘‘‘
获取主机组
:param hostGroupName:
:return: {‘jsonrpc‘: ‘2.0‘, ‘result‘: [{‘groupid‘: ‘15‘, ‘name‘: ‘linux group 1‘, ‘internal‘: ‘0‘, ‘flags‘: ‘0‘}], ‘id‘: 1}
‘‘‘
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": hostGroupName
}
},
"auth": self.auth,
"id": 1,
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get(‘result‘,‘‘))
# print(‘l‘,hosts)
return response.json() # len(ret.get(‘result‘))为1时获取到,否则未获取到。
except Exception as e:
print("\033[0;31;0m HOSTGROUP GET ERROR\033[0m")
raise Exception
def hostgroup_create(self,hostGroupName=‘‘):
if len(self.hostgroup_get(hostGroupName).get(‘result‘))==1:
print("群组%s已存在" % hostGroupName)
return 100
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": hostGroupName
},
"auth": self.auth,
"id": 1
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get(‘result‘,‘‘))
# print(‘l‘,hosts)
print("群组%s创建成功" % hostGroupName)
return response.json() # len(ret.get(‘result‘))为1时获取到,否则未获取到。
except Exception as e:
print("\033[0;31;0m HOSTGROUP CREATE ERROR\033[0m")
raise Exception
def template_get(self, templateName=‘‘):
data = json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"name": templateName
}
},
"auth": self.auth,
"id": 50,
})
try:
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
# hosts_count=len(response.json().get(‘result‘,‘‘))
# print(‘l‘,hosts)
return response.json() # len(ret.get(‘result‘))为1时获取到,否则未获取到。
except Exception as e:
print("\033[0;31;0m Template GET ERROR\033[0m")
raise Exception
def host_create(self,hostname,ip,groupname,templatename):
#校验主机名是否存在
if len(self.host_get(hostname).get(‘result‘)) == 1:
print("主机%s已存在" % hostname)
return 100
#校验主机群组是否存在,不存在添加,多个群组已‘,‘分割
hostgroup_list = []
for g in groupname.split(‘,‘):
find_hostgroupname = self.hostgroup_get(g)
if not len(find_hostgroupname.get(‘result‘)):
print(find_hostgroupname.get(‘result‘))
# hostgroupname 不存在,创建
self.hostgroup_create(g)
gid = self.hostgroup_get(g).get(‘result‘)[0][‘groupid‘]
hostgroup_list.append({‘groupid‘: gid})
#print(hostgroup_list)
#校验模板是否存在,多个模板已‘,‘分割,不存在请检查
template_list = []
for t in templatename.split(‘,‘):
find_template = self.template_get(t)
if not len(find_template.get(‘result‘)):
# template不存在退出 # 一般因为输错关系
print(find_template.get(‘result‘))
print("###recheck### template[%s] not find and return " % t)
return 1
tid = self.template_get(t).get(‘result‘)[0][‘templateid‘]
template_list.append({‘templateid‘: tid})
#print(template_list)
#添加zabbix-agent
data_agent = json.dumps({
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": hostname,
"interfaces": [
{
"type": 1,
"main": 1,
"useip": 1,
"ip": ip,
"dns": "",
"port": "10050"
}
],
"groups": hostgroup_list,
"templates": template_list
},
"auth": self.auth,
"id": 1
})
#添加snmp监控
data_snmp = json.dumps({
"jsonrpc": "2.0",
"method": "host.create",
"params": {
"host": hostname,
"interfaces": [
{
"type": 2,
"main": 1,
"useip": 1,
"ip": ip,
"dns": "",
"port": "161",
"details": {
"version": 2,
"bulk": 1,
"securityname": "mysecurityname",
"contextname": "",
"securitylevel": 1,
‘community‘: ‘{$SNMP_COMMUNITY}‘
}
}
],
"groups": hostgroup_list,
"templates": template_list
},
"auth": self.auth,
"id": 1
})
try:
data=data_snmp
response = requests.get(url=self.url, headers=self.headers, data=data, timeout=2)
hosts=len(response.json().get(‘result‘,‘‘))
hostid1=response.json().get(‘result‘,‘‘)
hostid=hostid1[‘hostids‘]
#print(type(hostid1),type(hostid))
print("执行返回信息: 添加HOSTNAME:%s,IP:%s,HOSTID:%s完成"%(hostname,ip,hostid))
return response.json() # len(ret.get(‘result‘))为1时获取到,否则未获取到。
except Exception as e:
print("\033[0;31;0m HOST CREATE ERROR\033[0m")
raise Exception
if __name__ == ‘__main__‘:
zabbix=ZabbixApi(ip,user,password)
#查询单台
#host=zabbix.host_get(‘192.168.56.153‘)
#添加单台
#zabbix.host_create(‘host1‘,‘192.168.56.152‘,‘dell‘,‘Template Dell idrac‘)
#批量添加主机,从同目录下add_hosts文件,文件格式为hostname # ip # 主机群组 #模板
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ADD_LIST = os.path.join(BASE_DIR, ‘add_hosts‘)
print(ADD_LIST)
with open(ADD_LIST, ‘r‘, encoding=‘utf-8‘) as f:
for line in f:
if len(line.strip()): # 跳过空行
serverinfo = line.strip().split(‘#‘)
#print(serverinfo[0].strip("‘"),serverinfo[1].strip("‘"),serverinfo[2].strip("‘"),serverinfo[3].strip("‘"))
zabbix.host_create(serverinfo[0].strip(), serverinfo[1].strip(), serverinfo[2].strip(), serverinfo[3].strip())
原文:https://www.cnblogs.com/jiangbupa/p/14929270.html