设为首页 收藏本站
查看: 1424|回复: 0

[经验分享] zabbix -- 一键安装2.4.7客户端 (附:邮件、微信警报)

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2016-9-18 09:20:27 | 显示全部楼层 |阅读模式
                      小Q:各位,最近一直在玩zabbix,写点总结。
1、搭建安装脚本,一键安装2.4.7 客户端
2、报警脚本(微信 邮件)
----------------------------------------------------------------------------------------------
1、搭建安装脚本,一键安装2.4.7 客户端
a、首先要找一台原始服务器,放置zabbix_2.4.7安装包,和一个已经写好适合自己的配置文件。
b、脚本如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
function install_zabbix
{
mkdir /downloads
cd /downloads
wget http://ip/zabbix-2.4.7.tar.gz
##配置一个服务器端的zabbix安装包
tar zxf zabbix-2.4.7.tar.gz
cd /downloads/zabbix-2.4.7
./configure --prefix=/usr --sysconfdir=/etc/zabbix --enable-agent
make
make install
cp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/
sed -i "s#BASEDIR=/usr/local#BASEDIR=/usr/#g" /etc/init.d/zabbix_agentd
groupadd zabbix -g 201
useradd -g zabbix -u 201 -m zabbix
mkdir /var/log/zabbix
mkdir /var/run/zabbix
chown zabbix.zabbix /var/log/zabbix
chown zabbix:zabbix /var/run/zabbix
chmod 755 /etc/init.d/zabbix_agentd
cd /etc/zabbix
mv /etc/zabbix/zabbix_agentd.conf /etc/zabbix/zabbix_agentd.conf.bak
wget http://IP/zabbix_agentd.conf
##自定义配置文件并配置在某服务器
#cd /usr/lib64
#ln -s /usr/local/lib/libiconv.so.2 ./
#ldconfig
/etc/init.d/zabbix_agentd start
}
install_zabbix



