配置 ZABBIX 使用企业微信发送 Alert 消息

成功的从企业微信中收到的 Alert 消息的样子:

Oracle 日志 Alert:

网络专线 Alert:

服务器 Alert:

Linux 命令行使用方法:

./workweixin_send.php
Usage: workweixin_send.php.php <username> <title> <content>
./workweixin_send.php <这里填写企业个人微信ID> hi  这是一条测试的企业微信消息

Windows 命令行使用方法:

php workweixin_send.php <这里填写企业个人微信ID> hi  这是一条测试的企业微信消息

测试消息发送成功的样子:

ZABBIX WEB前端中的配置:

ZABBIX 配置文件中的配置:

AlertScriptsPath=/opt/zabbix/scripts/

PHP脚本(需要安装PHP解释器和MEMCACHE,可以参照这个文章进行安装[《PHP版本5到7的源码编译安装》](https://blog.51cto.com/12641643/2484914)):

#!/opt/php/bin/php -q
<?php
class Cache
{
    /**
     * Cache instance
     * @var Cache
     */
    private static $instance;

    protected $conn;

    /**
     * 获得一个 cache 缓存实例
     * @param mixed $params
     * @return Cache
     */
    public static function getConnect($params = ‘‘) : Cache
    {
        if (! self::$instance instanceof self) {
            self::$instance = new self($params);
        }
        return self::$instance;
    }

    /**
     * 实例化一个 cache 实例
     * @param mixed $params
     * @throws \Exception
     */
    private function __construct($params)
    {
        if (! is_array($params)) {
            throw new \Exception(‘Invalid cache params, failed connect to cache server‘);
        }
        if (!isset($params[‘host‘])) {
            throw new \Exception(‘Invalid cache host‘);
        }
        if (!isset($params[‘port‘]) or ($params[‘port‘] < 1 and $params[‘port‘] > 65535)) {
            throw new \Exception(‘Invalid cache port‘);
        }
        if (!isset($params[‘persistent‘])) {
            $params[‘persistent‘] = false;
        }
        $params[‘persistent‘] = boolval($params[‘persistent‘]);

        $this->conn= new \Memcache();
        if ($params[‘persistent‘]) {
            $conn = $this->conn->pconnect($params[‘host‘], $params[‘port‘]);
        } else {
            $conn = $this->conn->connect($params[‘host‘], $params[‘port‘]);
        }
        if ($conn === false) {
            throw new \Exception(‘Failed connect to cache server‘);
        }
    }

    /**
     * 返回缓存值
     * @param string $key
     * @param mixed $default
     */
    public function get(string $key, $default = null)
    {
        if (!empty($key)) {
            $default = $this->conn->get($key);
        }
        return $default;
    }

    /**
     * 设置缓存值
     * @param string $key
     * @param mixed $value
     * @param int $ttl
     * @param bool $compress
     * @return bool
     */
    public function set(string $key, $value = null, int $ttl = null, $compress = false)
    {
        if ($ttl === null) {
            $ttl = $this->getTTL();
        }
        if ($compress) {
            return $this->conn->set($key, $value, MEMCACHE_COMPRESSED, $ttl);
        } else {
            return $this->conn->set($key, $value, 0 , $ttl);
        }
    }
}

class AccessToken
{
    /**
     * 企业ID<p>
     * 每个企业都拥有唯一的corpid,获取此信息可在管理后台“我的企业”-“企业信息”下查看“企业ID”
     * @var string
     */
    protected $corpid;

    /**
     * secret是企业应用里面用于保障数据安全的“钥匙”,每一个应用都有一个独立的访问密钥,为了保证数据的安全,secret务必不能泄漏
     * @var string
     */
    protected $secret;

    /**
     * 获取 access token 的 url
     * @var string
     */
    protected $url;

    /**
     * 过期时间
     * @var string
     */
    protected $expire;

    /**
     * 配置 corpid 和 secret
     * @param string $corpid
     * @param string $secret
     */
    public function __construct(string $corpid, string $secret)
    {
        $this->corpid = $corpid;
        $this->secret = $secret;
    }

    /**
     * 设置获取 access token 的 url
     * @param string $url
     */
    public function setUrl(string $url) : AccessToken
    {
        $this->url = str_replace([‘{corpid}‘, ‘{secret}‘], [$this->corpid, $this->secret], $url);
        return $this;
    }

    /**
     * 返回 access token
     * @return string
     */
    public function getAccessToken() : string
    {
        $cache = Cache::getConnect();
        $accessToken = $cache->get(‘work.weixin.access.token‘);
        if (empty($accessToken)) {
            $accessToken = $this->getAccessTokenFromServer();
            $cache->set(‘work.weixin.access.token‘, $accessToken, $this->getExpire() - 60);
        }
        return $accessToken;
    }

    /**
     * 返回 access token 的有效时间
     * @return int
     */
    public function getExpire() : int
    {
        return $this->expire;
    }

    /**
     * 从企业微信服务器上获取 access token
     * @return string
     */
    final protected function getAccessTokenFromServer() : string
    {
        $ch = curl_init();
        $options = [
            CURLOPT_URL             => $this->url,
            CURLOPT_TIMEOUT         => 10,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false
        ];
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        /*
         * 微信接口返回数据格式:
         * {‘errcode‘,‘errmsg‘,‘access_token‘,‘expires_in‘}
         */
        $data = json_decode($response, true);

        if (empty($data)) {
            throw new \Exception(‘Failed to access work weixin api‘);
        }

        // 判断是否成功取得access_token
        if ($data[‘errcode‘] !== 0) {
            throw new \Exception(‘Failed to get work weixin access token from server. ‘ . $data[‘errmsg‘]);
        }

        $this->expire = $data[‘expires_in‘];

        return $data[‘access_token‘];
    }
}

class SendMessage
{

    /**
     * access token instance
     * @var AccessToken
     */
    protected $accessToken;

    /**
     * 发送消息的url
     * @var string
     */
    protected $url;

    /**
     * 成员ID列表(指定为@all时则向关注该企业应用的全部成员发送)
     * @var array
     */
    protected $toUsers = [];

    /**
     * 部门ID列表(当touser为@all时忽略本参数)
     * @var array
     */
    protected $toParties = [];

    /**
     * 标签ID列表(当touser为@all时忽略本参数)
     * @var array
     */
    protected $toTags = [];

    /**
     * 企业应用的id,整型。可在应用的设置页面查看
     * @var int
     */
    protected $agentId;

    /**
     * 消息内容
     * @var string
     */
    protected $content;

    /**
     * 保密信息(表示是否是保密消息,0表示否,1表示是,默认0)
     * @var int
     */
    protected $safe = 0;

    public function __construct(AccessToken $accessToken)
    {
        $this->accessToken = $accessToken;
    }

    /**
     * 设置成员ID
     * @param array $users
     * @return SendMessage
     */
    public function setToUsers(array $users) : SendMessage
    {
        foreach ($users as $k => $user) {
            if (is_string($user)) {
                $this->toUsers[] = $user;
            }
        }
        return $this;
    }

    /**
     * 设置部门ID
     * @param array $parties
     * @return SendMessage
     */
    public function setToParties(array $parties) : SendMessage
    {
        foreach ($parties as $k => $party) {
            if (is_string($party)) {
                $this->toParties[] = $party;
            }
        }
        return $this;
    }

    /**
     * 设置标签ID
     * @param array $tags
     * @return SendMessage
     */
    public function setToTag(array $tags) : SendMessage
    {
        foreach ($tags as $k => $tag) {
            if (is_string($tag)) {
                $this->toTags[] = $tag;
            }
        }
        return $this;
    }

    /**
     * 设置应用ID
     * @param int $id
     * @return SendMessage
     */
    public function setAgentId(int $id) : SendMessage
    {
        $this->agentId = $id;
        return $this;
    }

    /**
     * 设置消息内容(最长不超过2048个字节)
     * @param string $content
     * @return SendMessage
     */
    public function setContent(string $content) : SendMessage
    {
        if (!empty($content)) {
            $this->content = $content;
        }
        return $this;
    }

    public function setUrl(string $url) : SendMessage
    {
        $this->url = str_replace(‘{accessToken}‘, $this->accessToken->getAccessToken(), $url);
        return $this;
    }

    /**
     * 调用企业微信 api 发送消息
     * @throws \Exception
     */
    private function send(string $data)
    {
        $ch = curl_init();
        $options = [
            CURLOPT_URL             => $this->url,
            CURLOPT_HEADER          => 0,
            CURLOPT_POST            => 1,
            CURLOPT_POSTFIELDS      => $data,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_TIMEOUT         => 10,
            CURLOPT_SSL_VERIFYPEER  => 0,
            CURLOPT_SSL_VERIFYHOST  => 0
        ];
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        $data = json_decode($response, true);

        if (empty($data)) {
            throw new \Exception(‘Failed to access work weixin api‘);
        }
        if ($data[‘errcode‘] !== 0) {
            throw new \Exception(‘Failed to send WeiXin message. ‘ . $data[‘errmsg‘]);
        }
    }

    /**
     * 发送文本消息
     * @throws \Exception
     */
    public function sendTextMessage() {
        if (empty($this->toUsers) && empty($this->toParties) && empty($this->toTags)) {
            throw new \Exception(‘Invalid message recevier‘);
        }
        if (empty($this->agentId)) {
            throw new \Exception(‘Invalid app agentid‘);
        }
        if (empty($this->content)) {
            throw new \Exception(‘Empty message content‘);
        }
        $data = json_encode([
            ‘touser‘    => implode(‘|‘, $this->toUsers),
            ‘toparty‘   => implode(‘|‘, $this->toParties),
            ‘totag‘     => implode(‘|‘, $this->toTags),
            ‘msgtype‘   => ‘text‘,
            ‘agentid‘   => $this->agentId,
            ‘safe‘      => $this->safe,
            ‘text‘      => [
                ‘content‘   => $this->content
            ]
        ], JSON_UNESCAPED_UNICODE);

        // 如果第一次发送失败,尝试两次发送
        try {
            $this->send($data);
        } catch (\Exception $e) {
            $this->send($data);
        }
    }

}

// -----------------------------------------------------------------------------------

$cacheParams = [
    ‘host‘ => ‘127.0.0.1‘,
    ‘port‘ => ‘11211‘
];
// 每个企业都拥有唯一的corpid,获取此信息可在管理后台“我的企业”-“企业信息”下查看“企业ID”
$corpid = ‘*************‘;
//secret是企业应用里面用于保障数据安全的“钥匙”,每一个应用都有一个独立的访问密钥,为了保证数据的安全,secret务必不能泄漏
$secret = ‘*************‘;
// agentid 企业应用的id,整型。可在应用的设置页面查看
$agentid = 1;
$fetchAccessTokenUrl= "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}";
$sendMessageUrl = ‘https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={accessToken}‘;

// -----------------------------------------------------------------------------------

if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3])) {
    echo ‘Usage: ‘ . basename(__FILE__) . ‘.php <username> <title> <content>‘;
    return;
}

