#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
import sys
import json
class zabbixtools:
def __init__(self):
self.url = "http://8.8.8.8/zabbix/api_jsonrpc.php"
self.header = {"Content-Type": "application/json"}
self.authID = self.user_login()
def user_login(self):
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "user.login",
"params": {
"user": "Admin",
"password": "Admin"
},
"id": 0
})
request = urllib2.Request(self.url,data)
for key in self.header:
request.add_header(key,self.header[key])
try:
result = urllib2.urlopen(request)
except URLError as e:
print "Auth Failed, Please Check Your Name And Password:"
else:
response = json.loads(result.read())
result.close()
authID = response['result']
return authID
def get_data(self,data,hostip=""):
request = urllib2.Request(self.url,data)
for key in self.header:
request.add_header(key,self.header[key])
try:
result = urllib2.urlopen(request)
except Exception,e:
if hasattr(e,'reason'):
print "we Failed to reach a server"
print 'reason:',e.reason
elif hasattr(e,'code'):
print "the server could not fulfaild the request"
print "error code:",e.code
return 0
else:
response = json.loads(result.read())
result.close()
return response
def host_get(self,hostip):
# 生成json格式数据
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output":["hostid","name","status","host"],
"filter": {"host": [hostip]}
},
"auth": self.authID,
"id": 1
})
res = self.get_data(data)['result']
if (res != 0) and (len(res) != 0):
host = res[0]
# print host
if host['status'] == 1:
print "\x1b[1;32mHost_IP: %s Host_Name: %s down\x1b[0m" % (host['host'],host['name'])
return host['hostid']
else:
print "\x1b[1;32mHost_ip: %s Host_Name: %s up\x1b[0m" % (host['host'],host['name'])
return host['hostid']
else:
print "host_get error please check define host_get()"
return 0
def hostgroup_get(self):
data = json.dumps(
{
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params":{
"output":"extend"
},
"auth":self.authID,
"id":1
})
res = self.get_data(data)
if 'result' in res.keys():
res = res['result']
# print res
if (res != 0) and (len(res) != 0):
for host in res:
print "\x1b[1;32mHost_id: %s Hostgroup_name: %s\x1b[0m" % (host['groupid'],host['name'])
else:
print "Host_Group info Gets the Error"
def template_get(self):
data = json.dumps(
{
"jsonrpc":"2.0",
"method":"template.get",
"params":{
"output":"extend"
},
"auth":self.authID,
"id":1
})
res = self.get_data(data)
if 'result' in res.keys():
res = res['result']
if (res != 0) and (len(res) != 0):
for host in res:
print "\x1b[1;32mTemplate_id: %s Template_name: %s\x1b[0m" % (host['templateid'],host['name'])
else:
print "Templateid gets the error"
def host_delete(self):
hostraw = raw_input("please input your delete hostip:")
if "txt" in hostraw:
for line in open(hostraw):
host = line.strip('\n')
hostid = self.host_get(host)
if hostid == 0:
print "\x1b[1;31mhost_get error please check it"
sys.exit()
# print hostid
else:
data = json.dumps(
{
"jsonrpc":"2.0",
"method":"host.delete",
"params":[{"hostid":hostid}],
"auth":self.authID,
"id":1
})
res = self.get_data(data)['result']
if 'hostids' in res.keys():
print "\x1b[1;32m%s删除成功!!!\x1b[0m" % host
else:
print "\x1b[1;31m%s删除失败!!!\x1b[0m" % host
elif hostraw.strip():
hostlist=hostraw.split()
for index in range(len(hostlist)):
host=hostlist[index]
hostid = self.host_get(host)
if hostid == 0:
print "\x1b[1;31mhost_get error please check it"
sys.exit()
# print hostid
else:
data = json.dumps(
{
"jsonrpc":"2.0",
"method":"host.delete",
"params":[{"hostid":hostid}],
"auth":self.authID,
"id":1
})
res = self.get_data(data)['result']
if 'hostids' in res.keys():
print "\x1b[1;32m%s删除成功!!!\x1b[0m" % host
else:
print "\x1b[1;31m%s删除失败!!!\x1b[0m" % host
else:
print "\x1b[1;31m%splease enter hosts!!!\x1b[0m"
def item_get(self):
hostraw = raw_input("please input your delete hostip:")
if hostraw.strip():
hostlist=hostraw.split()
for index in range(len(hostlist)):
host=hostlist[index]
hostid = self.host_get(host)
print hostid
if hostid == 0:
print "\x1b[1;31mhost_get error please check it"
sys.exit()
else:
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "item.getobjects",
"params": {
"host": hostraw
},
"auth": self.authID,
"id": 1
})
res = self.get_data(data)['result']
for i in res:
if i['error']:
print i['key_']
def host_create(self):
hostip = raw_input("please input hostip:")
groupid = raw_input("please input groupid:")
templateid = raw_input("please input templateid:")
g_list = []
t_list = []
for i in groupid.split(','):
var = {}
var['groupid'] = i
g_list.append(var)
for i in templateid.split(','):
var = {}
var['templateid'] = i
t_list.append(var)
if hostip and groupid and templateid:
data = json.dumps(
{
"jsonrpc":"2.0",
"method":"host.create",
"params":{
"host":hostip,
"interfaces":[
{
"type":1,
"main":1,
"useip":1,
"ip":hostip,
"dns":"",
"port":"10050",
}
],
"groups":g_list,
"templates":t_list
},
"auth":self.authID,
"id":1
})
res = self.get_data(data,hostip)
if 'result' in res:
res = res['result']
if 'hostids' in res.keys():
print "\x1b[1;32m%s \t\t主机添加成功\x1b[0m" % hostip
else:
print "\x1b[1;31m%s \t\t主机添加失败\x1b[0m" % hostip
else:
print "您输入的参数有误."
if __name__ == '__main__':
num = raw_input('\x1b[1;30mplease input 1(create host) or 2(delete host)?\x1b[0m')
if not num.strip():
print "Your input num is null!!!"
if num == str(1):
a = zabbixtools()
a.hostgroup_get()
a.template_get()
a.host_create()
elif num == str(2):
a = zabbixtools()
a.host_delete()
elif num == str(3):
a = zabbixtools()
a.item_get()
else:
print "you input num noteq 1 or 2"
转载于:https://my.oschina.net/honglongwei/blog/668085