環境:python3.6.1 ,pip 9.0.1php
1,經過itchat,實現微信的掃碼登陸,和關鍵定識別python
#coding=utf-8 import urllib.request, urllib.error, urllib.parse import sys import json import argparse from login import * from function import * ######################################################################## import itchat import time import re import requests import threading import shutil import os ''' reload(sys) sys.setdefaultencoding('utf-8') ''' self_name='PH' @itchat.msg_register(itchat.content.TEXT) def cmd(revmsg): msg = revmsg['Text'] if msg == "註銷登陸": quit() print("已註銷") # elif msg == "檢索事件": # getevents() elif str.isdigit("".join(re.findall(r'查詢事件(\d+)',msg))): print(msg) eventid = "".join(re.findall(r'查詢事件(\d+)',msg)) print(eventid) itchat.send('識別到事件id,開始查詢事件'+eventid,toUserName = revmsg['FromUserName']) getevent(eventid,revmsg['FromUserName']) elif str.isdigit("".join(re.findall(r'確認事件(\d+)',msg))): eventid = "".join(re.findall(r'確認事件(\d+)',msg)) #messages = "".join(re.findall(r'確認消息<(.+)>',msg)) #有確認消息,不關閉問題 if "".join(re.findall(r'(確認消息)<.+>',msg)) == "確認消息" and "".join(re.findall(r'【關閉】',msg)) == "": messages = "".join(re.findall(r'確認消息<(.+)>',msg)) itchat.send("識別到事件id,開始確認事件"+eventid+",確認消息爲:"+messages,toUserName = revmsg['FromUserName']) ackevent(eventid,revmsg['FromUserName'],messages) #無確認消息,關閉問題 elif "".join(re.findall(r'(確認消息)<.+>',msg)) == "" and "".join(re.findall(r'【關閉】',msg)) == "【關閉】": itchat.send("識別到事件id,開始確認事件"+eventid+",無確認消息。關閉問題。",toUserName = revmsg['FromUserName']) ackevent(eventid,revmsg['FromUserName'],action=1) #有確認消息,關閉問題 elif "".join(re.findall(r'(確認消息)<.+>',msg)) == "確認消息" and "".join(re.findall(r'【關閉】',msg)) == "【關閉】": messages = "".join(re.findall(r'確認消息<(.+)>',msg)) itchat.send("識別到事件id,開始確認事件"+eventid+",確認消息爲:"+messages+"。關閉問題。",toUserName = revmsg['FromUserName']) ackevent(eventid,revmsg['FromUserName'],messages,1) #無確認消息,不關閉問題。 else: print("識別到事件id:"+eventid) itchat.send("識別到事件id,開始確認事件:"+eventid,toUserName = revmsg['FromUserName']) ackevent(eventid,revmsg['FromUserName']) elif msg == "查詢告警": gettrigger(revmsg['FromUserName']) print("查詢問題觸發器") # elif msg == "告警": # gaojing() # print("執行告警") else: welcome = "您好,歡迎使用zabbix微信告警系統!你能夠回覆關鍵字\n(查詢告警、確認事件、查詢事件等)實現功能\n如:確認事件12345,確認消息<已解決>【關閉】(確認消息以「<>」爲分隔符)\n如:查詢事件1234\n更多功能正在研發中,敬請期待!" itchat.send(welcome,toUserName = revmsg['FromUserName']) ####################################### ####################################### def quit(): itchat.logout() ####################################### def gaojing(fromuser): users = itchat.search_friends(name=u'Feiger') userName = users[0]['UserName'] #登錄zabbix獲取auth auth = authenticate(url, username, password) #狀態0是啓用監控,1是禁用監控 status=1 #定義操做ip hostip='192.168.15.139' #經過hostip獲取zabbix hostids=ipgetHostsid(hostip,url,auth) hostid=hostids[0]['hostid'] alerts=actionidgetalert(url,auth) xiaoxi=str(alerts[0]) itchat.send(xiaoxi,toUserName = userName) def gettrigger(fromuser): #獲取當前觸發器 auth = authenticate(url, username, password) trigerIDs = gettrigetID(url,auth) #獲取觸發器列表 for trigerIDresault in trigerIDs: #遍歷觸發器 eventlist = triggergetevents(trigerIDresault['triggerid'],url,auth) #獲取事件列表 #for event in eventlist: #遍歷事件 # if event['acknowledged'] == '0' and event['value'] == '0': # print(event) # print(event['eventid']) # else: # continue xiaoxi=str(trigerIDs) itchat.send(xiaoxi,toUserName = fromuser) def ackevent(eventid,fromuser,message="已確認(微信默認消息)",action=0): #確認事件 auth = authenticate(url, username, password) #執行事件確認操做,並返回已確認事件的對象 eventobj=eventackknowledge(eventid,url,auth,message,action) #調取確認事件的方法 if 'eventids' in eventobj: #eventobj這事件ID的字典 itchat.send(str(eventobj['eventids'])+"事件確認成功",toUserName = fromuser) else: itchat.send("確認事件失敗:"+eventobj,toUserName = fromuser) def getevent(eventid,fromuser): auth = authenticate(url, username, password) event=eventget(eventid,url,auth) #查詢事件 itchat.send(str(event),toUserName = fromuser) def getevents(): #經過時間獲取事件 auth = authenticate(url, username, password) users = itchat.search_friends(name=u'Feiger') userName = users[0]['UserName'] events = timegetevents("1523030400","1523116800",url,auth) print(events) #xiaoxi=str(events[0]) #itchat.send(xiaoxi,toUserName = userName) ####################################### if __name__ == '__main__': itchat.auto_login(enableCmdQR=2) itchat.run()
2,zabbix登陸邏輯git
#!/usr/bin/env python #coding:utf-8 import urllib.request, urllib.error, urllib.parse import json #定義URL帳戶密碼 url = 'http://192.168.165.179:8027/api_jsonrpc.php' username = 'admin' password = 'zabbix' #定義經過HTTP方式訪問API地址的函數,後面每次請求API的各個方法都會調用這個函數 def requestJson(url,values): data = json.dumps(values) data=bytes(data,'utf8') req = urllib.request.Request(url, data, {'Content-Type': 'application/json-rpc'}) response = urllib.request.urlopen(req, data) output = json.loads(response.read()) print(output) try: message = output['result'] except: message = output['error']['data'] print(message) return message #API接口認證的函數,登陸成功會返回一個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
3,zabbixAPI,此段代碼也是網上找到的,本身看了Zabbix的官方文檔添加了些許功能。理論上來講能夠經過微信觸發關鍵字的方式實現一切對zabbix的操做。json
#coding=utf-8 import sys import argparse import urllib.request, urllib.error, urllib.parse import json from login import * #定義檢索問題狀態下全部觸發器的ID,名稱和嚴重性,並按降序對其進行嚴重性排序。 def gettrigetID(url,auth): values = { "jsonrpc" : "2.0" , "method" : "trigger.get" , "params" : { "output" : [ "triggerid" , "description" , "priority" ] , "filter" : { "value" : 1 } , "sortfield" : "priority" , "sortorder" : "DESC" } , "auth" : auth , "id" : 1 } output = requestJson(url,values) return output #觸發器檢索事件,返回一系列以事件爲元素的列表。 def triggergetevents(triggerID,url,auth): values = { "jsonrpc": "2.0", "method": "event.get", "params": { "output": ["eventid","objectid"], "select_acknowledges":"extend", #"output": "extend", "objectids": triggerID, "sortfield": ["clock", "eventid"], "sortorder": "DESC" }, "auth": auth, "id": 1 } output = requestJson(url,values) return output #按時間檢索事件 def timegetevents(time_from,time_till,url,auth): values = { "jsonrpc": "2.0", "method": "event.get", "params": { "output": "extend", "time_from": time_from, "time_till": time_till, "sortfield": ["clock", "eventid"], "sortorder": "desc" }, "auth": auth, "id": 1 } output = requestJson(url,values) return output #經過eventID查詢事件 def eventget(eventid,url,auth): values = { "jsonrpc": "2.0", "method": "event.get", "params": { "output": ["eventid","acknowledged","objectid"], "select_acknowledges":["eventid","message","action","alias"], "eventids": eventid, }, "auth": auth, "id": 1 } output = requestJson(url,values) return output #定義確認事件方法 def eventackknowledge(eventid,url,auth,message="已確認(微信默認確認消息)",action=0): values = { 'jsonrpc' : '2.0', 'method' : 'event.acknowledge', 'params' : { 'eventids' : eventid, 'message' : message, 'action' : action }, 'auth' : auth, 'id' : 1 } print("調用了eventacknowledge方法,正在確認事件:%s"%(eventid)) output = requestJson(url,values) if 'eventids' in output: print("確認事件成功") else: print("確認事件失敗") return output #經過動做ID檢索警報 def actionidgetalert(url,auth): values = { "jsonrpc": "2.0", "method": "alert.get", "params": { "output": "extend", "actionids": '7' }, "auth":auth, "id": 1 } output = requestJson(url,values) return output #定義更新action函數 def mediatypeupdate(mediatypeid,status,auth): values = {'jsonrpc': '2.0', 'method': 'mediatype.update', 'params': { "mediatypeid": mediatypeid, "status": status }, 'auth': auth, 'id': '1' } output = requestJson(url,values) #定義讀取狀態函數 def triggerget(auth): values = {'jsonrpc': '2.0', "method":"trigger.get", "params": { "output": [ "triggerid", "description", "priority" ], "filter": { "value": 1 }, "expandData":"hostname", "sortfield": "priority", "sortorder": "DESC" }, 'auth': auth, 'id': '2' } output = requestJson(url,values) return output #定義經過ip獲取主機id的函數 def ipgetHostsid(ip,url,auth): values = {'jsonrpc': '2.0', 'method': 'host.get', 'params': { 'output': [ "host" ], 'filter': { 'ip': ip }, }, 'auth': auth, 'id': '3' } output = requestJson(url,values) return output #定義經過主機id獲取開啓關閉監控函數 def idupdatehost(status,hostid,url,auth): values = {'jsonrpc': '2.0', 'method': 'host.update', 'params': { "hostid": hostid, "status": status }, 'auth': auth, 'id': '4' } output = requestJson(url,values) return output #定義經過項目hostid獲取itemid函數 def getHostsitemsid(hostid,itemsname,url,auth): values = {'jsonrpc': '2.0', 'method': "item.get", "params": { "output": ["itemids"], "hostids": hostid, "filter":{ "key_": itemsname, }, }, 'auth': auth, 'id': '5' } output = requestJson(url,values) if len(output)==0: return output else: return output[0]['itemid'] #定義經過項目id獲取監控項目最近值信息的函數 def getHostsitemsvalue(itemid,url,auth): values = {'jsonrpc': '2.0', 'method': "history.get", "params": { "output": "extend", "history":3, "itemids":itemid, "sortfield": "clock", "sortorder": "DESC", "limit":1, }, 'auth': auth, 'id': '6' } output = requestJson(url,values) if len(output)==0: return output else: return output[0]["value"] #定義更新讀取狀態action函數 def mediatypeget(mediatypeid,auth): values = {'jsonrpc': '2.0', 'method': 'mediatype.get', 'params': { "output": "extend", "filter": { "mediatypeid":mediatypeid, }, }, 'auth': auth, 'id': '7' } output = requestJson(url,values) if len(output)==0: return output else: return output[0]['status'] #定義maintenance維修模式host函數 def maintenancecreate(maintenancename,active_since,active_till,hostid,auth): values = {'jsonrpc': '2.0', 'method': 'maintenance.create', 'params': { "name": maintenancename, "active_since": active_since, "active_till": active_till, "hostids": [ hostid ], "timeperiods": [ { "timeperiod_type": 0, "every": 1, "dayofweek": 64, "start_time": 64800, "period": 3600 } ] }, 'auth': auth, 'id': '8' } output = requestJson(url,values) #定義經過模糊獲取關閉主機信息函數 def disabledhostget(url,auth): values = {'jsonrpc': '2.0', 'method': 'host.get', "params": { "output": ["host"], 'selectInterfaces': [ "ip" ], "filter": { "status":1 } }, 'auth': auth, 'id': '9' } output = requestJson(url,values) return output #定義maintenance維修模式group函數 def maintenancecreategroup(maintenancename,active_since,active_till,groupid,auth): values = {'jsonrpc': '2.0', 'method': 'maintenance.create', 'params': { "name": maintenancename, "active_since": active_since, "active_till": active_till, "groupids": [ groupid ], "timeperiods": [ { "timeperiod_type": 0, "every": 1, "dayofweek": 64, "start_time": 64800, "period": 3600 } ] }, 'auth': auth, 'id': '10' } output = requestJson(url,values) #定義經過host groups named 獲取groupid def groupnameGroupid(groupname,auth): values = {'jsonrpc': '2.0', 'method': 'hostgroup.get', "params": { "output": "extend", "filter": { "name": [ groupname ] } }, 'auth': auth, 'id': '11' } output = requestJson(url,values) return output #定義模糊查詢維護主機 def maintenanceget(url,auth): values = {'jsonrpc': '2.0', 'method': 'maintenance.get', "params": { "output": "extend", }, 'auth': auth, 'id': '12' } output = requestJson(url,values) return output #定義批量恢復處於維護主機 def maintenancedelete(maintenanceid,url,auth): values = {'jsonrpc': '2.0', 'method': 'maintenance.delete', "params": [ maintenanceid ], 'auth': auth, 'id': '13' } output = requestJson(url,values) return output #定義經過hostid獲取graphid的函數 def getgraphid(hostid,graphname,url,auth): values = {'jsonrpc': '2.0', 'method': 'graph.get', 'params': { "output": "name", "hostids": hostid, "sortfield": "name", 'filter': { "name": graphname }, }, 'auth': auth, 'id': '14' } output = requestJson(url,values) return output
09:57:03api