// -----------------------------------------------------------------------------------

try {

    Cache::getConnect($cacheParams);

    $accessToken = new AccessToken($corpid, $secret);
    $accessToken->setUrl($fetchAccessTokenUrl);

    $wwx = new SendMessage($accessToken);
    $wwx->setAgentId($agentid)
        ->setUrl($sendMessageUrl)
        ->setToUsers([$argv[1]])
        ->setContent(str_replace(‘?‘, ‘‘, strip_tags($argv[3])))
        ->sendTextMessage();
} catch (\Exception $e) {
    echo $e->getMessage();
    file_put_contents(basename(__FILE__, ‘.php‘) . ‘.log‘, $e->getMessage());
}

原文地址:https://blog.51cto.com/12641643/2485835

时间: 2024-08-28 19:09:36

配置 ZABBIX 使用企业微信发送 Alert 消息的相关文章

python实现通过企业微信发送消息

实现了通过企业微信发送消息,平时用于运维的告警还是不错的,相对于邮件来说,实时性更高,不过就是企业微信比较麻烦,此处不做过多解释. 企业微信api的详细请看:http://work.weixin.qq.com/api/doc#10167 话不多说,直接代码 1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 # @Time : 2018/4/25 17:06 5 # @Author : zms 6 # @Site : 7 # @File :