c、zabbix_agentd.conf  文件如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
LogFile=/var/log/zabbix/zabbix_agentd.log
PidFile=/var/run/zabbix/zabbix_agentd.pid
EnableRemoteCommands=0
Server=127.0.0.1,10.47.67.163
StartAgents=8
Hostname=clientname
ServerActive=10.47.67.163:10051
Timeout=30
Include=/etc/zabbix/zabbix_agentd.conf.d/
UnsafeUserParameters=1
UserParameter=mysql.ping,/usr/local/mysql/bin/mysqladmin -uroot ping|grep -c alive
UserParameter=mysql.version,mysql -V | cut -f6 -d " "| sed 's/,//'
UserParameter=custom.vfs.dev.read.sectors
  • ,cat /proc/diskstats | grep vda | head -1 | awk '{print $$6}'
    UserParameter=custom.vfs.dev.write.sectors
  • ,cat /proc/diskstats | grep vda | head -1 | awk '{print $$10}'



  • 2、报警脚本(微信 邮件)
    -----------------------------------------------------------放置地址在配置文件中定义
    wKioL1fc2kPxhHDrAACCrcC4RSo856.jpg
    spacer.jpg --------------------------------------------------------------------weixin
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    #!/usr/local/php/bin/php
    <?php
    error_reporting(E_ALL);
    ini_set("display_errors", true);
    class SdkQywx
    {
        const CORPID      = 'wx1b71f3b1c380ce02';
        const CORP_SECRET = 'S8-ZDuwiPipX0YQWs_xF9c4P6drWw08Z1MV0e_TgReTtYpn-4dqhBglthztHdFio';
        public static $_app_list = array(
           // 'gonggaotongzhi' => 34,
           // 'kaoqinxitong'   => 35,
           // 'huiyixitong'    => 36,
            'm_monitor'     => 43,
        );
        const IMAGE = 'image';
        const VOICE = 'voice';
        const VIDEO = 'video';
        const FILE  = 'file';
        public static $tmpConnections;
        private static $_access_token;
        private static $expire_on = 0;
        private $access_token;
        //阻止外部实例化,仅允许使用getInstance进行单例操作
        private function __construct($access_token)
        {
            $this->access_token = $access_token;
        }
        //防止对象被复制
        public function __clone()
        {
            trigger_error('Clone is not allowed !');
        }
        /**
         * 获取单例
         *
         * @return <Object>
         */
        public static function getInstance()
        {
            $access_token = self::fetchAccessToken();
            if (!isset(self::$tmpConnections[$access_token]) || !(self::$tmpConnections[$access_token] instanceof self))
            {
                // 清空连接池
                self::$tmpConnections = array();
                // 缓存新连接
                self::$tmpConnections[$access_token] = new self($access_token);
            }
            return self::$tmpConnections[$access_token];
        }
        private static function fetchAccessToken()
        {
            // 检查连接令牌是否超时
            if (self::$expire_on <= time())
            {
                // 调用接口获取连接令牌
                $result = self::doGet('https://qyapi.weixin.qq.com/cgi-bin/gettoken', array(
                            'corpid'     => self::CORPID,
                            'corpsecret' => self::CORP_SECRET,
                ));
                // 校验结果
                if (isset($result['errcode']))
                {
                    return null;
                }
                // 缓存令牌
                self::$expire_on     = time() + $result['expires_in'];
                self::$_access_token = $result['access_token'];
            }
            return self::$_access_token;
        }
        public function sendNewsMessage($agentid, $user_id, $content)
        {
            $url    = 'https://qyapi.weixin.qq.com/cgi-bin/message/send';
            $params = array('access_token' => $this->access_token);
            if (is_array($user_id))
            {
                $user_id = implode('|', $user_id);
            }
            $agentid  = (int) $agentid;
            $articles = '[';
            $tips     = '';
            foreach ($content as $article)
            {
                $article['title']       = str_replace('"', '\"', $article['title']);
                $article['description'] = str_replace('"', '\"', $article['description']);
                $article['url']         = str_replace('"', '\"', $article['url']);
                $articles .= $tips . '{"title":"' . $article['title'] . '","description":"' . $article['description'] . '","url":"' . $article['url'] . '"}';
                $tips                   = ',';
            }
            $articles .= ']';
            $post_data = '{"touser":"' . $user_id . '","msgtype":"news","agentid":' . $agentid . ',"news":{"articles":' . $articles . '}}';
            return self::doPost($url, $params, $post_data);
        }
        private static function doGet($url, $params = array())
        {
            $ch     = curl_init($url . '?' . http_build_query($params));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回
            curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
            $result = curl_exec($ch);
            curl_close($ch);
            return json_decode($result, true);
        }
        private static function doPost($url, $params = array(), $post_data = array())
        {
            $ch   = curl_init($url . '?' . http_build_query($params));
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $info = curl_exec($ch);
            curl_close($ch);
            return json_decode($info, true);
        }
    }
    $receiver = "$argv[1]";
    $title = "$argv[2]";
    $desc = "$argv[3]";
    $url = "http://zabbix网址/zabbix";
    //$receiver = "接收人";
    $content = array(
                    array(
                            'title' => $title,
                            'description' => $desc,
                            'url' => $url
                            )
                    );
    $r = SdkQywx::getInstance()->sendNewsMessage(43, $receiver, $content);



    ----------------------------------------------------------------------------------python
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    #!/usr/bin/python
    #coding:utf-8
    import smtplib
    from email.MIMEText import MIMEText
    import sys
    import os
    import argparse
    import logging
    import datetime
    mail_host = 'mailex.com'
    mail_user = 'zabbix@mailex.com'
    mail_pass = 'wslmwps'
    mail_postfix = 'mailex.com'
    mail_nickname = 'zabbix'
    ######################################
    ######################################
    global sendstatus
    global senderr
    def send_mail(mail_to,subject,content):
        me = mail_nickname +"<"+mail_user+">"
        msg = MIMEText(content)
        msg['Subject'] = subject
        msg['From'] = me
        msg['to'] = mail_to
        try:
            smtp = smtplib.SMTP()
            smtp.connect(mail_host)
            smtp.login(mail_user,mail_pass)
            smtp.sendmail(me,mail_to,msg.as_string())
            print 'send ok'
            sendstatus = True
        except Exception , e:
            sendert=str(e)
            #print senderr
            sendstatus = False
    def logwrite(sendstatus,mail_to,content):
        logpath='/var/log/zabbix/alert'

        if not sendstatus:
            content = senderr
        if not os.path.isdir(logpath):
            os.makedirs(logpath)
        t=datetime.datetime.now()
        daytime=t.strftime('%Y-%m-%d')
        daylogfile=logpath+'/'+str(daytime)+'.log'
        logging.basicConfig(filename=daylogfile,level=logging.DEBUG)
        logging.info('*'*130)
        logging.debug(str(t)+'mail send to{0},content is :\n {1}'.format(mail_to,content))
    if  __name__=="__main__":
        parser = argparse.ArgumentParser(description='Send mail to user for zabbix alterting')
        parser.add_argument('mail_to',action="store",help='The address of the E-mail that send to user')
        parser.add_argument('subject',action="store",help='The subject of the E-mail')
        parser.add_argument('content',action="store",help='The content of the E-mail')
        args = parser.parse_args()
        mail_to=args.mail_to
        subject=args.subject
        content=args.content

        send_mail(mail_to,subject,content)
        #logwrite(sendstatus,mail_to,content)




                       


    运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
    2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
    3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
    4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
    5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
    6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
    7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
    8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

    所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-273745-1-1.html 上篇帖子: zabbix proxy 3.0 RPM安装 下篇帖子: 企业级开源监控软件zabbix
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    扫码加入运维网微信交流群X

    扫码加入运维网微信交流群

    扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

    扫描微信二维码查看详情

    客服E-mail:kefu@iyunv.com 客服QQ:1061981298


    QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


    提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


    本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



    合作伙伴: 青云cloud

    快速回复 返回顶部 返回列表