一、Zabbix微信报警

默认路径:/usr/lib/zabbix/scripts/weixin.py

#!/usr/bin/python
# -*- coding: utf-8 -*- import urllib,json
import urllib2
import sys
import time
reload(sys)
#print sys.getdefaultencoding()
sys.setdefaultencoding('utf8')
#print sys.getdefaultencoding()
############################
#CorpId = '******9b5c9d******'
#AgentId = '1000013'
#Secret = '******7ln1_bRDLydnMBoCn9Cof7JqSiG7JuJ******'
#AuthId = 60
############################
class WeChat(object):
__token_id = ''
# init attribute
def __init__(self,url):
self.__url = url.rstrip('/')
self.__corpid = '******9b5c9d******'
self.__secret = '******7ln1_bRDLydnMBoCn9Cof7JqSiG7JuJ******' # Get TokenID
def authID(self):
params = {'corpid':self.__corpid, 'corpsecret':self.__secret}
data = urllib.urlencode(params)
content = self.getToken(data) try:
self.__token_id = content['access_token']
#print('access_token: '+content['access_token'])
except KeyError:
raise KeyError # Establish a connection
def getToken(self,data,url_prefix='/'):
url = self.__url + url_prefix + 'gettoken?'
try:
response = urllib2.Request(url + data)
except KeyError:
raise KeyError
result = urllib2.urlopen(response)
#print('result: ',result)
content = json.loads(result.read())
#print('content: ',content)
return content # Get sendmessage url
def postData(self,data,url_prefix='/'):
url = self.__url + url_prefix + 'message/send?access_token=%s' % self.__token_id
request = urllib2.Request(url,data)
try:
result = urllib2.urlopen(request)
except urllib2.HTTPError as e:
if hasattr(e,'reason'):
print('reason',e.reason)
elif hasattr(e,'code'):
print('code',e.code)
return 0
else:
content = json.loads(result.read())
result.close()
return content # send message
def sendMessage(self,touser,message):
self.authID()
data = json.dumps({
'touser':touser,
'toparty':"",
'msgtype':"text",
'agentid':"",
'text':{
'content':message
},
'safe':""
},ensure_ascii=False) response = self.postData(data)
print(response) if __name__ == '__main__':
a = WeChat('https://qyapi.weixin.qq.com/cgi-bin')
f=open(r'/tmp/wechat_warning.log', 'a+')
for i in sys.argv:
f.write(i)
f.write("\n")
f.close()
a.sendMessage(sys.argv[1],sys.argv[3])

二、写触发事件日志

/usr/lib/zabbix/scripts/trigger.py

#!/usr/bin/python36
import sys,time
import pymysql now=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
f=open(r'/tmp/trigger_writing.log', 'a+')
f.write("\n* * * * * * * * * * * * * * * * * * * * * * \n")
f.write(now+" ")
for line in sys.argv:
f.write(line)
f.write("\n")
f.write("\n")
f.close() f=open(r'/tmp/trigger_writing.log', 'a+')
print(sys.argv,file=f)
arr=sys.argv
need_arr =arr[3].split("\r\n")
for i in range(len(need_arr)):
if i >= 0:
key = need_arr[i].split(':')
if key[0] == 'ip_addr':
ip_addr = key[1].strip()
elif key[0] == 'host_name':
host_name = key[1].strip()
elif key[0] == 'host_port':
host_port = key[1].strip()
elif key[0] == 'item_id':
item_id = key[1].strip()
elif key[0] == 'item_name':
if len(key) > 2 :
item_name = key[1].strip()+':'+key[2].strip()
else:
item_name = key[1].strip()
elif key[0] == 'item_key':
if len(key) > 2:
item_key = key[1].strip()+':'+key[2].strip()
else:
item_key = key[1].strip()
elif key[0] == 'item_value':
item_value = key[1].strip()
elif key[0] == 'item_lastvalue':
item_lastvalue = key[1].strip()
elif key[0] == 'trigger_id':
trigger_id = key[1].strip()
elif key[0] == 'trigger_name':
if len(key) > 2:
trigger_name = key[1].strip()+':'+key[2].strip()
else:
trigger_name = key[1].strip()
elif key[0] == 'trigger_severity':
trigger_severity = key[1].strip()
elif key[0] == 'trigger_status':
trigger_status = key[1].strip()
elif key[0] == 'trigger_value':
trigger_value = key[1].strip()
elif key[0] == 'event_age':
event_age = key[1].strip()
elif key[0] == 'event_date':
event_date = key[1].strip()
elif key[0] == 'event_time':
event_time = key[1].strip()+':'+key[2].strip()+':'+key[3].strip()
elif key[0] == 'event_id':
event_id = key[1].strip()
else:
continue value = "'"+ip_addr+"','"+host_name+"','"+host_port+"','"+item_id+"','"+item_name+"','"\
+item_key+"','"+item_value+"','"+item_lastvalue+"','"+trigger_id+"','"+trigger_name+"','"\
+trigger_severity+"','"+trigger_status+"','"+trigger_value+"','"+event_age+"','"\
+event_date+"','"+event_time+"','"+event_id+"'" sql = "insert into sp_zbx_trigger (ipaddress,hostname,hostport,itemid,itemname,itemkey,itemvalue,itemlastvalue,triggerid,triggername,triggerseverity,triggerstatus,triggervalue,eventage,eventdate,eventtime,eventid) values " + "(" + value +")"
#print(sql,file=f)
f.write("\n"+sql+"\n")
f.close() # conn database
db = pymysql.connect(host='192.168.0.201', port=3306, user='user', passwd='passwd', db='zabbix')
# create cursor
cursor = db.cursor()
try:
if cursor.execute(sql):
print('ok')
db.commit()
except Exception as e:
print(e.args)
db.rollback()
db.close()