使用python3给企业微信发送消息

一.概述 本文将介绍如何使用python3给企业微信发送消息.我的环境是linux + python3.6.10. 二.python脚本 #!/root/.virtualenvs/wechat/bin/python # usage: send message via wechat import requests, sys, json import urllib3 urllib3.disable_warnings() ###填写参数### # Corpid是企业号的标识 Corpid = "ww3

Zabbix创建企业微信

(八)Zabbix创建企业微信 背景: 1.zabbix-3.4.4服务器搭建完成 2.主机监控已经部署(能触发警告报警即可) 思路: 1.创建免费的企业微信 2.根据自己报警内容可建多个企业应用 3.创建报警脚本.配置.测试 4.本内容仅供参考,以便以后学习使用. 一.创建企业应用 1.企业微信注册 注册地址:https://qy.weixin.qq.com/截止目前2017年11月30日此网站一直能用,不能保证以后能否使用,见谅,以前叫企业号,现在叫企业微信,哈哈.注册步骤就不在这重复了,和

zabbix调用telegram机器人发送报警消息

众所周知,telegram的机器人还是非常好用,而且是免费的,所以这就给监控系统发送报警消息提供了一个非常好的渠道,相信很多朋友已经垂涎三尺了,所以废话不多说,直奔主题吧!br/>?zabbix系统基础配置部分此处就直接跳过了,如果需求请参阅http://blog.51cto.com/183530300/category8.html?此处我们直接从创建机器人开始,当然创建机器人的前提是你要先有一个telegram账号,接下来是在telegram客户端上的操作了第一步:在搜索栏里直接使用@BotF

