PYTHON_API_INPUT

#!/usr/bin/python
# -*- coding:utf8 -*-

 

"""

"""


import json, sys, argparse
from zabbix_api import ZabbixAPI
import urllib2
import os
import datetime
import time

 


zabbix_header = {"Content-Type": "application/json"}
zabbix_user = "xxxxx"
zabbix_pass = "xxxxxx"

auth_data = json.dumps(
{
"jsonrpc": "2.0",
"method": "user.login",
"params":
{
"user": zabbix_user,
"password": zabbix_pass
},
"id": 0
})

class connect_zabbix(object):

def __init__(self, mechaine_base, host_ip, db_type):
self.mechaine_base = mechaine_base
self.host_ip = host_ip
self.db_type = db_type

 

 


def get_server(self):
if self.mechaine_base == 'xx':
server_addr = "http://xxxx.xxx.xxx/api_jsonrpc.php"
return server_addr
else:
return 0



def user_login(self):
server_url = self.get_server()
if server_url != 0:
auth_data = json.dumps(
{
"jsonrpc": "2.0",
"method": "user.login",
"params":
{
"user": zabbix_user,
"password": zabbix_pass
},
"id": 0
})
request = urllib2.Request(server_url,auth_data)
for key in zabbix_header:
request.add_header(key,zabbix_header[key])
try:
result = urllib2.urlopen(request)
except Exception as e:
print "Auth Failed, Please Check Your Name And Password:",e.code
else:
response = json.loads(result.read())
result.close()
authID = response['result']
return authID

def get_data(self,data,hostip=""):
server_url = self.get_server()
request = urllib2.Request(server_url,data)
for key in zabbix_header:
request.add_header(key,zabbix_header[key])
try:
result = urllib2.urlopen(request)
except Exception as 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 fulfill the request.'
print 'Error code: ', e.code
return 0
else:
response = json.loads(result.read())
result.close()
return response

 

def host_get_by_ip(self):
authID = self.user_login()
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostinterface.get",
"params": {
"output": "extend",
"filter": {
"ip": [
self.host_ip,
]
}
},
"auth": authID,
"id": 1
})
result = self.get_data(data)['result']
print result
if result:
hostid = result[0].get('hostid')

data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter": {
"hostid": [
hostid,
]
}
},
"auth": authID,
"id": 1
})
result = self.get_data(data)['result']
if result:
hostid = result[0].get('hostid')
#hostname = result[0].get('name')
return hostid

def host_group_get(self):
authID = self.user_login()
if self.db_type == 'mutimysql':
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": [
"mysql"
]
}
},
"auth": authID,
"id": 1
}
)
else:
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": [
self.db_type
]
}
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)['result']
if result:
groupid = result[0].get('groupid')
return groupid

def get_group_host(self):
authID = self.user_login()
hostid = self.host_get_by_ip()
#groupid = self.host_group_get()
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "hostid",
"selectGroups": "extend",
"filter": {
"hostid": hostid
}
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)['result']
if result:
groups = result[0].get('groups')
groupids = []
for group in range(len(groups)):
groupids.append(groups[group].get('groupid'))
return groupids

def update_group_host(self):
authID = self.user_login()
hostid = self.host_get_by_ip()
groupids = self.get_group_host()
new_groupid = self.host_group_get()
groupids.append(new_groupid)
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": hostid,
"groups": groupids
},
"auth": authID,
"id": 1
}
)

result = self.get_data(data)
print result


def get_template_id(self):
authID = self.user_login()
if self.db_type == 'mysql':
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "templateid",
"filter": {
"host": ["Template Percona MySQL Server"]
}
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)['result']
template_id = result[0].get('templateid')
print template_id
return template_id
elif self.db_type == 'mutimysql':
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "templateid",
"filter": {
"host": ["Percona MySQL Server Multiport Template"]
}
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)['result']
template_id = result[0].get('templateid')
return template_id
elif self.db_type == 'redis':
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "templateid",
"filter": {
"host": ["Template Redis Auto Discovery"]
}
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)['result']
template_id = result[0].get('templateid')
return template_id
elif self.db_type == 'mongo':
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "templateid",
"filter": {
"host": ["Template App MongoDB"]
}
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)['result']
template_id = result[0].get('templateid')
return template_id
elif self.db_type == 'es':
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "templateid",
"filter": {
"host": ["Elasticsearch Cluster"]
}
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)['result']
template_id = result[0].get('templateid')
return template_id

def add_template_host(self):
authID = self.user_login()
template_id = self.get_template_id()
hostid = self.host_get_by_ip()
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "template.massadd",
"params": {
"templates": template_id,
"hosts": hostid
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)
return result


