Zabbix

Zabbix

Python调用Zabbix API实例

运维技术Nock 发表了文章 • 0 个评论 • 395 次浏览 • 2016-12-06 19:59 • 来自相关话题

#!/usr/bin/python
#coding:utf-8


import json
import urllib2
from urllib2 import URLError
import sys,argparse

class zabbix_api:
def __init__(self):
self.url = 'http://192.168.210.13:81/zabbix/api_jsonrpc.php' #修改URL
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
})

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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code
else:
response = json.loads(result.read())
result.close()
#print response['result']
self.authID = response['result']
return self.authID
#主机查询
def host_get(self,hostName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter":{
"host":hostName
}
},
"auth": self.user_login(),
"id": 1
})
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:
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
else:
response = json.loads(result.read())
#print response
result.close()
print "主机数量: \033[31m%s\033[0m"%(len(response['result']))
for host in response['result']:
status={"0":"OK","1":"Disabled"}
available={"0":"Unknown","1":"available","2":"Unavailable"}
#print host
if len(hostName)==0:
print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
else:
print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
return host['hostid']
#图形查询
def graph_get(self,hostids,graphname=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "graph.get",
"params": {
"output": "extend",
"hostids": hostids,
"sortfield": "name"
},
"auth": self.user_login(),
"id":1
})
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:
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
else:
response = json.loads(result.read())
result.close()
print "图形数量: \033[31m%s\033[0m"%(len(response['result']))
for graph in response['result']:
if len(graphname)==0:
print "graphid : %s\t graphname : %s\t width :\033[32m%s\033[0m \t height :\033[31m%s\033[0m"%(graph['graphid'],graph['name'],graph['width'],graph['height'])
else:
print "graphid : %s\t graphname : %s\t width :\033[32m%s\033[0m \t height :\033[31m%s\033[0m"%(graph['graphid'],graph['name'],graph['width'],graph['height'])
return graph['graphid']
#筛选图查询
def screen_get(self,ScreenName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "screen.get",
"params": {
"output": "extend",
"selectScreenItems": "extend",
"filter": {
"name": ScreenName
}
},
"auth":self.user_login(),
"id":1
})

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 'Error as ', e
else:
response = json.loads(result.read())
result.close()
print "筛选图数量: \033[31m%s\033[0m"%(len(response['result']))
for screen in response['result']:
if len(ScreenName)==0:
print "ScreenID : %s\t ScreenName : %s\t Hsize :\033[32m%s\033[0m \t Vsize :\033[31m%s\033[0m"%(screen['screenid'],screen['name'],screen['hsize'],screen['vsize'])
else:
print "ScreenID : %s\t ScreenName : %s\t Hsize :\033[32m%s\033[0m \t Vsize :\033[31m%s\033[0m"%(screen['screenid'],screen['name'],screen['hsize'],screen['vsize'])
return screen['screenid']
#主机组查询
def hostgroup_get(self, hostgroupName=''):
data = json.dumps({
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": hostgroupName
}
},
"auth":self.user_login(),
"id":1
})

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 "Error as ", e
else:
#print result.read()
response = json.loads(result.read())
result.close()
#print response()
for group in response['result']:
if len(hostgroupName)==0:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
else:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
self.hostgroupID = group['groupid']
return group['groupid']
#模版查询
def template_get(self,templateName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"name":templateName
}
},
"auth":self.user_login(),
"id":1
})

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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
#print response
for template in response['result']:
if len(templateName)==0:
print "template : \033[31m%s\033[0m\t id : %s" % (template['name'], template['templateid'])
else:
self.templateID = response['result'][0]['templateid']
print "Template Name : \033[31m%s\033[0m "%templateName
return response['result'][0]['templateid']
#主机组创建
def hostgroup_create(self,hostgroupName):
if self.hostgroup_get(hostgroupName):
print "hostgroup \033[42m%s\033[0m is exist !"%hostgroupName
sys.exit(1)
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": hostgroupName
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加主机组:%s\033[0m hostgroupID : %s"%(hostgroupName,response['result']['groupids'])
#筛选图添加
def screen_create(self,ScreenName,hsize,vsize):
if self.screen_get(ScreenName):
print "Screen \033[42m%s\033[0m is exist !"%ScreenName
sys.exit(1)
data = json.dumps({
"jsonrpc": "2.0",
"method": "screen.create",
"params": {
"name": ScreenName,
"hsize": hsize,
"vsize": vsize
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加筛选图:%s\033[0m ScreenName : %s"%(ScreenName,response['result']['screenids'])
#筛选图图形添加
def screen_item_create(self,screenid,resourceid,x,y):
if self.screen_item_create(resourceid):
print "resource \033[042m%s\033[0m is exist !"%resourceid
sys.exit(1)
screen_list=[]
for i in screenid.split(','):
var = {}
var['screenid'] = self.screen_get(i)
screen_list.append(var)
data = json.dumps({
"jsonrpc": "2.0",
"method": "screenitem.create",
"params": {
"screenid": screen_list,
"resourceid": resourceid,
"x": x,
"y": y
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加筛选图形:%s\033[0m resourceid : %s"%(resourceid,response['result']['resourceids'])
#主机创建
def host_create(self, hostip, hostgroupName, templateName):
if self.host_get(hostip):
print "\033[041m该主机已经添加!\033[0m"
sys.exit(1)

group_list=[]
template_list=[]
for i in hostgroupName.split(','):
var = {}
var['groupid'] = self.hostgroup_get(i)
group_list.append(var)
for i in templateName.split(','):
var={}
var['templateid']=self.template_get(i)
template_list.append(var)

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": group_list,
"templates": template_list,
},
"auth": self.user_login(),
"id":1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])
#关闭主机
def host_disable(self,hostip):
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": self.host_get(hostip),
"status": 1
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print '----主机现在状态------------'
print self.host_get(hostip)
#删除主机
def host_delete(self,hostid):
hostid_list=[]
#print type(hostid)
for i in hostid.split(','):
var = {}
var['hostid'] = self.host_get(i)
hostid_list.append(var)
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.delete",
"params": hostid_list,
"auth": self.user_login(),
"id": 1
})

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:
print e
else:

result.close()
print "主机 \033[041m %s\033[0m 已经删除 !"%hostid
#删除筛选图
def screen_delete(self,screenid):
screenid_list=[]
for i in screenid.split(','):
var = {}
var['screenid'] = self.screen_get(i)
screenid_list.append(var)
data=json.dumps({
"jsonrpc": "2.0",
"method": "screen.delete",
"params": screenid_list,
"auth": self.user_login(),
"id": 1
})
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:
print e
else:
result.close()
print "筛选图 \033[041m %s\033[0m 已经删除 !"%screenid


if __name__ == "__main__":
zabbix=zabbix_api()
parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')
parser.add_argument('-Z','--graph',nargs='?',dest='listgraph',default='graph',help='查询图形')
parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')
parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')
parser.add_argument('-S','--screen',nargs='?',dest='listscreen',default='screen',help='查询筛选图')
parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')
parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主机,多个主机组或模板使用分号')
parser.add_argument('-B','--create-screenitem',dest='addscreenitem',nargs=4,metavar=('38', '365', '0', '0'),help='添加筛选图图形')
parser.add_argument('-J','--add-screen',nargs=3,dest='addscreen',help='添加筛选图')
parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主机')
parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='删除主机,多个主机之间用分号')
parser.add_argument('-P','--delete-screen',dest='deletescreen',nargs='+',metavar=('38'),help='删除筛选图,多个筛选图之间用分号')
parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
if len(sys.argv)==1:
print parser.print_help()
else:
args=parser.parse_args()

if args.listhost != 'host' :
if args.listhost:
zabbix.host_get(args.listhost)
else:
zabbix.host_get()
if args.listgraph != 'graph':
if args.listgraph:
zabbix.graph_get(args.listgraph)
else:
zabbix.graph_get()
if args.listgroup !='group':
if args.listgroup:
zabbix.hostgroup_get(args.listgroup)
else:
zabbix.hostgroup_get()
if args.listtemp != 'template':
if args.listtemp:
zabbix.template_get(args.listtemp)
else:
zabbix.template_get()
if args.listscreen != 'screen':
if args.listscreen:
zabbix.screen_get(args.listscreen)
else:
zabbix.screen_get()
if args.addgroup:
zabbix.hostgroup_create(args.addgroup[0])
if args.addhost:
zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2])
if args.addscreen:
zabbix.screen_create(args.addscreen[0],args.addscreen[1],args.addscreen[2])
if args.addscreenitem:
zabbix.screen_item_create(args.addscreenitem[0],args.addscreenitem[1],args.addscreenitem[2],args.addscreenitem[3])
if args.disablehost:
zabbix.host_disable(args.disablehost)
if args.deletehost:
zabbix.host_delete(args.deletehost[0])
if args.deletescreen:
zabbix.screen_delete(args.deletescreen[0]) 查看全部
#!/usr/bin/python 
#coding:utf-8


import json
import urllib2
from urllib2 import URLError
import sys,argparse

class zabbix_api:
def __init__(self):
self.url = 'http://192.168.210.13:81/zabbix/api_jsonrpc.php' #修改URL
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
})

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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code
else:
response = json.loads(result.read())
result.close()
#print response['result']
self.authID = response['result']
return self.authID
#主机查询
def host_get(self,hostName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter":{
"host":hostName
}
},
"auth": self.user_login(),
"id": 1
})
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:
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
else:
response = json.loads(result.read())
#print response
result.close()
print "主机数量: \033[31m%s\033[0m"%(len(response['result']))
for host in response['result']:
status={"0":"OK","1":"Disabled"}
available={"0":"Unknown","1":"available","2":"Unavailable"}
#print host
if len(hostName)==0:
print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
else:
print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
return host['hostid']
#图形查询
def graph_get(self,hostids,graphname=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "graph.get",
"params": {
"output": "extend",
"hostids": hostids,
"sortfield": "name"
},
"auth": self.user_login(),
"id":1
})
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:
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
else:
response = json.loads(result.read())
result.close()
print "图形数量: \033[31m%s\033[0m"%(len(response['result']))
for graph in response['result']:
if len(graphname)==0:
print "graphid : %s\t graphname : %s\t width :\033[32m%s\033[0m \t height :\033[31m%s\033[0m"%(graph['graphid'],graph['name'],graph['width'],graph['height'])
else:
print "graphid : %s\t graphname : %s\t width :\033[32m%s\033[0m \t height :\033[31m%s\033[0m"%(graph['graphid'],graph['name'],graph['width'],graph['height'])
return graph['graphid']
#筛选图查询
def screen_get(self,ScreenName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "screen.get",
"params": {
"output": "extend",
"selectScreenItems": "extend",
"filter": {
"name": ScreenName
}
},
"auth":self.user_login(),
"id":1
})

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 'Error as ', e
else:
response = json.loads(result.read())
result.close()
print "筛选图数量: \033[31m%s\033[0m"%(len(response['result']))
for screen in response['result']:
if len(ScreenName)==0:
print "ScreenID : %s\t ScreenName : %s\t Hsize :\033[32m%s\033[0m \t Vsize :\033[31m%s\033[0m"%(screen['screenid'],screen['name'],screen['hsize'],screen['vsize'])
else:
print "ScreenID : %s\t ScreenName : %s\t Hsize :\033[32m%s\033[0m \t Vsize :\033[31m%s\033[0m"%(screen['screenid'],screen['name'],screen['hsize'],screen['vsize'])
return screen['screenid']
#主机组查询
def hostgroup_get(self, hostgroupName=''):
data = json.dumps({
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": hostgroupName
}
},
"auth":self.user_login(),
"id":1
})

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 "Error as ", e
else:
#print result.read()
response = json.loads(result.read())
result.close()
#print response()
for group in response['result']:
if len(hostgroupName)==0:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
else:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
self.hostgroupID = group['groupid']
return group['groupid']
#模版查询
def template_get(self,templateName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"name":templateName
}
},
"auth":self.user_login(),
"id":1
})

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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
#print response
for template in response['result']:
if len(templateName)==0:
print "template : \033[31m%s\033[0m\t id : %s" % (template['name'], template['templateid'])
else:
self.templateID = response['result'][0]['templateid']
print "Template Name : \033[31m%s\033[0m "%templateName
return response['result'][0]['templateid']
#主机组创建
def hostgroup_create(self,hostgroupName):
if self.hostgroup_get(hostgroupName):
print "hostgroup \033[42m%s\033[0m is exist !"%hostgroupName
sys.exit(1)
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": hostgroupName
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加主机组:%s\033[0m hostgroupID : %s"%(hostgroupName,response['result']['groupids'])
#筛选图添加
def screen_create(self,ScreenName,hsize,vsize):
if self.screen_get(ScreenName):
print "Screen \033[42m%s\033[0m is exist !"%ScreenName
sys.exit(1)
data = json.dumps({
"jsonrpc": "2.0",
"method": "screen.create",
"params": {
"name": ScreenName,
"hsize": hsize,
"vsize": vsize
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加筛选图:%s\033[0m ScreenName : %s"%(ScreenName,response['result']['screenids'])
#筛选图图形添加
def screen_item_create(self,screenid,resourceid,x,y):
if self.screen_item_create(resourceid):
print "resource \033[042m%s\033[0m is exist !"%resourceid
sys.exit(1)
screen_list=[]
for i in screenid.split(','):
var = {}
var['screenid'] = self.screen_get(i)
screen_list.append(var)
data = json.dumps({
"jsonrpc": "2.0",
"method": "screenitem.create",
"params": {
"screenid": screen_list,
"resourceid": resourceid,
"x": x,
"y": y
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加筛选图形:%s\033[0m resourceid : %s"%(resourceid,response['result']['resourceids'])
#主机创建
def host_create(self, hostip, hostgroupName, templateName):
if self.host_get(hostip):
print "\033[041m该主机已经添加!\033[0m"
sys.exit(1)

group_list=[]
template_list=[]
for i in hostgroupName.split(','):
var = {}
var['groupid'] = self.hostgroup_get(i)
group_list.append(var)
for i in templateName.split(','):
var={}
var['templateid']=self.template_get(i)
template_list.append(var)

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": group_list,
"templates": template_list,
},
"auth": self.user_login(),
"id":1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])
#关闭主机
def host_disable(self,hostip):
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": self.host_get(hostip),
"status": 1
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print '----主机现在状态------------'
print self.host_get(hostip)
#删除主机
def host_delete(self,hostid):
hostid_list=[]
#print type(hostid)
for i in hostid.split(','):
var = {}
var['hostid'] = self.host_get(i)
hostid_list.append(var)
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.delete",
"params": hostid_list,
"auth": self.user_login(),
"id": 1
})

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:
print e
else:

result.close()
print "主机 \033[041m %s\033[0m 已经删除 !"%hostid
#删除筛选图
def screen_delete(self,screenid):
screenid_list=[]
for i in screenid.split(','):
var = {}
var['screenid'] = self.screen_get(i)
screenid_list.append(var)
data=json.dumps({
"jsonrpc": "2.0",
"method": "screen.delete",
"params": screenid_list,
"auth": self.user_login(),
"id": 1
})
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:
print e
else:
result.close()
print "筛选图 \033[041m %s\033[0m 已经删除 !"%screenid


if __name__ == "__main__":
zabbix=zabbix_api()
parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')
parser.add_argument('-Z','--graph',nargs='?',dest='listgraph',default='graph',help='查询图形')
parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')
parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')
parser.add_argument('-S','--screen',nargs='?',dest='listscreen',default='screen',help='查询筛选图')
parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')
parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主机,多个主机组或模板使用分号')
parser.add_argument('-B','--create-screenitem',dest='addscreenitem',nargs=4,metavar=('38', '365', '0', '0'),help='添加筛选图图形')
parser.add_argument('-J','--add-screen',nargs=3,dest='addscreen',help='添加筛选图')
parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主机')
parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='删除主机,多个主机之间用分号')
parser.add_argument('-P','--delete-screen',dest='deletescreen',nargs='+',metavar=('38'),help='删除筛选图,多个筛选图之间用分号')
parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
if len(sys.argv)==1:
print parser.print_help()
else:
args=parser.parse_args()

if args.listhost != 'host' :
if args.listhost:
zabbix.host_get(args.listhost)
else:
zabbix.host_get()
if args.listgraph != 'graph':
if args.listgraph:
zabbix.graph_get(args.listgraph)
else:
zabbix.graph_get()
if args.listgroup !='group':
if args.listgroup:
zabbix.hostgroup_get(args.listgroup)
else:
zabbix.hostgroup_get()
if args.listtemp != 'template':
if args.listtemp:
zabbix.template_get(args.listtemp)
else:
zabbix.template_get()
if args.listscreen != 'screen':
if args.listscreen:
zabbix.screen_get(args.listscreen)
else:
zabbix.screen_get()
if args.addgroup:
zabbix.hostgroup_create(args.addgroup[0])
if args.addhost:
zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2])
if args.addscreen:
zabbix.screen_create(args.addscreen[0],args.addscreen[1],args.addscreen[2])
if args.addscreenitem:
zabbix.screen_item_create(args.addscreenitem[0],args.addscreenitem[1],args.addscreenitem[2],args.addscreenitem[3])
if args.disablehost:
zabbix.host_disable(args.disablehost)
if args.deletehost:
zabbix.host_delete(args.deletehost[0])
if args.deletescreen:
zabbix.screen_delete(args.deletescreen[0])

zabbix怎么重置密码

运维技术koyo 回复了问题 • 2 人关注 • 1 个回复 • 1043 次浏览 • 2015-09-10 11:30 • 来自相关话题

Zabbix监控之Mysql

运维技术Ansible 发表了文章 • 3 个评论 • 996 次浏览 • 2015-08-25 00:28 • 来自相关话题

      使用go语言写了一个采集mysql性能的小程序,通过SDK连接mysql数据库,采集数据库性能指标,同时采集远程数据库的性能,大家可试用一下,欢迎提出修改意见和建议

被监控端设置

监控下载:
   Linux:
                mymon_x86.tar.gz
                mymon_x64.tar.gz
   Windows:
                mymon_windows_amd64.zip
 
Windows:
      下载解压后放在c盘,修改agentd.conf文件,执行脚本路径为:c:\mymon\mymon.exe


      重启agentd即可

Linux:
      修改zabbix agentd配置文件(具体位置根据自身情况设置),添加keyvi /usr/local/zabbix/etc/zabbix_agentd.conf      添加如下:




      添加好之后执行mkdir -p /usr/local/zabbix/bin/mysql/
cd /usr/local/zabbix/bin/mysql/
wget http://dl.cactifans.org/tools/mymon_x64.tar.gz
tar zxvf mymon_x64.tar.gz
chmod a+x mymon      同时编辑cfg.json配置文件,设置要监控数据库的连接参数vi /usr/local/zabbix/bin/mysql/cfg.json      文件内容如下{
"mysql": {
"username": "root",
"password": "123456",
"host": "localhost",
"port": 3306
},
"sever": {
"log": "/tmp/mon.log"
}
}      登录数据库的账号,密码等信息,log项目不用设置,默认即可
      设置好之后重启zabixx agentservice zabbix-agent restart

zabbix服务端设置

      测试agent是否工作正常/usr/local/bin/zabbix_get -s 192.168.7.186 -k mysql.status[GlobalStatus,Uptime]      如果有一下回显,表示工作正常[root@vm153 ~]# /usr/local/bin/zabbix_get -s 192.168.7.186 -k mysql.status[GlobalStatus,Uptime]
12364726
[root@vm153 ~]#      导入模版:zabbix_mysql_templates.xml
      并关联到主机
      效果:




      参数:




      PS:可自行添加对应key可监控项目,模版自带了几种,脚本包括800多项目



具体更具key定义,括号内第一项为key类型,分GlobalStatus和GlobalVariables二种,后面的数值为在mysql里执行“SHOW /!50001 GLOBAL / STATUS”和“SHOW /!50001 GLOBAL / VARIABLES”,对应的key,注意有些数值为固定数值,有些key的类型为每秒速差,自行添加.原文地址 查看全部
      使用go语言写了一个采集mysql性能的小程序,通过SDK连接mysql数据库,采集数据库性能指标,同时采集远程数据库的性能,大家可试用一下,欢迎提出修改意见和建议


被监控端设置


监控下载:
   Linux:
                mymon_x86.tar.gz
                mymon_x64.tar.gz
   Windows:
                mymon_windows_amd64.zip
 
Windows:
      下载解压后放在c盘,修改agentd.conf文件,执行脚本路径为:
c:\mymon\mymon.exe


      重启agentd即可

Linux:
      修改zabbix agentd配置文件(具体位置根据自身情况设置),添加key
vi /usr/local/zabbix/etc/zabbix_agentd.conf
      添加如下:
zmy4.png

      添加好之后执行
mkdir -p /usr/local/zabbix/bin/mysql/
cd /usr/local/zabbix/bin/mysql/
wget http://dl.cactifans.org/tools/mymon_x64.tar.gz
tar zxvf mymon_x64.tar.gz
chmod a+x mymon
      同时编辑cfg.json配置文件,设置要监控数据库的连接参数
vi /usr/local/zabbix/bin/mysql/cfg.json
      文件内容如下
{
"mysql": {
"username": "root",
"password": "123456",
"host": "localhost",
"port": 3306
},
"sever": {
"log": "/tmp/mon.log"
}
}
      登录数据库的账号,密码等信息,log项目不用设置,默认即可
      设置好之后重启zabixx agent
service zabbix-agent restart


zabbix服务端设置


      测试agent是否工作正常
/usr/local/bin/zabbix_get -s 192.168.7.186 -k mysql.status[GlobalStatus,Uptime]
      如果有一下回显,表示工作正常
[root@vm153 ~]#  /usr/local/bin/zabbix_get -s 192.168.7.186 -k mysql.status[GlobalStatus,Uptime]
12364726
[root@vm153 ~]#
      导入模版:zabbix_mysql_templates.xml
      并关联到主机
      效果:
zmy1.png

      参数:
zmy2.png

      PS:可自行添加对应key可监控项目,模版自带了几种,脚本包括800多项目
zmy3.png
具体更具key定义,括号内第一项为key类型,分GlobalStatus和GlobalVariables二种,后面的数值为在mysql里执行“SHOW /!50001 GLOBAL / STATUS”和“SHOW /!50001 GLOBAL / VARIABLES”,对应的key,注意有些数值为固定数值,有些key的类型为每秒速差,自行添加.
原文地址

zabbix怎么重置密码

运维技术koyo 回复了问题 • 2 人关注 • 1 个回复 • 1043 次浏览 • 2015-09-10 11:30 • 来自相关话题

zabbix怎么重置密码

回复

运维技术koyo 回复了问题 • 2 人关注 • 1 个回复 • 1043 次浏览 • 2015-09-10 11:30 • 来自相关话题

Python调用Zabbix API实例

运维技术Nock 发表了文章 • 0 个评论 • 395 次浏览 • 2016-12-06 19:59 • 来自相关话题

#!/usr/bin/python
#coding:utf-8


import json
import urllib2
from urllib2 import URLError
import sys,argparse

class zabbix_api:
def __init__(self):
self.url = 'http://192.168.210.13:81/zabbix/api_jsonrpc.php' #修改URL
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
})

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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code
else:
response = json.loads(result.read())
result.close()
#print response['result']
self.authID = response['result']
return self.authID
#主机查询
def host_get(self,hostName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter":{
"host":hostName
}
},
"auth": self.user_login(),
"id": 1
})
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:
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
else:
response = json.loads(result.read())
#print response
result.close()
print "主机数量: \033[31m%s\033[0m"%(len(response['result']))
for host in response['result']:
status={"0":"OK","1":"Disabled"}
available={"0":"Unknown","1":"available","2":"Unavailable"}
#print host
if len(hostName)==0:
print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
else:
print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
return host['hostid']
#图形查询
def graph_get(self,hostids,graphname=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "graph.get",
"params": {
"output": "extend",
"hostids": hostids,
"sortfield": "name"
},
"auth": self.user_login(),
"id":1
})
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:
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
else:
response = json.loads(result.read())
result.close()
print "图形数量: \033[31m%s\033[0m"%(len(response['result']))
for graph in response['result']:
if len(graphname)==0:
print "graphid : %s\t graphname : %s\t width :\033[32m%s\033[0m \t height :\033[31m%s\033[0m"%(graph['graphid'],graph['name'],graph['width'],graph['height'])
else:
print "graphid : %s\t graphname : %s\t width :\033[32m%s\033[0m \t height :\033[31m%s\033[0m"%(graph['graphid'],graph['name'],graph['width'],graph['height'])
return graph['graphid']
#筛选图查询
def screen_get(self,ScreenName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "screen.get",
"params": {
"output": "extend",
"selectScreenItems": "extend",
"filter": {
"name": ScreenName
}
},
"auth":self.user_login(),
"id":1
})

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 'Error as ', e
else:
response = json.loads(result.read())
result.close()
print "筛选图数量: \033[31m%s\033[0m"%(len(response['result']))
for screen in response['result']:
if len(ScreenName)==0:
print "ScreenID : %s\t ScreenName : %s\t Hsize :\033[32m%s\033[0m \t Vsize :\033[31m%s\033[0m"%(screen['screenid'],screen['name'],screen['hsize'],screen['vsize'])
else:
print "ScreenID : %s\t ScreenName : %s\t Hsize :\033[32m%s\033[0m \t Vsize :\033[31m%s\033[0m"%(screen['screenid'],screen['name'],screen['hsize'],screen['vsize'])
return screen['screenid']
#主机组查询
def hostgroup_get(self, hostgroupName=''):
data = json.dumps({
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": hostgroupName
}
},
"auth":self.user_login(),
"id":1
})

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 "Error as ", e
else:
#print result.read()
response = json.loads(result.read())
result.close()
#print response()
for group in response['result']:
if len(hostgroupName)==0:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
else:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
self.hostgroupID = group['groupid']
return group['groupid']
#模版查询
def template_get(self,templateName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"name":templateName
}
},
"auth":self.user_login(),
"id":1
})

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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
#print response
for template in response['result']:
if len(templateName)==0:
print "template : \033[31m%s\033[0m\t id : %s" % (template['name'], template['templateid'])
else:
self.templateID = response['result'][0]['templateid']
print "Template Name : \033[31m%s\033[0m "%templateName
return response['result'][0]['templateid']
#主机组创建
def hostgroup_create(self,hostgroupName):
if self.hostgroup_get(hostgroupName):
print "hostgroup \033[42m%s\033[0m is exist !"%hostgroupName
sys.exit(1)
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": hostgroupName
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加主机组:%s\033[0m hostgroupID : %s"%(hostgroupName,response['result']['groupids'])
#筛选图添加
def screen_create(self,ScreenName,hsize,vsize):
if self.screen_get(ScreenName):
print "Screen \033[42m%s\033[0m is exist !"%ScreenName
sys.exit(1)
data = json.dumps({
"jsonrpc": "2.0",
"method": "screen.create",
"params": {
"name": ScreenName,
"hsize": hsize,
"vsize": vsize
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加筛选图:%s\033[0m ScreenName : %s"%(ScreenName,response['result']['screenids'])
#筛选图图形添加
def screen_item_create(self,screenid,resourceid,x,y):
if self.screen_item_create(resourceid):
print "resource \033[042m%s\033[0m is exist !"%resourceid
sys.exit(1)
screen_list=[]
for i in screenid.split(','):
var = {}
var['screenid'] = self.screen_get(i)
screen_list.append(var)
data = json.dumps({
"jsonrpc": "2.0",
"method": "screenitem.create",
"params": {
"screenid": screen_list,
"resourceid": resourceid,
"x": x,
"y": y
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加筛选图形:%s\033[0m resourceid : %s"%(resourceid,response['result']['resourceids'])
#主机创建
def host_create(self, hostip, hostgroupName, templateName):
if self.host_get(hostip):
print "\033[041m该主机已经添加!\033[0m"
sys.exit(1)

group_list=[]
template_list=[]
for i in hostgroupName.split(','):
var = {}
var['groupid'] = self.hostgroup_get(i)
group_list.append(var)
for i in templateName.split(','):
var={}
var['templateid']=self.template_get(i)
template_list.append(var)

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": group_list,
"templates": template_list,
},
"auth": self.user_login(),
"id":1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])
#关闭主机
def host_disable(self,hostip):
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": self.host_get(hostip),
"status": 1
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print '----主机现在状态------------'
print self.host_get(hostip)
#删除主机
def host_delete(self,hostid):
hostid_list=[]
#print type(hostid)
for i in hostid.split(','):
var = {}
var['hostid'] = self.host_get(i)
hostid_list.append(var)
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.delete",
"params": hostid_list,
"auth": self.user_login(),
"id": 1
})

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:
print e
else:

result.close()
print "主机 \033[041m %s\033[0m 已经删除 !"%hostid
#删除筛选图
def screen_delete(self,screenid):
screenid_list=[]
for i in screenid.split(','):
var = {}
var['screenid'] = self.screen_get(i)
screenid_list.append(var)
data=json.dumps({
"jsonrpc": "2.0",
"method": "screen.delete",
"params": screenid_list,
"auth": self.user_login(),
"id": 1
})
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:
print e
else:
result.close()
print "筛选图 \033[041m %s\033[0m 已经删除 !"%screenid


if __name__ == "__main__":
zabbix=zabbix_api()
parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')
parser.add_argument('-Z','--graph',nargs='?',dest='listgraph',default='graph',help='查询图形')
parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')
parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')
parser.add_argument('-S','--screen',nargs='?',dest='listscreen',default='screen',help='查询筛选图')
parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')
parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主机,多个主机组或模板使用分号')
parser.add_argument('-B','--create-screenitem',dest='addscreenitem',nargs=4,metavar=('38', '365', '0', '0'),help='添加筛选图图形')
parser.add_argument('-J','--add-screen',nargs=3,dest='addscreen',help='添加筛选图')
parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主机')
parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='删除主机,多个主机之间用分号')
parser.add_argument('-P','--delete-screen',dest='deletescreen',nargs='+',metavar=('38'),help='删除筛选图,多个筛选图之间用分号')
parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
if len(sys.argv)==1:
print parser.print_help()
else:
args=parser.parse_args()

if args.listhost != 'host' :
if args.listhost:
zabbix.host_get(args.listhost)
else:
zabbix.host_get()
if args.listgraph != 'graph':
if args.listgraph:
zabbix.graph_get(args.listgraph)
else:
zabbix.graph_get()
if args.listgroup !='group':
if args.listgroup:
zabbix.hostgroup_get(args.listgroup)
else:
zabbix.hostgroup_get()
if args.listtemp != 'template':
if args.listtemp:
zabbix.template_get(args.listtemp)
else:
zabbix.template_get()
if args.listscreen != 'screen':
if args.listscreen:
zabbix.screen_get(args.listscreen)
else:
zabbix.screen_get()
if args.addgroup:
zabbix.hostgroup_create(args.addgroup[0])
if args.addhost:
zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2])
if args.addscreen:
zabbix.screen_create(args.addscreen[0],args.addscreen[1],args.addscreen[2])
if args.addscreenitem:
zabbix.screen_item_create(args.addscreenitem[0],args.addscreenitem[1],args.addscreenitem[2],args.addscreenitem[3])
if args.disablehost:
zabbix.host_disable(args.disablehost)
if args.deletehost:
zabbix.host_delete(args.deletehost[0])
if args.deletescreen:
zabbix.screen_delete(args.deletescreen[0]) 查看全部
#!/usr/bin/python 
#coding:utf-8


import json
import urllib2
from urllib2 import URLError
import sys,argparse

class zabbix_api:
def __init__(self):
self.url = 'http://192.168.210.13:81/zabbix/api_jsonrpc.php' #修改URL
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
})

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 "\033[041m 用户认证失败,请检查 !\033[0m", e.code
else:
response = json.loads(result.read())
result.close()
#print response['result']
self.authID = response['result']
return self.authID
#主机查询
def host_get(self,hostName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "host.get",
"params": {
"output": "extend",
"filter":{
"host":hostName
}
},
"auth": self.user_login(),
"id": 1
})
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:
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
else:
response = json.loads(result.read())
#print response
result.close()
print "主机数量: \033[31m%s\033[0m"%(len(response['result']))
for host in response['result']:
status={"0":"OK","1":"Disabled"}
available={"0":"Unknown","1":"available","2":"Unavailable"}
#print host
if len(hostName)==0:
print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
else:
print "HostID : %s\t HostName : %s\t Status :\033[32m%s\033[0m \t Available :\033[31m%s\033[0m"%(host['hostid'],host['name'],status[host['status']],available[host['available']])
return host['hostid']
#图形查询
def graph_get(self,hostids,graphname=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "graph.get",
"params": {
"output": "extend",
"hostids": hostids,
"sortfield": "name"
},
"auth": self.user_login(),
"id":1
})
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:
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
else:
response = json.loads(result.read())
result.close()
print "图形数量: \033[31m%s\033[0m"%(len(response['result']))
for graph in response['result']:
if len(graphname)==0:
print "graphid : %s\t graphname : %s\t width :\033[32m%s\033[0m \t height :\033[31m%s\033[0m"%(graph['graphid'],graph['name'],graph['width'],graph['height'])
else:
print "graphid : %s\t graphname : %s\t width :\033[32m%s\033[0m \t height :\033[31m%s\033[0m"%(graph['graphid'],graph['name'],graph['width'],graph['height'])
return graph['graphid']
#筛选图查询
def screen_get(self,ScreenName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "screen.get",
"params": {
"output": "extend",
"selectScreenItems": "extend",
"filter": {
"name": ScreenName
}
},
"auth":self.user_login(),
"id":1
})

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 'Error as ', e
else:
response = json.loads(result.read())
result.close()
print "筛选图数量: \033[31m%s\033[0m"%(len(response['result']))
for screen in response['result']:
if len(ScreenName)==0:
print "ScreenID : %s\t ScreenName : %s\t Hsize :\033[32m%s\033[0m \t Vsize :\033[31m%s\033[0m"%(screen['screenid'],screen['name'],screen['hsize'],screen['vsize'])
else:
print "ScreenID : %s\t ScreenName : %s\t Hsize :\033[32m%s\033[0m \t Vsize :\033[31m%s\033[0m"%(screen['screenid'],screen['name'],screen['hsize'],screen['vsize'])
return screen['screenid']
#主机组查询
def hostgroup_get(self, hostgroupName=''):
data = json.dumps({
"jsonrpc":"2.0",
"method":"hostgroup.get",
"params": {
"output": "extend",
"filter": {
"name": hostgroupName
}
},
"auth":self.user_login(),
"id":1
})

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 "Error as ", e
else:
#print result.read()
response = json.loads(result.read())
result.close()
#print response()
for group in response['result']:
if len(hostgroupName)==0:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
else:
print "hostgroup: \033[31m%s\033[0m \tgroupid : %s" %(group['name'],group['groupid'])
self.hostgroupID = group['groupid']
return group['groupid']
#模版查询
def template_get(self,templateName=''):
data = json.dumps({
"jsonrpc": "2.0",
"method": "template.get",
"params": {
"output": "extend",
"filter": {
"name":templateName
}
},
"auth":self.user_login(),
"id":1
})

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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
#print response
for template in response['result']:
if len(templateName)==0:
print "template : \033[31m%s\033[0m\t id : %s" % (template['name'], template['templateid'])
else:
self.templateID = response['result'][0]['templateid']
print "Template Name : \033[31m%s\033[0m "%templateName
return response['result'][0]['templateid']
#主机组创建
def hostgroup_create(self,hostgroupName):
if self.hostgroup_get(hostgroupName):
print "hostgroup \033[42m%s\033[0m is exist !"%hostgroupName
sys.exit(1)
data = json.dumps({
"jsonrpc": "2.0",
"method": "hostgroup.create",
"params": {
"name": hostgroupName
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加主机组:%s\033[0m hostgroupID : %s"%(hostgroupName,response['result']['groupids'])
#筛选图添加
def screen_create(self,ScreenName,hsize,vsize):
if self.screen_get(ScreenName):
print "Screen \033[42m%s\033[0m is exist !"%ScreenName
sys.exit(1)
data = json.dumps({
"jsonrpc": "2.0",
"method": "screen.create",
"params": {
"name": ScreenName,
"hsize": hsize,
"vsize": vsize
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加筛选图:%s\033[0m ScreenName : %s"%(ScreenName,response['result']['screenids'])
#筛选图图形添加
def screen_item_create(self,screenid,resourceid,x,y):
if self.screen_item_create(resourceid):
print "resource \033[042m%s\033[0m is exist !"%resourceid
sys.exit(1)
screen_list=[]
for i in screenid.split(','):
var = {}
var['screenid'] = self.screen_get(i)
screen_list.append(var)
data = json.dumps({
"jsonrpc": "2.0",
"method": "screenitem.create",
"params": {
"screenid": screen_list,
"resourceid": resourceid,
"x": x,
"y": y
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "\033[042m 添加筛选图形:%s\033[0m resourceid : %s"%(resourceid,response['result']['resourceids'])
#主机创建
def host_create(self, hostip, hostgroupName, templateName):
if self.host_get(hostip):
print "\033[041m该主机已经添加!\033[0m"
sys.exit(1)

group_list=[]
template_list=[]
for i in hostgroupName.split(','):
var = {}
var['groupid'] = self.hostgroup_get(i)
group_list.append(var)
for i in templateName.split(','):
var={}
var['templateid']=self.template_get(i)
template_list.append(var)

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": group_list,
"templates": template_list,
},
"auth": self.user_login(),
"id":1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])
#关闭主机
def host_disable(self,hostip):
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.update",
"params": {
"hostid": self.host_get(hostip),
"status": 1
},
"auth": self.user_login(),
"id": 1
})
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 "Error as ", e
else:
response = json.loads(result.read())
result.close()
print '----主机现在状态------------'
print self.host_get(hostip)
#删除主机
def host_delete(self,hostid):
hostid_list=[]
#print type(hostid)
for i in hostid.split(','):
var = {}
var['hostid'] = self.host_get(i)
hostid_list.append(var)
data=json.dumps({
"jsonrpc": "2.0",
"method": "host.delete",
"params": hostid_list,
"auth": self.user_login(),
"id": 1
})

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:
print e
else:

result.close()
print "主机 \033[041m %s\033[0m 已经删除 !"%hostid
#删除筛选图
def screen_delete(self,screenid):
screenid_list=[]
for i in screenid.split(','):
var = {}
var['screenid'] = self.screen_get(i)
screenid_list.append(var)
data=json.dumps({
"jsonrpc": "2.0",
"method": "screen.delete",
"params": screenid_list,
"auth": self.user_login(),
"id": 1
})
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:
print e
else:
result.close()
print "筛选图 \033[041m %s\033[0m 已经删除 !"%screenid


if __name__ == "__main__":
zabbix=zabbix_api()
parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')
parser.add_argument('-Z','--graph',nargs='?',dest='listgraph',default='graph',help='查询图形')
parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')
parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')
parser.add_argument('-S','--screen',nargs='?',dest='listscreen',default='screen',help='查询筛选图')
parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')
parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主机,多个主机组或模板使用分号')
parser.add_argument('-B','--create-screenitem',dest='addscreenitem',nargs=4,metavar=('38', '365', '0', '0'),help='添加筛选图图形')
parser.add_argument('-J','--add-screen',nargs=3,dest='addscreen',help='添加筛选图')
parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主机')
parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='删除主机,多个主机之间用分号')
parser.add_argument('-P','--delete-screen',dest='deletescreen',nargs='+',metavar=('38'),help='删除筛选图,多个筛选图之间用分号')
parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
if len(sys.argv)==1:
print parser.print_help()
else:
args=parser.parse_args()

if args.listhost != 'host' :
if args.listhost:
zabbix.host_get(args.listhost)
else:
zabbix.host_get()
if args.listgraph != 'graph':
if args.listgraph:
zabbix.graph_get(args.listgraph)
else:
zabbix.graph_get()
if args.listgroup !='group':
if args.listgroup:
zabbix.hostgroup_get(args.listgroup)
else:
zabbix.hostgroup_get()
if args.listtemp != 'template':
if args.listtemp:
zabbix.template_get(args.listtemp)
else:
zabbix.template_get()
if args.listscreen != 'screen':
if args.listscreen:
zabbix.screen_get(args.listscreen)
else:
zabbix.screen_get()
if args.addgroup:
zabbix.hostgroup_create(args.addgroup[0])
if args.addhost:
zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2])
if args.addscreen:
zabbix.screen_create(args.addscreen[0],args.addscreen[1],args.addscreen[2])
if args.addscreenitem:
zabbix.screen_item_create(args.addscreenitem[0],args.addscreenitem[1],args.addscreenitem[2],args.addscreenitem[3])
if args.disablehost:
zabbix.host_disable(args.disablehost)
if args.deletehost:
zabbix.host_delete(args.deletehost[0])
if args.deletescreen:
zabbix.screen_delete(args.deletescreen[0])

Zabbix监控之Mysql

运维技术Ansible 发表了文章 • 3 个评论 • 996 次浏览 • 2015-08-25 00:28 • 来自相关话题

      使用go语言写了一个采集mysql性能的小程序,通过SDK连接mysql数据库,采集数据库性能指标,同时采集远程数据库的性能,大家可试用一下,欢迎提出修改意见和建议

被监控端设置

监控下载:
   Linux:
                mymon_x86.tar.gz
                mymon_x64.tar.gz
   Windows:
                mymon_windows_amd64.zip
 
Windows:
      下载解压后放在c盘,修改agentd.conf文件,执行脚本路径为:c:\mymon\mymon.exe


      重启agentd即可

Linux:
      修改zabbix agentd配置文件(具体位置根据自身情况设置),添加keyvi /usr/local/zabbix/etc/zabbix_agentd.conf      添加如下:




      添加好之后执行mkdir -p /usr/local/zabbix/bin/mysql/
cd /usr/local/zabbix/bin/mysql/
wget http://dl.cactifans.org/tools/mymon_x64.tar.gz
tar zxvf mymon_x64.tar.gz
chmod a+x mymon      同时编辑cfg.json配置文件,设置要监控数据库的连接参数vi /usr/local/zabbix/bin/mysql/cfg.json      文件内容如下{
"mysql": {
"username": "root",
"password": "123456",
"host": "localhost",
"port": 3306
},
"sever": {
"log": "/tmp/mon.log"
}
}      登录数据库的账号,密码等信息,log项目不用设置,默认即可
      设置好之后重启zabixx agentservice zabbix-agent restart

zabbix服务端设置

      测试agent是否工作正常/usr/local/bin/zabbix_get -s 192.168.7.186 -k mysql.status[GlobalStatus,Uptime]      如果有一下回显,表示工作正常[root@vm153 ~]# /usr/local/bin/zabbix_get -s 192.168.7.186 -k mysql.status[GlobalStatus,Uptime]
12364726
[root@vm153 ~]#      导入模版:zabbix_mysql_templates.xml
      并关联到主机
      效果:




      参数:




      PS:可自行添加对应key可监控项目,模版自带了几种,脚本包括800多项目



具体更具key定义,括号内第一项为key类型,分GlobalStatus和GlobalVariables二种,后面的数值为在mysql里执行“SHOW /!50001 GLOBAL / STATUS”和“SHOW /!50001 GLOBAL / VARIABLES”,对应的key,注意有些数值为固定数值,有些key的类型为每秒速差,自行添加.原文地址 查看全部
      使用go语言写了一个采集mysql性能的小程序,通过SDK连接mysql数据库,采集数据库性能指标,同时采集远程数据库的性能,大家可试用一下,欢迎提出修改意见和建议


被监控端设置


监控下载:
   Linux:
                mymon_x86.tar.gz
                mymon_x64.tar.gz
   Windows:
                mymon_windows_amd64.zip
 
Windows:
      下载解压后放在c盘,修改agentd.conf文件,执行脚本路径为:
c:\mymon\mymon.exe


      重启agentd即可

Linux:
      修改zabbix agentd配置文件(具体位置根据自身情况设置),添加key
vi /usr/local/zabbix/etc/zabbix_agentd.conf
      添加如下:
zmy4.png

      添加好之后执行
mkdir -p /usr/local/zabbix/bin/mysql/
cd /usr/local/zabbix/bin/mysql/
wget http://dl.cactifans.org/tools/mymon_x64.tar.gz
tar zxvf mymon_x64.tar.gz
chmod a+x mymon
      同时编辑cfg.json配置文件,设置要监控数据库的连接参数
vi /usr/local/zabbix/bin/mysql/cfg.json
      文件内容如下
{
"mysql": {
"username": "root",
"password": "123456",
"host": "localhost",
"port": 3306
},
"sever": {
"log": "/tmp/mon.log"
}
}
      登录数据库的账号,密码等信息,log项目不用设置,默认即可
      设置好之后重启zabixx agent
service zabbix-agent restart


zabbix服务端设置


      测试agent是否工作正常
/usr/local/bin/zabbix_get -s 192.168.7.186 -k mysql.status[GlobalStatus,Uptime]
      如果有一下回显,表示工作正常
[root@vm153 ~]#  /usr/local/bin/zabbix_get -s 192.168.7.186 -k mysql.status[GlobalStatus,Uptime]
12364726
[root@vm153 ~]#
      导入模版:zabbix_mysql_templates.xml
      并关联到主机
      效果:
zmy1.png

      参数:
zmy2.png

      PS:可自行添加对应key可监控项目,模版自带了几种,脚本包括800多项目
zmy3.png
具体更具key定义,括号内第一项为key类型,分GlobalStatus和GlobalVariables二种,后面的数值为在mysql里执行“SHOW /!50001 GLOBAL / STATUS”和“SHOW /!50001 GLOBAL / VARIABLES”,对应的key,注意有些数值为固定数值,有些key的类型为每秒速差,自行添加.
原文地址
zabbix(音同 zæbix)是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案。