zabbix使用企业微信发消息

注册一个企业微信,https://work.weixin.qq.com/ 接收消息有2种方式,一是用企业微信,二是用个人微信(需要关注企业号,需要登录扫描下图邀请关注的二维码): 官方api说明 地址:https://work.weixin.qq.com/api/doc#10167 过程 一:创建自建应用「报警」,然后用公司corpid和企业应用secret获取token,https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$corpid&co

zabbix实现企业微信告警,亲测可用~~

Zabbix 新版微信告警 date 2017-06-14 标签(空格分隔): zabbix Zabbix可以通过多种方式把告警信息发送到指定人,常用的有邮件,短信报警方式,但是越来越多的企业开始使用zabbix结合微信作为主要的告警方式,这样可以及时有效的把告警信息推送到接收人,方便告警的及时处理. 关于邮件报警可以参考: Zabbix 使用脚本发送邮件 Zabbix Web 邮件报警 一.微信企业号申请 地址: http://work.weixin.qq.com/ 第一步注册 因为我们没有企

微信发送模板消息代码示例

最近一个微信的项目里需要发送微信模板消息给卖家或者供应商等,微信开发其实也就按照微信的官方接口要求组装起来即可,下面简单介绍一下我的微信模板发送代码. 1.获取access token,至于access token是什么,大家可以自行微信接口文档看一下,这边不多说 获取access token我这边主要是用定时器没大概2分钟获取一次,每天获取的次数是100000次,用法如下: 1 #region 2 3 using System; 4 using System.Timers; 5 6 #endr

zabbix之企业微信报警通知

一.背景介绍: 起初使用邮件报警,接收效果一直不好,需要打开邮箱才看到报警邮件.后来使用微信企业公众号,方便,省事,接收及时,可以做到第一时间相应.现在微信企业公众号更新成企业微信了.发送报警的方式有稍微改变.之前借用别人的脚本,密密麻麻.借此机会,自己写了个脚本与之分享. 二.实现步骤: 1.申请企业微信号 2.创建告警脚本 3.设置web管理界面触发脚本. 4.修改zabbix_server端配置文件.并重启 5.测试报警触发功能 6.完成 三.实施部署: 完成第一步:申请企业微信号: 地址

用企业微信发送告警

1.遇到的坑 {"errcode":40001,"errmsg":"invalid credential, hint: [1507881186_cb1093c9bcaedaf108b7ce2ea10f2d38]"} 40001 不合法的secret参数 secret在应用详情/通讯录管理助手可查看 排查secret的取值也没有错啊.就郁闷了. 最后发现问题:是corpid写错了.把企业id写成了应用id. 因为“全局错误码”里没有提到corpid