#!/usr/bin/env python
#-*-coding:utf-8-*-
# Author : SammyTan
# Email : [email protected]
# Last modified : 2016-04-25 16:24
# Filename : zabbix_screens_automation.py
# Description : Auto add delete and update zabbix screens
import os
import urllib2
import json
import argparse
url=‘http://10.1.180.166/zabbix/api_jsonrpc.php‘
username=‘Admin‘
password=‘zabbix‘
def authenticate(url, username, password):
values ={‘jsonrpc‘:‘2.0‘,
‘method‘:‘user.login‘,
‘params‘:{
‘user‘: username,
‘password‘: password
},
‘id‘:‘0‘
}
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
output = json.loads(response.read())
try:
message = output[‘result‘]
except:
message = output[‘error‘][‘data‘]
print message
quit()
return output[‘result‘]
def getHost():
values ={
"jsonrpc":"2.0",
"method":"host.get",
"params":{
"output":[
"host"
]
},
"id":1,
"auth":"2e92f0d30d878442533da77c15ae7cdd"
}
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
output = json.loads(response.read())
return output
def getGraph(hostid):
values ={
"jsonrpc":"2.0",
"method":"graph.get",
"params":{
"output":[
"graphid"
],
"hostids": hostid
},
"auth":"2e92f0d30d878442533da77c15ae7cdd",
"id":1
}
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
#print json.dumps(output)
return output
def getScreentimeid(screenid):
values ={
"jsonrpc":"2.0",
"method":"screen.get",
"params":{
"output":"extend",
"selectScreenItems":[
"screenitemid"
],
"screenids": screenid
},
"auth":"2e92f0d30d878442533da77c15ae7cdd",
"id":1
}
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
#print json.dumps(output)
return output
def getScreen():
values ={
"jsonrpc":"2.0",
"method":"screen.get",
"params":{
"output":[
"name",
"screenid"
]
},
"auth":"2e92f0d30d878442533da77c15ae7cdd",
"id":1
}
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
return output
def screenDelete(screenid):
values ={
"jsonrpc":"2.0",
"method":"screen.delete",
"params":[
screenid
],
"auth":"2e92f0d30d878442533da77c15ae7cdd",
"id":1
}
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
return output
#os.system(‘python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 $each_host $each_host‘)
def main():
host_output=getHost()
host_list =[]
# add host to host list
for host in host_output[‘result‘]:
#print host
host_list.append(host[‘host‘])
screenname_list =[]
screen_output=getScreen()
# add screen name to saceen list
for name in screen_output[‘result‘]:
screenname_list.append(name[‘name‘])
#Check host , if this host not have screen ,the self create screen .
for host in host_list:
if host notin screenname_list:# if this host not in screen list , the creend the host screen
os.system(‘python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 %s %s‘%(host,host))
#### 该脚本在下面
print‘Create %s host screen‘%(host)
#Delete invalid screen
for name in screenname_list:
for sid in screen_output[‘result‘]:
if name in sid[‘name‘]:
screenid = sid[‘screenid‘]
if name notin host_list:
delete_result = screenDelete(screenid)
print‘Delete %s host screen‘%(name)
#Check host graphs number, if graphs number grant than exsit screens graphs , the delete it after recreated.
for screenid in screen_output[‘result‘]:
#print screenid
screenGraphs = getScreentimeid(screenid[‘screenid‘])
for sid in screenGraphs[‘result‘]:
for host in host_output[‘result‘]:
if host[‘host‘]in screenid[‘name‘]:
hostid = host[‘hostid‘]
hostname = host[‘host‘]
hostGraphs = getGraph(hostid)
#print host[‘host‘],len(hostGraphs[‘result‘]),len(sid[‘screenitems‘])
if len(hostGraphs[‘result‘])> len(sid[‘screenitems‘]):
delete_result = screenDelete(host[‘hostid‘])
os.system(‘python /root/Scripts_Tmemplate/Auto_add_screens.py -c 2 %s %s‘%(hostname,hostname))
print‘Update %s host screen‘%(hostname)
else:
print‘All screen already sync .‘
if __name__ ==‘__main__‘:
main()
#!/usr/bin/env python
import urllib2
import json
import argparse
def authenticate(url, username, password):
values ={‘jsonrpc‘:‘2.0‘,
‘method‘:‘user.login‘,
‘params‘:{
‘user‘: username,
‘password‘: password
},
‘id‘:‘0‘
}
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
output = json.loads(response.read())
try:
message = output[‘result‘]
except:
message = output[‘error‘][‘data‘]
print message
quit()
return output[‘result‘]
def getGraph(hostname, url, auth, graphtype, dynamic, columns):
if(graphtype ==0):
selecttype =[‘graphid‘]
select =‘selectGraphs‘
if(graphtype ==1):
selecttype =[‘itemid‘,‘value_type‘]
select =‘selectItems‘
values ={‘jsonrpc‘:‘2.0‘,
‘method‘:‘host.get‘,
‘params‘:{
select: selecttype,
‘output‘:[‘hostid‘,‘host‘],
‘searchByAny‘:1,
‘filter‘:{
‘host‘: hostname
}
},
‘auth‘: auth,
‘id‘:‘2‘
}
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
# print json.dumps(output)
graphs =[]
if(graphtype ==0):
for i in output[‘result‘][0][‘graphs‘]:
graphs.append(i[‘graphid‘])
if(graphtype ==1):
for i in output[‘result‘][0][‘items‘]:
if int(i[‘value_type‘])in(0,3):
graphs.append(i[‘itemid‘])
graph_list =[]
x =0
y =0
for graph in graphs:
graph_list.append({
"resourcetype": graphtype,
"resourceid": graph,
"width":"500",
"height":"200",
"x": str(x),
"y": str(y),
"colspan":"1",
"rowspan":"1",
"elements":"0",
"valign":"0",
"halign":"0",
"style":"0",
"url":"",
"dynamic": str(dynamic)
})
x +=1
if x == columns:
x =0
y +=1
return graph_list
def screenCreate(url, auth, screen_name, graphids, columns):
# print graphids
if len(graphids)% columns ==0:
vsize = len(graphids)/ columns
else:
vsize =(len(graphids)/ columns)+1
values ={"jsonrpc":"2.0",
"method":"screen.create",
"params":[{
"name": screen_name,
"hsize": columns,
"vsize": vsize,
"screenitems":[]
}],
"auth": auth,
"id":2
}
for i in graphids:
values[‘params‘][0][‘screenitems‘].append(i)
data = json.dumps(values)
req = urllib2.Request(url, data,{‘Content-Type‘:‘application/json-rpc‘})
response = urllib2.urlopen(req, data)
host_get = response.read()
output = json.loads(host_get)
try:
message = output[‘result‘]
except:
message = output[‘error‘][‘data‘]
print json.dumps(message)
def main():
url =‘http://10.1.180.166/zabbix/api_jsonrpc.php‘
username ="Admin"
password ="zabbix"
parser = argparse.ArgumentParser(description=‘Create Zabbix screen from all of a host Items or Graphs.‘)
parser.add_argument(‘hostname‘, metavar=‘H‘, type=str,
help=‘Zabbix Host to create screen from‘)
parser.add_argument(‘screenname‘, metavar=‘N‘, type=str,
help=‘Screen name in Zabbix. Put quotes around it if you want spaces in the name.‘)
parser.add_argument(‘-c‘, dest=‘columns‘, type=int, default=2,
help=‘number of columns in the screen (default: 2)‘)
parser.add_argument(‘-d‘, dest=‘dynamic‘, action=‘store_true‘,
help=‘enable for dynamic screen items (default: disabled)‘)
parser.add_argument(‘-t‘, dest=‘screentype‘, action=‘store_true‘,
help=‘set to 1 if you want item simple graphs created (default: 0, regular graphs)‘)
args = parser.parse_args()
hostname = args.hostname
screen_name = args.screenname
columns = args.columns
dynamic =(1if args.dynamic else0)
screentype =(1if args.screentype else0)
auth = authenticate(url, username, password)
graphids = getGraph(hostname, url, auth, screentype, dynamic, columns)
print"Screen Name: "+ screen_name
print"Total Number of Graphs: "+ str(len(graphids))
screenCreate(url, auth, screen_name, graphids, columns)
if __name__ ==‘__main__‘:
main()
时间: 2024-10-06 00:23:20