Zabbix微信报警脚本及写触发记录的更多相关文章

  1. zabbix 微信报警脚本

    不知道是什么原因直接用Python脚本zabbix无法执行脚本,需要一个shell来启动 #! /bin/bash userid=$ content=$ python /data/zabbix/ale ...

  2. Zabbix微信报警触发

    (1)         企业应用-创建应用 1.除了对个人添加微信报警之外,还可以添加不同管理组,接受同一个应用推送的消息, 成员账号,组织部门ID,应用Agent ID,CorpID和Secret, ...

  3. 通过脚本发送zabbix微信报警

    实现zabbix通过微信报警的方式也是通过脚本来实现,与邮件报警不同的是,脚本调用的微信的相关接口的获取相对复杂一点 1.申请一个微信公众号(企业号) 申请方法不多说,如果已申请请忽略 2.在微信企业 ...

  4. (五)zabbix微信报警

    1.注册微信企业号 1)注册微信企业号 https://work.weixin.qq.com 2)通讯录添加用户 3)记住部门id 4)创建应用 5)点击刚创建的应用,记住Agentld和secret ...

  5. Zabbix 微信报警Python版(带监控项波动图片)

    #!/usr/bin/python # -*- coding: UTF- -*- #Function: 微信报警python版(带波动图) #Environment: python import ur ...

  6. zabbix 微信报警

    http://blog.csdn.net/wh211212/article/details/52735236 Zabbix可以通过多种方式把告警信息发送到指定人,常用的有邮件,短信报警方式,但是越来越 ...

  7. filebeat+logstash通过zabbix微信报警

    一.安装软件: 1.在要收集日志的机器上安装filebeat: 1).下载安装: cd /usr/local/src wget https://artifacts.elastic.co/downloa ...

  8. zabbix微信报警

    [root@LinuxS04 jiaoben]# ./weixin 联系人 baojing baojingok[root@LinuxS04 jiaoben]# pwd/usr/local/zabbix ...

  9. zabbix邮件报警脚本(Python)

    #!/usr/bin/python #coding:utf-8 import smtplib from email.mime.text import MIMEText import sys mail_ ...

随机推荐

  1. 【前端技术】一篇文章搞掂:uni-app

    语法 //列表遍历,遍历数组,第一个参数为数组中元素,可以给第二个参数作为索引值 <view v-for="(item, itemIndex) in card" :key=& ...

  2. ORACLE Physical Standby DG搭建

    主库: 一:强制force logging: alter database force logging; 二:开启主库的归档模式 三:主库添加standby redo log,比redo日志组多一组: ...

  3. p5342 [TJOI2019]甲苯先生的线段树

    分析  代码 #include<bits/stdc++.h> using namespace std; #define int long long ],yy[],cnt1,cnt2; ][ ...

  4. jenkins展示html测试报告(不使用html publisher)

     最终效果: 点击『测试报告』,查看测试报告: 一开始的思路是: jenkins上展示html报告[转载] jenkins使用HTML Publisher Plugin插件 拉取报告样式缺失问题解决 ...

  5. zookeeper分布式锁用法

    package com.example.demo3.zk; import lombok.extern.slf4j.Slf4j; import org.apache.storm.shade.org.ap ...

  6. 16/7/14-MySQL-遇到的基本问题

    从一开始遇到的3534 ---------------------------------------------------------------------------------------- ...

  7. poj3280Cheapest Palindrome

    给定一个字符串S,字符串S的长度为M(M≤2000),字符串S所含有的字符的种类的数量为N(N≤26),然后给定这N种字符Add与Delete的代价,求将S变为回文串的最小代价和. Input 第一行 ...

  8. app本身性能测试简介

    app 性能测试指标: 1.启动时间 2.内存占用量,内存警告次数 3.页面渲染时间,刷新帧率 4.网络请求时间.流量消耗 5.UI阻塞次数,不可操作时长,主线程阻塞超过400毫秒次数 6.耗电功率 ...

  9. Python入门习题8.羊车门问题

    例8. 羊车门问题描述:有3扇关闭的门,一扇后停着汽车,另外两扇门后是山羊,主持人知道每扇门后是什么.参赛者首先选择一扇门.在开启它之前,主持人会从另外两扇门中打开一扇门,露出门后的山羊.此时,允许参 ...

  10. LayaBox 常用技巧

    1.修改IDE的菜单 找到安装路径的LayaAirIDE\resources\app\out\vs\layaEditor\renders\laya.editorUI.xml 注意事项: 1.mask的 ...