Python3入門練手嘗試篇php
API參考: zabbix API 4.0版本:https://www.zabbix.com/documentation/4.0/zh/manual/apipython
#!/bin/python3 import xlrd,os,json,requests,sys #參考zabbix API 4.0版本:https://www.zabbix.com/documentation/4.0/zh/manual/api class zabbixtools: url = 'http://47.98.222.237/zabbix/api_jsonrpc.php' head = {'Content-Type':'application/jsonrequest'} #獲取認證id def user_login(self): data = { "jsonrpc": "2.0", "method": "user.login", "params": { "user": "Admin", "password": "zabbix" }, "id": 1, "auth": None } try: request_auth = requests.post(self.url,headers=self.head,data=json.dumps(data)) request_auth_json = request_auth.json() auth = request_auth_json['result'] except Exception as e: return '0' return auth #獲取監控主機列表 def get_hosts(self): data={ "jsonrpc": "2.0", "method": "host.get", "params": { "output": ["hostid","host"],"selectInterfaces": ["interfaceid","ip"]}, "id": 2, "auth": self.user_login() } request_host= requests.post(self.url,headers=self.head,data=json.dumps(data)) request_host_json = request_host.json() return request_host_json #建立主機 def create_hosts(self): file=sys.argv[2] with xlrd.open_workbook(file) as fb: sheet=fb.sheet_by_name('create') print('表名稱:%s,錶行數:%s,表列數:%s'% (sheet.name,sheet.nrows,sheet.ncols)) for i in range(1,sheet.nrows): hostname=sheet.row_values(i)[0] hostip=sheet.row_values(i)[1] groupid=int(sheet.row_values(i)[2]) templateid=int(sheet.row_values(i)[3]) #################################### data={ "jsonrpc": "2.0", "method": "host.create","params": {"host": hostname,"interfaces": [{"type": 1,"main": 1,"useip": 1,"ip": hostip,"dns":"","port":"10050"}], "groups": [{"groupid":groupid }], "templates": [{"templateid": templateid }], "inventory_mode": 0, "inventory": {"macaddress_a": "01234","macaddress_b": "56768"}}, "auth": self.user_login(), "id": 1 } request_create=requests.post(self.url,headers=self.head,data=json.dumps(data)) request_create_json=request_create.json() #刪除主機 def delete_hosts(self): file=sys.argv[2] with xlrd.open_workbook(file) as fb: sheet=fb.sheet_by_name('delete') print('表名稱:%s,錶行數:%s,表列數:%s'% (sheet.name,sheet.nrows,sheet.ncols)) delhostname=[] for i in range(1,sheet.nrows): hostname=sheet.row_values(i)[0] delhostname.append(hostname) print('獲取刪除主機名稱列表:%s'%(delhostname)) print('----------------------------------------') delhostnameid=[] for i in delhostname: data={ "jsonrpc": "2.0", "method": "host.get", "params": {"output": ["hostid"],"filter": {"host":i}}, "auth":self.user_login(), "id": 1 } try: request_delete=requests.post(self.url,headers=self.head,data=json.dumps(data)) request_delete_json=request_delete.json() request_delete_hostid=str(request_delete_json['result'][0]['hostid']) delhostnameid.append(request_delete_hostid) except Exception as e: print('沒法獲取主機%s:ID信息,請在web頁面確認該主機是否存在.'%(i)) continue request_delete_hostid=str(request_delete_json['result'][0]['hostid']) delhostnameid.append(request_delete_hostid) print('獲取刪除主機id列表:%s'%(delhostnameid)) if len(delhostnameid)== 0: print('沒有獲取任何相關主機hostsid信息,請確檢查excel文件信息的準確性.') return '0' print('-------------------------------------') del_id={ "jsonrpc": "2.0", "method": "host.delete", "params": delhostnameid, "auth": self.user_login(), "id": 1 } request_del=requests.post(self.url,headers=self.head,data=json.dumps(del_id)) request_del_json=request_del.json() print('刪除主機id列表:%s'%(request_del_json)) #導入模板 def zbx_export(self): fb=open(sys.argv[2],encoding='utf8').read() data_export={ "jsonrpc": "2.0", "method": "configuration.import", "params": { "format": "xml", "rules": { "applications":{"createMissing":True,"deleteMissing":True}, "valueMaps":{"createMissing":True,"updateExisting":True}, "groups":{"createMissing":True}, "graphs":{"createMissing":True}, "screens":{"createMissing":True}, "templateScreens":{"createMissing":True}, "triggers":{"createMissing":True,"updateExisting":True}, "templates":{"createMissing":True}, "items":{"createMissing":True, "updateExisting":True,"deleteMissing":True} }, "source":fb}, "auth": self.user_login(), "id": 1 } request_export=requests.post(self.url,headers=self.head,data=json.dumps(data_export)) request_export_json=request_export.json() return request_export_json def main(): if len(sys.argv) == 3: if (sys.argv[1] == 'delete' or sys.argv[1] == 'create' or sys.argv[1] == 'export') and os.path.isfile(sys.argv[2]): auths = zabbixtools() if auths == 0: print('獲取認證令牌失敗..請檢查提交數據的準確性') return '0' #獲取認證令牌 print('-------------') print('獲取用戶認證令牌auth:%s'% auths.user_login()) if sys.argv[1] == 'create': #添加監控主機 print('-------------') print('添加主機log:%s'% auths.create_hosts()) elif sys.argv[1] == 'delete': #刪除主機 print('-------------') print('刪除主機log:%s'% auths.delete_hosts()) if sys.argv[1] == 'export': #導入模板 print('-------------') print('導入模板log:%s'% auths.zbx_export()) else: pass #獲取線上監控主機列表 print('--------------') hostlist=auths.get_hosts()['result'] for i in hostlist: i['ip']=i['interfaces'][0]['ip'] del i['interfaces'] print('目前監控主機列表:%s'%(i)) else: print('執行失敗.Usage: /bin/python3 %s delete/create/export target_file'%(sys.argv[0])) else: print('執行失敗.Usage: /bin/python3 %s delete/create/export target_file'%(sys.argv[0])) return '0' if __name__ == '__main__': main()
1.用法:批量添加主機:先準備好excel表格,內容以下。注:模板id和主機組id能夠經過web頁面查看到web
執行腳本添加主機:python3 zabbix_delete_create_export.py create server.xlsxjson
已經添加成功,查看web頁面效果以下:api
2.批量刪除主機操做:建立delete表 寫入須要刪除主機的列表。(故意寫了幾條錯誤的數據test-no01-03)app
執行腳本:python3 zabbix_delete_create_export.py delete server.xlsxpost
查看web界面,已經刪除成功測試
3.導入模板,先經過web頁面將模板導出爲xml文件。刪除以前已經建立好的測試模板 執行腳本:url
查看web頁面,模板添加成功.
spa