python batch adds zabbix Screens's two script shares
- 2020-05-19 05:12:12
- OfStack
preface
When I first set up the company's monitoring system, I was most troubled by the need to add the same graphics of the same project team to one Screens. Since I could only add one by one, it was time-consuming and time-consuming.
Here are two scripts to solve this headache.
1. Add all graphics from a single host to 1 Screens
Method of use
# To change the main() In the function url , username , password
# parameter 1 : the host name
# parameter 2 : filter graph name
python zabbix_screen_host.py 'zabbixserver' 'zabbixserver'
zabbix_screen_host.py script content
#!/usr/bin/env python
#zabbix_screen_host.py
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": "100",
"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://zabbixip/zabbix/api_jsonrpc.php'
username = "***"
password = "***"
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=3,
help='number of columns in the screen (default: 3)')
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 = (1 if args.dynamic else 0)
screentype = (1 if args.screentype else 0)
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()
2. Add the same 1 graph of the same group of hosts to 1 Screens
Method of use
# To change the main() In the function url , username , password
#-g : the name of the group
#-G : graphic name
#-n Screening: ( screen Figure name)
#-c : 1 How many graphs does a row have
python zabbix_screen_group.py -g 'zabbix' -G 'icmp-ping' -n 'zabbix-icmp-ping' -c 2
zabbix_screen_group.py script content
#!/usr/bin/env python
import urllib2
import sys
import json
import argparse
# Defined by HTTP Access to API Address of the function, after each request API This function is called by each of the following methods
def requestJson(url,values):
data = json.dumps(values)
req = urllib2.Request(url, data, {'Content-Type': 'application/json-rpc'})
response = urllib2.urlopen(req, data)
output = json.loads(response.read())
# print output
try:
message = output['result']
except:
message = output['error']['data']
print message
quit()
return output['result']
#API Interface authentication function, login success will return 1 a Token
def authenticate(url, username, password):
values = {'jsonrpc': '2.0',
'method': 'user.login',
'params': {
'user': username,
'password': password
},
'id': '0'
}
idvalue = requestJson(url,values)
return idvalue
# Define the host group name to get each hostid The function of
def getHosts(groupname,url,auth):
host_list = []
values = {'jsonrpc': '2.0',
'method': 'hostgroup.get',
'params': {
'output': 'extend',
'filter': {
'name': groupname
},
'selectHosts' : ['hostid','host'],
},
'auth': auth,
'id': '2'
}
output = requestJson(url,values)
for host in output[0]['hosts']:
host_list.append(host['hostid'])
return host_list
# Define access graphid The function of
def getGraphs(host_list,name_list, url, auth, columns, graphtype=0 ,dynamic=0):
if (graphtype == 0):
selecttype = ['graphid']
select = 'selectGraphs'
if (graphtype == 1):
selecttype = ['itemid', 'value_type']
select = 'selectItems'
values=({'jsonrpc' : '2.0',
'method' : 'graph.get',
'params' : {
'output' : ['graphid','name'],
select : [selecttype,'name'],
'hostids' : host_list,
'sortfield' : 'name',
'filter' : {
'name' : name_list,
},
},
'auth' : auth,
'id' : 3
})
output = requestJson(url,values)
bb = sorted(output,key = lambda x:x['graphid'])
graphs = []
if (graphtype == 0):
for i in bb:
print i
graphs.append(i['graphid'])
if (graphtype == 1):
for i in bb:
if int(i['value_type']) in (0, 3):
graphs.append(i['itemid'])
graph_list = []
x = 0
y = 0
for graph in graphs:
print "x is " + str(x)
print "y is " + str(y)
graph_list.append({
"resourcetype": graphtype,
"resourceid": graph,
"width": "500",
"height": "100",
"x": str(x),
"y": str(y),
"colspan": "1",
"rowspan": "1",
"elements": "0",
"valign": "0",
"halign": "0",
"style": "0",
"url": "",
"dynamic": str(dynamic)
})
x += 1
# print type(x)
# print type(columns)
if x == int(columns):
x = 0
y += 1
# print graph_list
return graph_list
# Definition to create screen The function of
def screenCreate(url, auth, screen_name, graphids, columns):
columns = int(columns)
if len(graphids) % columns == 0:
vsize = len(graphids) / columns
else:
vsize = (len(graphids) / columns) + 1
# Use the first screen.get Judge a given screen name If there is a
values0 = {
"jsonrpc" : "2.0",
"method" : "screen.get",
"params" : {
"output" : "extend",
"filter" : {
"name" : screen_name,
}
},
"auth" : auth,
"id" : 2
}
values = {
"jsonrpc": "2.0",
"method": "screen.create",
"params": {
"name": screen_name,
"hsize": columns,
"vsize": vsize,
"screenitems": []
},
"auth": auth,
"id": 2
}
output0 = requestJson(url,values0)
print output0
# If given screen name Nonexistence is created directly screen
if output0 == []:
print "The Given Screen Name Not Exists"
print "Creating Screen %s" %screen_name
for i in graphids:
values['params']['screenitems'].append(i)
output = requestJson(url,values)
else:
# If given screen name Existing, created directly screen No.
# Either use it first screen.delete The original screen Delete it, and then create it,
# Or use it directly screen.update Update the old one screen .
# use screen.delete It will generate new screenid,
# use screen.update A reasonable 1 Points.
print "The Given Screen Name Already Exists"
update_screenid=output0[0]["screenid"]
print update_screenid
print "Updating Screen Name %s Screen ID %s" %(screen_name,update_screenid)
values1 = {
"jsonrpc" : "2.0",
"method" : "screen.update",
"params" : {
"screenid" : update_screenid,
"screenitems": []
},
"auth" : auth,
"id" : 2
}
output1 = requestJson(url,values1)
print output1
print "Updating Screen Name %s" %screen_name
for i in graphids:
values1['params']['screenitems'].append(i)
output = requestJson(url,values1)
def main():
url = 'http://zabbixip/zabbix/api_jsonrpc.php'
username = '****'
password = '****'
auth = authenticate(url, username, password)
host_list = getHosts(groupname,url,auth)
print host_list
graph_ids = getGraphs(host_list,graphname, url, auth, columns)
screenCreate(url, auth, screenname, graph_ids, columns)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create Zabbix screen from all of a host Items or Graphs.')
parser.add_argument('-G', dest='graphname', nargs='+',metavar=('grah name'),
help='Zabbix Host Graph to create screen from')
parser.add_argument('-H', dest='hostname', nargs='+',metavar=('10.19.111.145'),
help='Zabbix Host to create screen from')
parser.add_argument('-g', dest='groupname', nargs='+',metavar=('linux server'),
help='Zabbix Group to create screen from')
parser.add_argument('-n', dest='screenname', 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,
help='number of columns in the screen')
args = parser.parse_args()
print args
hostname = args.hostname
groupname = args.groupname
screenname = args.screenname
columns = args.columns
graphname = args.graphname
if columns is None:
columns = len(graphname)
# print columns
main()
conclusion
The above is the whole content of this article, I hope the content of this article can bring 1 definite help to your study or work, if you have any questions, you can leave a message to communicate.