zabbix批量清理模板,添加新模板
程序员文章站
2022-06-09 21:25:58
1 import requests 2 import json 3 import sys 4 5 6 7 def get_token(): 8 data = { 9 "jsonrpc": "2.0", 10 "method": "user.login", 11 "params": { 12 ... ......
1 import requests 2 import json 3 import sys 4 5 6 7 def get_token(): 8 data = { 9 "jsonrpc": "2.0", 10 "method": "user.login", 11 "params": { 12 "user": username, 13 "password": password 14 }, 15 "id": 0 16 } 17 r = requests.get(zaurl, headers=header, data=json.dumps(data)) 18 auth = json.loads(r.text) 19 return auth["result"] 20 21 22 #指定模板,获取主机信息 23 def template_hostget(token): 24 data = { 25 "jsonrpc": "2.0", 26 "method": "template.get", 27 "params": { 28 "output": ['host', 'templateid'], 29 "templateids": ['10001'], 30 "selecthosts": [ # 返回链接到模板的主机 31 "hostid", 32 "host", 33 ], 34 }, 35 "auth": token, 36 "id": 1 37 } 38 39 request = requests.post(zaurl, data=json.dumps(data), headers=header) 40 dict = json.loads(request.content) 41 return (dict['result'][0]['hosts']) 42 43 #获取连接的模板信息 44 def hostget(token, hostid): 45 data = { 46 "jsonrpc": "2.0", 47 "method": "host.get", 48 "params": { 49 "output": ["hostid","host"], 50 "selectparenttemplates": [ 51 "templateid", 52 "name" 53 ], 54 "hostids": hostid 55 }, 56 "auth": token, 57 "id": 1 58 } 59 60 request = requests.post(zaurl, data=json.dumps(data), headers=header) 61 dict = json.loads(request.content) 62 # print (dict) 63 print (dict['result'][0]['hostid'],dict['result'][0]['host'],dict['result'][0]['parenttemplates']) 64 65 66 def massupdate_templates_clear_hosts(token, hostid): 67 data = { 68 "jsonrpc": "2.0", 69 "method": "host.update", 70 "params": { 71 "hostid": hostid, 72 "templates_clear": ['10001'] 73 }, 74 "auth": token, 75 "id": 1 76 } 77 request = requests.post(zaurl, data=json.dumps(data), headers=header) 78 print(request.content) 79 80 def add_template(token, templateid, hostid): 81 data = { 82 "jsonrpc": "2.0", 83 "method": "template.massadd", 84 "params": { 85 "templates": [ 86 { 87 "templateid": templateid 88 }, 89 ], 90 "hosts": [ 91 { 92 "hostid": hostid 93 } 94 ] 95 }, 96 "auth": token, 97 "id": 2 98 } 99 request = requests.post(zaurl, data=json.dumps(data), headers=header) 100 print(request.content) 101 102 if __name__ == "__main__": 103 #修改输入参数 104 hostfile = "主机ip.txt" 105 zaurl = "http://x.x.x.x/zabbix/api_jsonrpc.php" 106 header = {"content-type": "application/json"} 107 username = "xx" 108 password = "xx" 109 token = get_token() 110 #获取主机和模板 111 # hostinfo = template_hostget(token) 112 # for i in hostinfo: 113 # hostget(token, i['hostid']) 114 115 #因监控机器数量太多,一次性全部修改会对zabbix数据库造成比较大的压力,所以分批修改 116 hostids = [获取到主机在zabbix里面的hostid] 117 for id in hostids: 118 # hostget(token,'15097') 119 massupdate_templates_clear_hosts(token, id) 120 add_template(token, "10146", id) 121 122
上一篇: Elixir 分布式平台