def del_template_host(self):
authID = self.user_login()
template_id = self.get_template_id()
hostid = self.host_get_by_ip()
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": hostid,
"templates_clear": template_id
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)
print result
return result

def input_host_zabbix(self):
db_type = self.db_type

if db_type == 'mysql':
cmd = '/data/webget/zabbix_api_input/single_mysql_zabbix --host_ip=%s' %(self.host_ip)
if os.system(cmd) == 0:
self.add_template_host()
else:
return "execute fail for zabbix_mysql init scripts!!!"
elif db_type == 'mutimysql':
cmd = '/data/webget/zabbix_api_input/muti_mysql_zabbix --host_ip=%s' %(self.host_ip)
if os.system(cmd) == 0:
self.add_template_host()
else:
return "execute fail for zabbix_muti_mysql init scripts!!!"
elif db_type == 'redis':
cmd = '/data/webget/zabbix_api_input/install_redis_zabbix --host_ip=%s' %(self.host_ip)
if os.system(cmd) == 0:
self.add_template_host()
else:
return "execute fail for zabbix_redis init scripts!!!"
elif db_type == 'mongo':
cmd = '/data/webget/zabbix_api_input/mongo_zabbix --host_ip=%s' %(self.host_ip)
if os.system(cmd) == 0:
self.add_template_host()
else:
return "execute fail for zabbix_mongo init scripts!!!"
elif db_type == 'es':
cmd = '/data/webget/zabbix_api_input/es_zabbix --host_ip=%s' %(self.host_ip)
if os.system(cmd) == 0:
self.add_template_host()
else:
return "execute fail for zabbix_mongo init scripts!!!"


def create_maintence(self):
authID = self.user_login()
hostid = self.host_get_by_ip()
print hostid
maintence_name = "%s_maintence_10_hour" %(self.host_ip)
now = datetime.datetime.now()
now_str = now.strftime('%Y-%m-%d %H:%M:%S')
now_str_new = time.strptime(now_str, '%Y-%m-%d %H:%M:%S')
active_since = int(time.mktime(now_str_new))

now_tem = now + datetime.timedelta(days=1)
now_str_tem = now_tem.strftime('%Y-%m-%d %H:%M:%S')
now_str_tem_new = time.strptime(now_str_tem, '%Y-%m-%d %H:%M:%S')
active_still = int(time.mktime(now_str_tem_new))
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "maintenance.create",
"params": {
"name": maintence_name,
"active_since": active_since,
"active_till": active_still,
"hostids": [ hostid ],
"timeperiods": [
{
"timeperiod_type": 0,
"period": 36000
}
]
},
"auth": authID,
"id": 1
}
)

result = self.get_data(data)
print result
return result

def get_maintence_id(self):
authID = self.user_login()
maintence_name = "%s_maintence_10_hour_1" % (self.host_ip)
print maintence_name
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "maintenance.get",
"params": {
"output": "extend",
"filter": {
"name": [ maintence_name ]
}
},
"auth": authID,
"id": 1
}
)
result = self.get_data(data)['result']
if result:
print result
maintence_id = result[0].get('maintenanceid')
print maintence_id
return maintence_id

def del_maintence(self):
authID = self.user_login()
maintence_id = self.get_maintence_id()
print maintence_id
if maintence_id:
data = json.dumps(
{
"jsonrpc": "2.0",
"method": "maintenance.delete",
"params": [
maintence_id
],
"auth": authID,
"id": 1
}
)

result = self.get_data(data)
print result
return result

 

 


if __name__ == "__main__":
mechaine_base = 'bj'
db_type = 'es'
f = open("host.txt", "r")
lines = f.readlines()
for host_ip in lines:
print host_ip
host_ip_new = host_ip.strip('\n')
host_id = connect_zabbix(mechaine_base, host_ip_new, db_type)
#获取主机id
#host_id.host_get_by_ip()
#获取主机组
#host_id.host_group_get()
#host_id.get_group_host()
#更新主机组
host_id.update_group_host()
#获取模板ID
#host_id.get_template_id()
#给主机增加模板
#host_id.add_template_host()
#删除主机模板
#host_id.del_template_host()
#DB主机接入ZABBIX, 目前已能自动接入单实例MYSQL, REDIS
#host_id.input_host_zabbix()
#添加维护模式
host_id.create_maintence()
#获取维护ID
#host_id.get_maintence_id()
#删除维护模式
#host_id.del_maintence()
f.close()

 

posted @ 2019-01-06 14:25  SMALL-D  阅读(250)  评论(0编辑  收藏  举报