Zabbix错误”zbx_mem_malloc(): out of memory”解决方法

Zabbix Server突然挂了,查看log报错如下:

using configuration file: /etc/zabbix/zabbix_server.conf
...
[file:dbconfig.c,line:545] zbx_mem_malloc(): out of memory (requested 16 bytes)
[file:dbconfig.c,line:545] zbx_mem_malloc(): please increase CacheSize configuration parameter

报错里已经很明确的提示了修复办法:please increase CacheSize configuration parameter

所以,我们就去zabbix_server.conf中找到CacheSize字段

### Option: CacheSize
#   Size of configuration cache, in bytes.
#   Shared memory size for storing host, item and trigger data.
#
# Mandatory: no
# Range: 128K-8G
# Default:
# CacheSize=8M

根据服务器配置情况,修改CacheSize

### Option: CacheSize
#   Size of configuration cache, in bytes.
#   Shared memory size for storing host, item and trigger data.
#
# Mandatory: no
# Range: 128K-8G
# Default:
CacheSize=2048M

重启Zabbix Server即可

systemctl start zabbix-server

zabbix告警事件归档与提取

由于现网设备量比较大,根据业务类型又分了上百个左右的业务模块。而基于zabbix搭建的基础告警每天吐出的告警信息特别多。为了提高告警的准确性和及时率,同时也便于后期查询和报表统计。考虑将zabbix的部分进行下修改。

一、alerts表信息提取

alerts 中存放的是通过短信、邮件或其他媒介发出的告警数据 。比如要提取当天的所有磁盘相应的已发出的所有告警,可以通过如下sql 语句实现:

select FROM_UNIXTIME(clock),sendto,`subject` from alerts
where `subject` like '%磁盘%'
and DATE_FORMAT(FROM_UNIXTIME(clock),'%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d');

由于其中的clock时间使用的是unixtime,所以这里需要查询的时候通过转化,就成datetime时间 。查询结果如下:

未分类

不过通过alter表获取的数据有以下缺点:

  • 不好明确区分告警问题是否已恢复(通过告警恢复正常触发器可以判读,但 alerts 数据量比较大时,就不好处理了);

  • 并未配置媒介告警的事件类无法在该表体现;

  • 不便区分告警问题的级别;

二、event事件表关联

通过event表,关联基他几个表的数据,可以将查询的结果生成一个临时表 。通过查询该临时表,可以得到我们关心的几个数据:

#创建临时表
DROP TABLE IF EXISTS `tmp1`;
create table tmp1 as
     (SELECT
            `hosts`.`host`,
            `triggers`.triggerid,
            `triggers`.description,
            `triggers`.priority,
            `events`.`value`,
            FROM_UNIXTIME(`events`.clock) time
    FROM
            `hosts`,
            `triggers`,
            `events`,
            `items`,
            `functions`,
            `groups`,
            `hosts_groups`
    WHERE
            `hosts`.hostid = `hosts_groups`.hostid
            AND `hosts_groups`.groupid = `groups`.groupid
            AND `triggers`.triggerid = `events`.objectid
            AND `hosts`.hostid = `items`.hostid
            AND `items`.itemid = `functions`.itemid
            AND `functions`.triggerid = `triggers`.triggerid);
#查询磁盘告警,且未恢复的
select * from tmp1 where value=1
and  triggerid not in (select triggerid from tmp1 where value=0)
and  description like '%磁盘%';

其中triggers.priority字段表示的是事件的告警级别(如普通、严重),events.value代表的是告警事件是否恢复(1代表存在问题,0代表正常),triggers.description 为告警描述信息 。

event事件关联临时表虽然解决了我们的需求,不过也存在一些小瑕疵:由于设备量比较多,仅仅几个月的基础事件就有几百万条,每次查询为了保证事件的完整性,都需要执行删除临时表,再重新将查询结果生成到临时表的方法相对较慢 ,而且当这个查询执行的时候会对mysql 造成一点性能伤害 ---尽管可以在zabbix 的mysql 备库上执行 。

三、mysql 触发器

为了满足后期一些报表定制查询的需要,决定使用触发器,对event事件表发生insert操作时,自动将查行一个select关联查询,并将关联查询的结果

未分类

这里只使用newevent事件表,其中devtype、cause、sendstatus字段也暂时不用,后期需要分表设计时,可以考虑使用。如果启用dict表,还有一个可优化的项,因为description类型只有几千个,而newevent事件有几百万条,可以去掉description字段,将该字段放到dict表里,通过descid 字段去关联。

这里先以最简单的方式进行实现,先建库建表,如下:

DROP DATABASE IF EXISTS `report`;
CREATE DATABASE report character set utf8;
USE report;
DROP TABLE IF EXISTS `newevent`;
CREATE TABLE `newevent` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `host` varchar(128) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `triggerid` bigint(20) unsigned NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `priority` int(11) NOT NULL DEFAULT '0',
  `value` int(11) NOT NULL DEFAULT '0',
  `time` datetime DEFAULT NULL,
   primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

触发器创建如下:

DELIMITER $$
DROP TRIGGER IF EXISTS after_insert_on_event;
CREATE TRIGGER after_insert_on_event
AFTER INSERT ON zabbix.`events`
FOR EACH ROW
BEGIN
    INSERT INTO report.newevent (
        report.newevent.host,
        report.newevent.triggerid,
        report.newevent.description,
        report.newevent.priority,
        report.newevent.value,
        report.newevent.time
    )
    SELECT
        zabbix.`hosts`.`host`,
        zabbix.`triggers`.triggerid,
        zabbix.`triggers`.description,
        zabbix.`triggers`.priority,
        zabbix.`events`.`value`,
        FROM_UNIXTIME(zabbix.`events`.clock)
    FROM
        zabbix.`hosts`,
        zabbix.`triggers`,
        zabbix.`events`,
        zabbix.items,
        zabbix.functions,
        zabbix.groups,
        zabbix.hosts_groups
    WHERE
        zabbix.`hosts`.hostid = zabbix.hosts_groups.hostid
        AND zabbix.hosts_groups.groupid = zabbix.groups.groupid
        AND zabbix.`triggers`.triggerid = zabbix.`events`.objectid
        AND zabbix.`hosts`.hostid = zabbix.items.hostid
        AND zabbix.items.itemid = zabbix.functions.itemid
        AND zabbix.functions.triggerid = zabbix.`triggers`.triggerid
        AND zabbix.`events`.eventid=new.eventid;
END;
$$
DELIMITER ;

注,这个新的事件表同样也可以创建在zabbix库内,这里单独又建一个库的目的主要是为了后期定制开发及和其他平台对接的需要。后续只要event表中每新增一条数据,对应的数据就会在新的表中增加。

四、待解决问题及其他

1、备库触发器问题

最早的设计是将mysql 的这个触发器和新库建在备库上,不过发现在备库上创建完成后,newevent表中并没有数据,在网上也查到过主备库同步,备库触发器不生效的问题。网上给的解释是由于主备库之间的同步模式为mixed或row级时,就会出现备库上不捕获inster这种操作的情况。改成基于sql 语句同步的方式会解决,不过发现更改为基于sql 语句后,也不生效。

不重启数据库,通过修改变量修改sql 模式的语名如下:

SET GLOBAL binlog_format = 'STATEMENT';

mysql同步复制的三种模式如下:

-- 基于SQL语句的复制(statement-based replication, SBR),
-- 基于行的复制(row-based replication, RBR),
-- 混合模式复制(mixed-based replication, MBR)。

具体三者之间的优缺点比对可以参看csdn上的一篇博文 --- MYSQL复制的几种模式(http://blog.csdn.net/adparking/article/details/7586054) 。

还有提到和mysql 事务隔离级别相关的,关于事务隔离级别部分的知识可以参看这篇博文 --- MySQL数据库事务隔离级别(http://blog.csdn.net/jiangwei0910410003/article/details/24960785) 。

2、其他

如果想基于老的想要后期查询或改档用,并且同时又想保证查询的速度,可以对历史的newevent做一个归档,比如,select每三个月的数据将其保存另一个带日志的表中。再清空该表的数据,重新接受触发数据库写入。

Zabbix使用Pycurl模块监控web页面状态

由于网络的问题,zabbix自带web模块用不了,后台研发2b,老是更新正式环境安装包,导致一直出问题,老是给他们擦屁股,早说过这事,他们不配合,现在出问题了,挺爽,这锅我表示不背,就找了pycurl这个模块写个监控。

pycurl模块用法:

(这块是抄的,引用地址:http://blog.csdn.net/xsj_blog/article/details/52102652)

c = pycurl.Curl()    #创建一个curl对象 
c.setopt(pycurl.CONNECTTIMEOUT, 5)    #连接的等待时间,设置为0则不等待  
c.setopt(pycurl.TIMEOUT, 5)           #请求超时时间  
c.setopt(pycurl.NOPROGRESS, 0)        #是否屏蔽下载进度条,非0则屏蔽  
c.setopt(pycurl.MAXREDIRS, 5)         #指定HTTP重定向的最大数  
c.setopt(pycurl.FORBID_REUSE, 1)      #完成交互后强制断开连接,不重用  
c.setopt(pycurl.FRESH_CONNECT,1)      #强制获取新的连接,即替代缓存中的连接  
c.setopt(pycurl.DNS_CACHE_TIMEOUT,60) #设置保存DNS信息的时间,默认为120秒  
c.setopt(pycurl.URL,"http://www.baidu.com")      #指定请求的URL  
c.setopt(pycurl.USERAGENT,"Mozilla/5.2 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50324)")    #配置请求HTTP头的User-Agent
c.setopt(pycurl.HEADERFUNCTION, getheader)   #将返回的HTTP HEADER定向到回调函数getheader
c.setopt(pycurl.WRITEFUNCTION, getbody)      #将返回的内容定向到回调函数getbody
c.setopt(pycurl.WRITEHEADER, fileobj)        #将返回的HTTP HEADER定向到fileobj文件对象
c.setopt(pycurl.WRITEDATA, fileobj)          #将返回的HTML内容定向到fileobj文件对象
c.getinfo(pycurl.HTTP_CODE)         #返回的HTTP状态码
c.getinfo(pycurl.TOTAL_TIME)        #传输结束所消耗的总时间
c.getinfo(pycurl.NAMELOOKUP_TIME)   #DNS解析所消耗的时间
c.getinfo(pycurl.CONNECT_TIME)      #建立连接所消耗的时间
c.getinfo(pycurl.PRETRANSFER_TIME)  #从建立连接到准备传输所消耗的时间
c.getinfo(pycurl.STARTTRANSFER_TIME)    #从建立连接到传输开始消耗的时间
c.getinfo(pycurl.REDIRECT_TIME)     #重定向所消耗的时间
c.getinfo(pycurl.SIZE_UPLOAD)       #上传数据包大小
c.getinfo(pycurl.SIZE_DOWNLOAD)     #下载数据包大小 
c.getinfo(pycurl.SPEED_DOWNLOAD)    #平均下载速度
c.getinfo(pycurl.SPEED_UPLOAD)      #平均上传速度
c.getinfo(pycurl.HEADER_SIZE)       #HTTP头部大小

代码如下:

#!/usr/bin/env python
# __*__coding:utf8__*__
#Author:wangpengtai
#Blog:http://wangpengtai.blog.51cto.com/
import pycurl
import sys
import StringIO #引用该模块的原因是:使用pycurl后会打印出页面内容,我们不需要看到这个内容,只需要获取页面反馈信息就行了,只能将其写入缓存中,目前没找到好办法,学艺不精,不会使用重定向写到os.devnull中,无奈初次下策。。。
#开始使用的是写入临时文件,但是会有权限问题,导致zabbix无法获取到数据。
class WebStatus(object):
    def __init__(self, url):
        self.url = url
        self.curl = pycurl.Curl()
        self.string = StringIO.StringIO()
        # 连接等待时间,0则不等待
        self.curl.setopt(pycurl.CONNECTTIMEOUT, 5)
        # 超时时间
        self.curl.setopt(pycurl.TIMEOUT, 5)
        # 下载进度条,非0则屏蔽
        self.curl.setopt(pycurl.NOPROGRESS, 1)
        # 指定HTTP重定向最大次数
        self.curl.setopt(pycurl.MAXREDIRS, 5)
        # 完成交互后强制断开连接,不重用
        self.curl.setopt(pycurl.FORBID_REUSE, 1)
        # 设置DNS信息保存时间,默认为120秒
        self.curl.setopt(pycurl.DNS_CACHE_TIMEOUT, 60)
        # 设置请求的Url
        self.curl.setopt(pycurl.URL, self.url)
        self.curl.setopt(pycurl.WRITEFUNCTION, self.string.write)#将页面内容写入缓存
        self.curl.perform()
    def request_value(self):
        data = {
            "Http_code": self.curl.getinfo(pycurl.HTTP_CODE),
            "Speed_download": self.curl.getinfo(pycurl.SPEED_DOWNLOAD),
            "Connect_time": self.curl.getinfo(pycurl.CONNECT_TIME),
            "Total_time": self.curl.getinfo(pycurl.TOTAL_TIME),
            "Dnslookup_time": self.curl.getinfo(pycurl.NAMELOOKUP_TIME),
            "Redirect_time": self.curl.getinfo(pycurl.REDIRECT_TIME),
            "Redirect_count": self.curl.getinfo(pycurl.REDIRECT_COUNT)
        }
        return data
    def __end__(self):  #释放内存和连接,做一个有始有终,有责任心的运维狗
        self.string.close()
        self.curl.close()
if __name__ == "__main__":
    Usage = """
Usage: python web_monitor.py url [Http_code|Speed_download|Connect_time|Total_time|Dnslookup_time|Redirect_time|Redirect_count]
    """
    try:
        url = sys.argv[1]
        request = sys.argv[2]
        try:
            s = WebStatus(url)
            try:
                print s.request_value()[request]
            except KeyError:
                print "Make sure 2nd argument is right!"
        except pycurl.error:
            print "Make sure the url is right or reachable!"
    except IndexError:
        print "Must be 2 arguments given!%s" % Usage

验证:www.baidu.com一直是我测(攻)试(击)的对象

未分类

一、配置zabbix自定义监控

这个相对来说比较灵活,可以找一台机器专门用来做监控,只需要在这台机器上配置以下内容就可以监控多个URL了。

zabbix界面中可以配置一个模版,将其挂在该机器上就行了。

1、将代码写到下面目录下并加上可执行权限

[root@zabbix-12-195 scripts]# pwd
/etc/zabbix/scripts
[root@zabbix-12-195 scripts]# vim web_monitor.py 
[root@zabbix-12-195 scripts]# chmod +x web_monitor.py

2、配置zabbix_agentd.conf

[root@zabbix-12-195 scripts]# cat /etc/zabbix_agentd.conf
UserParameter=web[*],/etc/zabbix/scripts/web_monitor.py $1 $2

3、重启zabbix-agentd

[root@zabbix-12-195 scripts]# service zabbix-agentd restart

二、配置zabbix监控

直接上图了,后续的添加就自由发挥了,好多返回值可以出图,可以做触发器告警等。不多叙述了。

未分类

未分类

未分类

CentOS 7.2安装配置zabbix 3.0 LTS

1、zabbix简介

  
zabbix(音同 zæbix)是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案。
  
zabbix能监视各种网络参数,保证服务器系统的安全运营;并提供灵活的通知机制以让系统管理员快速定位/解决存在的各种问题。
  
zabbix由2部分构成,zabbix server与可选组件zabbix agent。
  
zabbix server可以通过SNMP,zabbix agent,ping,端口监视等方法提供对远程服务器/网络状态的监视,数据收集等功能,它可以运行在Linux,Solaris,HP-UX,AIX,Free BSD,Open BSD,OS X等平台上。

更多详细信息请访问zabbix官网:https://www.zabbix.com/

2、zabbix版本选择

企业使用建议选择zabbix的LTS版本(Long Time Support),尝鲜的可以选择官方的最新版本。

3、zabbix安装

本篇随笔基于CentOS 7.2编写。适用于CentOS 7所有版本及RedHat系列。
  
官方yum源:http://repo.zabbix.com/zabbix/3.0/rhel/7/x86_64/zabbix-release-3.0-1.el7.noarch.rpm
  
阿里云yum源:https://mirrors.aliyun.com/zabbix/zabbix/3.0/rhel/7/x86_64/zabbix-release-3.0-1.el7.noarch.rpm
  
安装官方的yum源

[root@zabbix-server ~]# rpm -ivh http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
Retrieving http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm
warning: /var/tmp/rpm-tmp.PutPhp: Header V4 RSA/SHA512 Signature, key ID a14fe591: NOKEY
Preparing...                          ################################# [100%]
Updating / installing...
   1:zabbix-release-3.2-1.el7         ################################# [100%]
[root@zabbix-server ~]#

  
查看都安装了什么

[root@zabbix-server ~]# rpm -ql zabbix-release
/etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX
/etc/yum.repos.d/zabbix.repo
/usr/share/doc/zabbix-release-3.0
/usr/share/doc/zabbix-release-3.0/GPL
[root@zabbix-server ~]#

  
安装zabbix及其他必须的软件

[root@zabbix-server ~]# yum install -y zabbix-server-mysql zabbix-web-mysql

  
由于CentOS 7比较特殊,MySQL已经没了,只能安装mariadb:

[root@zabbix-server ~]# yum install -y mariadb-server

启动并设置开机自启动数据库

[root@zabbix-server bin]# systemctl enable mariadb.service
Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb.service to /usr/lib/systemd/system/mariadb.service.
[root@zabbix-server bin]# systemctl start mariadb.service
[root@zabbix-server bin]#

  
初始化数据库

[root@zabbix-server ~]# find / -type f -name "mysql_secure_installation"
/usr/bin/mysql_secure_installation    #mariadb数据库自带的初始化脚本
[root@zabbix-server ~]#
[root@zabbix-server bin]# mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none):
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.
Set root password? [Y/n] y
New password:    #123456
Re-enter new password:    #123456
Password updated successfully!
Reloading privilege tables..
... Success!
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] y
... Success!
Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] y
... Success!
By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] y
... Success!
Cleaning up...
All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!
[root@zabbix-server bin]#

  
创建zabbix数据库

[root@zabbix-server ~]# mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or g.
Your MariaDB connection id is 10
Server version: 5.5.52-MariaDB MariaDB Server
Copyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
MariaDB [(none)]> create database zabbix character set utf8 collate utf8_bin;
Query OK, 1 row affected (0.01 sec)
MariaDB [(none)]> grant all privileges on zabbix.* to zabbix@localhost identified by '123456';
Query OK, 0 rows affected (0.00 sec)
MariaDB [(none)]> q
Bye
[root@zabbix-server ~]#

  
导入zabbix库的数据

[root@zabbix-server ~]# ll /usr/share/doc/zabbix-server-mysql-3.2.7/create.sql.gz
-rw-r--r-- 1 root root 1161488 Jul 19 00:09 /usr/share/doc/zabbix-server-mysql-3.2.7/create.sql.gz
[root@zabbix-server ~]# zcat /usr/share/doc/zabbix-server-mysql-3.2.7/create.sql.gz|mysql -uzabbix -p zabbix
Enter password:
[root@zabbix-server ~]# mysql -uzabbix -p123456 -e "use zabbix;show tables;"
+----------------------------+
| Tables_in_zabbix           |
+----------------------------+
| acknowledges               |
| actions                    |
| alerts                     |
| application_discovery      |
| application_prototype      |
| application_template       |
| applications               |
| auditlog                   |
| auditlog_details           |
| autoreg_host               |
| conditions                 |
| config                     |
| corr_condition             |
| corr_condition_group       |
| corr_condition_tag         |
| corr_condition_tagpair     |
| corr_condition_tagvalue    |
| corr_operation             |
| correlation                |
| dbversion                  |
| dchecks                    |
| dhosts                     |
| drules                     |
| dservices                  |
| escalations                |
| event_recovery             |
| event_tag                  |
| events                     |
| expressions                |
| functions                  |
| globalmacro                |
| globalvars                 |
| graph_discovery            |
| graph_theme                |
| graphs                     |
| graphs_items               |
| group_discovery            |
| group_prototype            |
| groups                     |
| history                    |
| history_log                |
| history_str                |
| history_text               |
| history_uint               |
| host_discovery             |
| host_inventory             |
| hostmacro                  |
| hosts                      |
| hosts_groups               |
| hosts_templates            |
| housekeeper                |
| httpstep                   |
| httpstepitem               |
| httptest                   |
| httptestitem               |
| icon_map                   |
| icon_mapping               |
| ids                        |
| images                     |
| interface                  |
| interface_discovery        |
| item_application_prototype |
| item_condition             |
| item_discovery             |
| items                      |
| items_applications         |
| maintenances               |
| maintenances_groups        |
| maintenances_hosts         |
| maintenances_windows       |
| mappings                   |
| media                      |
| media_type                 |
| opcommand                  |
| opcommand_grp              |
| opcommand_hst              |
| opconditions               |
| operations                 |
| opgroup                    |
| opinventory                |
| opmessage                  |
| opmessage_grp              |
| opmessage_usr              |
| optemplate                 |
| problem                    |
| problem_tag                |
| profiles                   |
| proxy_autoreg_host         |
| proxy_dhistory             |
| proxy_history              |
| regexps                    |
| rights                     |
| screen_user                |
| screen_usrgrp              |
| screens                    |
| screens_items              |
| scripts                    |
| service_alarms             |
| services                   |
| services_links             |
| services_times             |
| sessions                   |
| slides                     |
| slideshow_user             |
| slideshow_usrgrp           |
| slideshows                 |
| sysmap_element_url         |
| sysmap_url                 |
| sysmap_user                |
| sysmap_usrgrp              |
| sysmaps                    |
| sysmaps_elements           |
| sysmaps_link_triggers      |
| sysmaps_links              |
| task                       |
| task_close_problem         |
| timeperiods                |
| trends                     |
| trends_uint                |
| trigger_depends            |
| trigger_discovery          |
| trigger_tag                |
| triggers                   |
| users                      |
| users_groups               |
| usrgrp                     |
| valuemaps                  |
+----------------------------+
[root@zabbix-server ~]#

修改zabbix-server配置文件

[root@zabbix-server ~]# vim /etc/zabbix/zabbix_server.conf
# This is a configuration file for Zabbix server daemon
# To get more information about Zabbix, visit http://www.zabbix.com
############ GENERAL PARAMETERS #################
### Option: ListenPort
#       Listen port for trapper.
#
# Mandatory: no
# Range: 1024-32767
# Default:
# ListenPort=10051
### Option: SourceIP
#       Source IP address for outgoing connections.
#
# Mandatory: no
# Default:
# SourceIP=
### Option: LogType
#       Specifies where log messages are written to:
#               system  - syslog
#               file    - file specified with LogFile parameter
#               console - standard output
#
# Mandatory: no
# Default:
# LogType=file
### Option: LogFile
#       Log file name for LogType 'file' parameter.
#
# Mandatory: no
# Default:
# LogFile=
LogFile=/var/log/zabbix/zabbix_server.log
### Option: LogFileSize
#       Maximum size of log file in MB.
#       0 - disable automatic log rotation.
/DBHost
#       1 - critical information
#       2 - error information
#       3 - warnings
#       4 - for debugging (produces lots of information)
#       5 - extended debugging (produces even more information)
#
# Mandatory: no
# Range: 0-5
# Default:
# DebugLevel=3
### Option: PidFile
#       Name of PID file.
#
# Mandatory: no
# Default:
# PidFile=/tmp/zabbix_server.pid
PidFile=/var/run/zabbix/zabbix_server.pid
### Option: DBHost
#       Database host name.
#       If set to localhost, socket is used for MySQL.
#       If set to empty string, socket is used for PostgreSQL.
#
# Mandatory: no
# Default:
# DBHost=localhost
### Option: DBName
#       Database name.
#       For SQLite3 path to database file must be provided. DBUser and DBPassword are ignored.
#
# Mandatory: yes
# Default:
# DBName=
DBName=zabbix
### Option: DBSchema
#       Schema name. Used for IBM DB2 and PostgreSQL.
#
# Mandatory: no
# Default:
# DBSchema=
### Option: DBUser
#       Database user. Ignored for SQLite.
#
# Mandatory: no
# Default:
# DBUser=
DBUser=zabbix
### Option: DBPassword
#       Database password. Ignored for SQLite.
#       Comment this line if no password is used.
#
# Mandatory: no
# Default:
# DBPassword=
DBPassword=123456
### Option: DBSocket
#       Path to MySQL socket.
#
# Mandatory: no
# Default:
# DBSocket=/tmp/mysql.sock
### Option: DBPort
"/etc/zabbix/zabbix_server.conf" 642L, 14894C written                                                  
[root@zabbix-server ~]#

  
启动zabbix-server服务

[root@zabbix-server ~]# systemctl start zabbix-server
[root@zabbix-server ~]# systemctl enable zabbix-server
Created symlink from /etc/systemd/system/multi-user.target.wants/zabbix-server.service to /usr/lib/systemd/system/zabbix-server.service.
[root@zabbix-server ~]#

设置正确的时区

[root@zabbix-server conf.d]# vim /etc/httpd/conf.d/zabbix.conf
#
# Zabbix monitoring system php web frontend
#
Alias /zabbix /usr/share/zabbix
<Directory "/usr/share/zabbix">
    Options FollowSymLinks
    AllowOverride None
    Require all granted
    <IfModule mod_php5.c>
        php_value max_execution_time 300
        php_value memory_limit 128M
        php_value post_max_size 16M
        php_value upload_max_filesize 2M
        php_value max_input_time 300
        php_value always_populate_raw_post_data -1
        php_value date.timezone Asia/Shanghai
    </IfModule>
</Directory>
<Directory "/usr/share/zabbix/conf">
    Require all denied
</Directory>
<Directory "/usr/share/zabbix/app">
    Require all denied
</Directory>
<Directory "/usr/share/zabbix/include">
    Require all denied
</Directory>
<Directory "/usr/share/zabbix/local">
    Require all denied
</Directory>
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
~                                                                                                                        
"zabbix.conf" 37L, 831C written                                                                        
[root@zabbix-server conf.d]#

启动httpd

[root@zabbix-server conf.d]# systemctl start httpd
[root@zabbix-server conf.d]# systemctl enable httpd
Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service.
[root@zabbix-server conf.d]#

浏览器访问:http://10.0.0.11/zabbix

未分类  

web界面会自动检查所有的条件是否满足,未满足的会提示。
  
未分类

配置数据库连接
  
未分类

默认不需要修改,只需要自己随便设置一个name就可以了。

未分类

所有的设置信息全部显示,可以查看校验是否有误

未分类

成功界面,显示成功安装zabbix,并告知配置文件及路径

未分类

登录界面,默认用户名Admin,默认密码zabbix。

未分类

登陆之后,进入zabbix监控页

未分类

zabbix3.0之后,默认支持中文显示,修改成中文步骤如下

未分类

中文显示界面如下

未分类

zabbix-agent客户端安装

[root@zabbix-server~]# yum install -y zabbix-get zabbix-agent    #其中zabbix-agent负责数据收集,zabbix-get是一个server端模拟数据收集的命令,常用语部署自定义监控前的测试工具

  
启动zabbix-agent

[root@zabbix-server conf.d]# systemctl start zabbix-agent.service
[root@zabbix-server conf.d]# systemctl enable zabbix-agent.service
Created symlink from /etc/systemd/system/multi-user.target.wants/zabbix-agent.service to /usr/lib/systemd/system/zabbix-agent.service.

  
检查

[root@zabbix-server conf.d]# netstat -lnutp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      4398/mysqld         
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1465/sshd           
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1774/master         
tcp        0      0 0.0.0.0:10050           0.0.0.0:*               LISTEN      5293/zabbix_agentd  
tcp        0      0 0.0.0.0:10051           0.0.0.0:*               LISTEN      4538/zabbix_server  
tcp6       0      0 :::80                   :::*                    LISTEN      4685/httpd          
tcp6       0      0 :::22                   :::*                    LISTEN      1465/sshd           
tcp6       0      0 ::1:25                  :::*                    LISTEN      1774/master         
tcp6       0      0 :::10050                :::*                    LISTEN      5293/zabbix_agentd  
tcp6       0      0 :::10051                :::*                    LISTEN      4538/zabbix_server  
udp        0      0 127.0.0.1:323           0.0.0.0:*                           3293/chronyd        
udp6       0      0 ::1:323                 :::*                                3293/chronyd        
[root@zabbix-server conf.d]#

zabbix监控Memcached状态

一、安装 memcached

# yum -y installlibevent libevent-devel

#wget http://memcached.org/files/memcached-1.5.0.tar.gz

#tar -zxvf memcached-1.5.0.tar.gz

#cd memcached-1.5.0/

#./configure --with-libevent=/usr/

# make && make install

二、监控端配置

#启动memcached

#/usr/local/bin/memcached -d -m 128 -l 192.168.1.207 -p 11211 -u root



#配置zabbix-agent

# vi/etc/zabbix/zabbix_agentd.conf

PidFile=/var/run/zabbix/zabbix_agentd.pid

LogFile=/var/log/zabbix/zabbix_agentd.log

LogFileSize=0

Server=192.168.1.208

Hostname=192.168.1.207

Include=/etc/zabbix/zabbix_agentd.d/*.conf

UnsafeUserParameters=1



# vi/etc/zabbix/zabbix_agentd.d/userparameter_memcached.conf

UserParameter=memcached_stats[*],(echostats; sleep 1) | telnet 192.168.1.207 $1 2>&1 | awk '/STAT $2 / {print$NF}'



# systemctl start zabbix-agent



# Server端手动测试

#zabbix_get -s 192.168.1.207 -p 10050 -k'memcached_stats[11211,accepting_conns]'

三、WEB端配置

上传模板

模板下载地址:
http://download.csdn.net/detail/m0_37313242/9920278

未分类

配置Zabbix监控MySQL详细教程

一、Server端安装

机器 192.168.94.78

1、创建mysql实例

机器:192.168.94.78
目录:/data/mysql6001

2、建立系统用户

[[email protected] zabbix_agent]# groupadd  -g 201 zabbix
[[email protected] zabbix_agent]# useradd -g zabbix -u 201 -m zabbix
[[email protected] zabbix_agent]# passwd zabbix

3、创建zabbix数据库

[[email protected] zabbix]# mysql6001
mysql> create database zabbix; 
Query OK, 1 row affected (0.00 sec)

mysql>  grant all on zabbix.* to zabbix@'%' identified by 'zabbix'; 
Query OK, 0 rows affected (0.00 sec)

mysql>  flush privileges;  
Query OK, 0 rows affected (0.00 sec)

4、上传zabbix包到server端机器

zabbix-2.4.4.tar.gz
解压
tar zxvf zabbix-2.4.4.tar.gz 
目录:zabbix-2.4.4

5、导入SQL

cd /data/zabbix/zabbix-2.4.4/database/mysql/
注:有顺序的
[[email protected] mysql]# mysql6001 zabbix < schema.sql 
[[email protected] mysql]# mysql6001 zabbix < images.sql 
[[email protected] mysql]# mysql6001 zabbix < data.sql 

6、导入网页

安装软件包

[[email protected] mysql]# yum -y  install curl curl-devel net-snmp net-snmp-devel perl-DBI php-gd php-xml php-bcmath
[[email protected] mysql]#yum -y install php 
[[email protected] mysql]#yum -y install httpd

[[email protected] html]# mkdir  /var/www/html/zabbix
[[email protected] html]# cp -a /data/zabbix/zabbix-2.4.4/frontends/php/*     /var/www/html/zabbix/
[[email protected] html]# chown -R  apache.apache /var/www/html/zabbix/

7、安装zabbix服务端

[[email protected] zabbix-2.4.4]# cd /data/zabbix/zabbix-2.4.4
[[email protected] zabbix-2.4.4]#  ./configure --prefix=/usr/local/zabbix --enable-server --enable-agent --enable-proxy --with-mysql=/usr/local/mysql5.5/bin/mysql_config --with-net-snmp --with-libcurl

第二步:make
第三步:make install

修改 vi /etc/services,添加下面几行

zabbix-agent    10050/tcp               #zabbix agent
zabbix-agent    10050/udp               #zabbix agent
zabbix-trapper  10051/tcp               #zabbix trapper
zabbix-trapper  10051/udp               #zabbix trapper

8、修改zabbix的配置:

[[email protected] zabbix-2.4.4]# vi /usr/local/zabbix/etc/zabbix_server.conf
[[email protected] zabbix-2.4.4]# cat /usr/local/zabbix/etc/zabbix_server.conf|grep -v ^# | grep -v ^$
LogFile=/data/zabbix/zabbix_server.log
PidFile=/data/zabbix/zabbix_server.pid
DBHost=192.168.94.78
DBName=zabbix
DBUser=zabbix
DBPassword=zabbix
DBSocket=/tmp/mysql.sock
DBPort=6001
StartPollers=20
StartTrappers=15
 StartPingers=10
User=zabbix

[root@localhost ~]# vi /etc/init.d/zabbix_server

BASEDIR=/usr/local/zabbix   ##########修改这行

[root@localhost ~]# vi /etc/init.d/zabbix_agentd

BASEDIR=/usr/local/zabbix   ##########修改这行

9、修改httpd配置

[[email protected] zabbix-2.4.4]# vi /etc/httpd/conf/httpd.conf 
ServerName 127.0.0.1
<VirtualHost *:80>
 DocumentRoot  "/var/www/html"
 ServerName 192.168.94.78
</VirtualHost>

10、开启httpd

[[email protected] core]# service httpd restart
Stopping httpd: [  OK  ]
Starting httpd: httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
[  OK  ]

[[email protected] core]# lsof -i:80
COMMAND   PID   USER   FD   TYPE     DEVICE SIZE/OFF NODE NAME
httpd   23923   root    4u  IPv4 2582967064      0t0  TCP *:80(LISTEN)
httpd   23925 apache    4u  IPv4 2582967064      0t0  TCP *:80 (LISTEN)
httpd   23926 apache    4u  IPv4 2582967064      0t0  TCP *:80 (LISTEN)
httpd   23927 apache    4u  IPv4 2582967064      0t0  TCP *:80 (LISTEN)
httpd   23928 apache    4u  IPv4 2582967064      0t0  TCP *:80 (LISTEN)
httpd   23929 apache    4u  IPv4 2582967064      0t0  TCP *:80 (LISTEN)
httpd   23930 apache    4u  IPv4 2582967064      0t0  TCP *:80 (LISTEN)
httpd   23931 apache    4u  IPv4 2582967064      0t0  TCP *:80 (LISTEN)
httpd   23932 apache    4u  IPv4 2582967064      0t0  TCP *:80 (LISTEN)

11、做几个软连接

[root@localhost ~]# ln -s /usr/local/zabbix/bin/* /usr/bin/
[root@localhost ~]# ln -s /usr/local/zabbix/sbin/* /usr/sbin/

[root@localhost ~]# cd  /data/zabbix/zabbix-2.4.4/misc/init.d/fedora/core

[root@localhost ~]# cp * /etc/init.d/

12、开启zabbix server端

[[email protected] subsys]# chown zabbix.zabbix   /var/lock/subsys/ -R
[[email protected] subsys]# chown zabbix.zabbix   /usr/local/zabbix  -R
[[email protected] subsys]# chown zabbix.zabbix  /data/zabbix/  -R

[[email protected] core]# /etc/init.d/zabbix_agentd start
Starting zabbix_agentd:  zabbix_agentd [24613]: user zabbix does not exist
zabbix_agentd [24613]: cannot run as root!
[FAILED]
[[email protected] core]# /etc/init.d/zabbix_server start
Starting zabbix_server:  zabbix_server [24821]: user zabbix does not exist
zabbix_server [24821]: cannot run as root!
[FAILED]

处理失败:
[[email protected] home]#  vi /etc/passwd 
改成:
zabbix:x:505:498::/home/zabbix:/bin/bash
[[email protected] home]# su - zabbix

===============================================
[zabbix_linux@bjs-dbmypacket3301 ~]$  /etc/init.d/zabbix_agentd restart
Shutting down zabbix_agentd: [  OK  ]
Starting zabbix_agentd:  [  OK  ]

[zabbix_linux@bjs-dbmypacket3301 ~]$  /etc/init.d/zabbix_server stop
Shutting down zabbix_server: [  OK  ]
[zabbix_linux@bjs-dbmypacket3301 ~]$  /etc/init.d/zabbix_server start
Starting zabbix_server:  [  OK  ]

13、页面设置zabbix

http://192.168.94.78/zabbix/setup.php

未分类

zabbix PHP mbstring.func_overload 报错

修复方法:

vi /etc/php.ini
mbstring.func_overload=off
lways_populate_raw_post_data=1
 重启httpd与zabbix
[[email protected] html]# service httpd restart
[zabbix@bjs-dbmypacket3301 ~]$ /etc/init.d/zabbix_server restart

未分类

未分类

未分类

未分类

未分类

未分类

未分类

二、客户端安装

客户端机器

192.168.94.144
192.168.94.137

1、安装agent

[[email protected] zabbix]# scp zabbix-2.4.4.tar.gz 192.168.94.144:/data/zabbix_agent/

[[email protected] zabbix_agent]# groupadd  -g 201 zabbix
[[email protected] zabbix_agent]# useradd -g zabbix -u 201 -m zabbix
[[email protected] zabbix_agent]# passwd zabbix
Changing password for user zabbix.
New password: 
BAD PASSWORD: it is based on a dictionary word
BAD PASSWORD: is too simple
Retype new password: 
passwd: all authentication tokens updated successfully.
 [[email protected] zabbix-2.4.4]# cd /data/zabbix_agent/zabbix-2.4.4
 [[email protected] zabbix-2.4.4]#  ./configure --prefix=/usr/local/zabbix  --enable-agent --enable-proxy --with-mysql=/usr/local/mysql5.5/bin/mysql_config 

[[email protected] zabbix-2.4.4]# make && make install 

2、拷贝/创建快捷

[[email protected] zabbix-2.4.4]# pwd
/data/zabbix_agent/zabbix-2.4.4
[[email protected] zabbix-2.4.4]# cp misc/init.d/tru64/zabbix_agentd   /etc/init.d/
[[email protected] zabbix-2.4.4]# chmod +x /etc/init.d/zabbix_agentd
3、修改配置文件
[[email protected] zabbix-2.4.4]# vi  /usr/local/zabbix/etc/zabbix_agentd.conf

[[email protected] zabbix-2.4.4]# cat /usr/local/zabbix/etc/zabbix_agentd.conf | grep -v ^# | grep -v ^$
LogFile=/data/zabbix_agent/zabbix_agentd.log
UnsafeUserParameters=1                   
Include= /usr/local/zabbix/etc/zabbix_agentd.conf.d/
Server=192.168.94.78      #server端IP
ServerActive=192.168.94.78   #server端IP
Hostname=192.168.94.144     #客户端IP

4、开启zabbix 的agent

[[email protected] zabbix-2.4.4]# chown zabbix.zabbix /data/zabbix_agent/ -R
[[email protected] zabbix-2.4.4]# chown zabbix.zabbix /usr/local/zabbix/  -R
[[email protected] zabbix-2.4.4]# chown zabbix.zabbix /soft/mysqlmonitor/port_6190 -R


[[email protected] tmp]# /usr/local/zabbix/sbin/zabbix_agentd -c /usr/local/zabbix/etc/zabbix_agentd.conf
[[email protected] tmp]# ps -ef|grep zabbix
zabbix   53114     1  0 16:14 ?        00:00:00 /usr/local/zabbix/sbin/zabbix_agentd -c /usr/local/zabbix/etc/zabbix_agentd.conf
zabbix   53115 53114  0 16:14 ?        00:00:00 /usr/local/zabbix/sbin/zabbix_agentd: collector [idle 1 sec]                    
zabbix   53116 53114  0 16:14 ?        00:00:00 /usr/local/zabbix/sbin/zabbix_agentd: listener #1 [waiting for connection]      
zabbix   53117 53114  0 16:14 ?        00:00:00 /usr/local/zabbix/sbin/zabbix_agentd: listener #2 [waiting for connection]      
zabbix   53118 53114  0 16:14 ?        00:00:00 /usr/local/zabbix/sbin/zabbix_agentd: listener #3 [waiting for connection]      
zabbix   53119 53114  0 16:14 ?        00:00:00 /usr/local/zabbix/sbin/zabbix_agentd: active checks #1 [idle 1 sec]             
root     53362 62129  0 16:14 pts/0    00:00:00 grep zabbix
[[email protected] tmp]# lsof -i:1005COMMAND     PID   USER   FD   TYPE     DEVICE SIZE/OFF NODE NAME
zabbix_ag 53114 zabbix    4u  IPv4 2301997410      0t0  TCP *:zabbix-agent (LISTEN)
zabbix_ag 53115 zabbix    4u  IPv4 2301997410      0t0  TCP *:zabbix-agent (LISTEN)
zabbix_ag 53116 zabbix    4u  IPv4 2301997410      0t0  TCP *:zabbix-agent (LISTEN)
zabbix_ag 53117 zabbix    4u  IPv4 2301997410      0t0  TCP *:zabbix-agent (LISTEN)
zabbix_ag 53118 zabbix    4u  IPv4 2301997410      0t0  TCP *:zabbix-agent (LISTEN)
zabbix_ag 53119 zabbix    4u  IPv4 2301997410      0t0  TCP *:zabbix-agent (LISTEN)

5、界面添加host

此时可以在界面上面添加host进行监控测试了,因后面添加自定义监控,此处忽略

三、自定义监控配置

1、准备检查脚本

准备检查mysql状态的脚本

[[email protected] ~]# cd /soft/port_6190/
[[email protected] port_6190]# ./mysql_status.pl|grep com_writes
com_writes=0

[[email protected] port_6190]# /soft/port_6190/mysql_status.pl |grep com_writes|awk -F '=' '{print $2}'
0

注:此处可以自定义脚本,返回key=value 即可,或者使用percona的模板,此处以自定义监控脚本为例来进行配置监控

2、修改agent的配置文件

[[email protected] port_6190]# vi /usr/local/zabbix/etc/zabbix_agentd.conf

[[email protected] port_6190]# cat /usr/local/zabbix/etc/zabbix_agentd.conf|grep -v '^#'|grep -v '^$'
LogFile=/data/zabbix_agent/zabbix_agentd.log
UnsafeUserParameters=1                   
Include= /usr/local/zabbix/etc/zabbix_agentd.conf.d/
Server=192.168.94.78
ServerActive=192.168.94.78
Hostname=test
 UserParameter=com_writes,/soft/port_6190/mysql_status.pl |grep com_writes|awk -F '=' '{print $2}'
 UserParameter=com_reads,/soft/port_6190/mysql_status.pl  |grep com_reads |awk -F '=' '{print $2}'
 UserParameter=com_update,/soft/port_6190/mysql_status.pl |grep com_update|awk -F '=' '{print $2}'
 UserParameter=com_insert,/soft/port_6190/mysql_status.pl |grep com_insert|awk -F '=' '{print $2}'
 UserParameter=com_delete,/soft/port_6190/mysql_status.pl |grep com_delete|awk -F '=' '{print $2}'

注:com_delet 为键值名,后面为键值的值

重启agent

/etc/init.d/zabbix_agentd stop
/usr/local/zabbix/sbin/zabbix_agentd -c /usr/local/zabbix/etc/zabbix_agentd.conf

3、server端检查

检查

[[email protected] bin]# pwd
/usr/local/zabbix/bin

[[email protected] bin]# ./zabbix_get -s 192.168.94.144 -k com_writes
0

4、server端进行界面配

4.1添加host

未分类

4.2 添加模版

未分类

4.3 创建应用集

未分类

未分类

4.4创建项目

未分类

4.5 创建图形

未分类

未分类

未分类

5、查看监控图

未分类

6、其他过程

未分类

未分类

未分类

未分类

未分类

未分类

未分类

未分类

未分类

未分类

使用zabbix监控apache性能

原理

监控原理跟之前写的监控nginx差不多,都是利用web服务器自身提供的状态信息页获取运行状态信息。apache的监控状态信息如下:

Total Accesses: 252523

Total kBytes: 2154830

CPULoad: 2.72004

Uptime: 16624

ReqPerSec: 15.1903

BytesPerSec: 132733

BytesPerReq: 8738

BusyWorkers: 1

IdleWorkers: 9

Scoreboard: 

我们一般只需要这四个数据:ReqPerSec、BytesPerSec、BusyWorkers、IdleWorkers

开启apache status

创建状态页配置文件/etc/httpd/conf.d/status.conf

Listen 89
<VirtualHost *:89>
    CustomLog /dev/null common
    ErrorLog /dev/null
    <Location "/server-status">
        SetHandler server-status
        Require ip 192.168.7.227
    </Location>
</VirtualHost>

CustomLog 和 ErrorLog在这里的作用是将日志写入/dev/null,即关闭咋apache状态页面日志记录。但是CustomLog和ErrorLog指令不能放到Location里,所以就新建一个VirtualHost。

访问http://192.168.7.227:89/server-status?auto即可得到上面的状态信息。我这里测试用的就是zabbix-server安装时自带的apache,所以限定可以访问的IP和apache服务器的IP是同一个。

创建zabbix模板

/etc/zabbix/zabbix_agentd.d/apache_status.sh

#!/bin/bash

URL="http://192.168.7.227:89/server-status?auto"

function ReqPerSec(){
/usr/bin/curl -s $URL |grep ReqPerSec|awk '{print $2}'
}

function BytesPerSec(){
/usr/bin/curl -s $URL |grep BytesPerSec|awk '{print $2}'
}

function BusyWorkers(){
/usr/bin/curl -s $URL |grep BusyWorkers|awk '{print $2}'
}

function IdleWorkers(){
/usr/bin/curl -s $URL |grep IdleWorkers|awk '{print $2}'
}

function ping(){
/usr/sbin/pidof httpd|wc -l
}

#根据脚本参数执行对应函数
$1

/etc/zabbix/zabbix_agentd.d/apache_status.conf
Bash

UserParameter=apache.status[*],/etc/zabbix/zabbix_agentd.d/apache_status.sh $1

重启zabbix-agent后就可以创建apache监控模板了。

items配置都和nginx监控大同小异,特别看下这个带单位的:单位我这里写的Bps,Bytes每秒的意思,但在zabbix中,它会自动帮你换算成KBps:

未分类

并不是说zabbix很聪明知道你这个单位什么意思,它只是简单的除以1000然后加上一个大写“K”在前面而已,加入你的单位是”obe”,那么就显示成了Kobe,哈哈^_^

未分类

再添加3个Graphs,模板就算做完了:

未分类

最后附上版本文件,适用于zabbix-3.2.7-1:https://github.com/dmli30/shell/blob/master/zabbix/apache_status_templates.xml

zabbix通过stub_status模块实现对nginx的监控

原理

nginx的ngx_http_stub_status_module模块提供了基本的nginx状态信息,源码安装的话需要加上–with-http_stub_status_module编译参数,或者如果是epel源yum安装的话,已经默认启用该模块。在nginx.conf的server段中添加:

location /basic_status {
    stub_status;
    access_log off;
}

那么访问http://xxx.com/basic_status就可以得到7个nginx运行信息了:

Active connections: 291 
server accepts handled requests
 16630948 16630948 31070465 
Reading: 6 Writing: 179 Waiting: 106

各项含义摘抄如下:

Active connections  The current number of active client connections including Waiting connections.

accepts  The total number of accepted client connections.

handled  The total number of handled connections. Generally, the parameter value is the same as acceptsunless some resource limits have been reached (for example, the worker_connections limit).

requests  The total number of client requests.

Reading  The current number of connections where nginx is reading the request header.

Writing  The current number of connections where nginx is writing the response back to the client.

Waiting  The current number of idle client connections waiting for a request.

Active connections/Reading/Writing/Waiting 是状态量,体现了nginx当前的运行状态,需要重点关注。

accepts/handled/requests是统计量,是个历史计数器,其中requests可以反映出“吞吐量”的概念,accepts和handled的差值可以反映出“丢包量”,即nginx由于某种原因丢弃的连接。

由此可以看出,zabbix监控nginx就是通过搜集以上数据,并稍作加工,形成图表供分析。

自定义脚本

zabbix可以通过自定义参数收集自定义信息,详见:https://www.zabbix.com/documentation/3.2/manual/config/items/userparameters

首先需要一个脚本,得到所需数据,然后通过zabbix-agent传给zabbix-server。有几点思路:

1、使用shell脚本即可,简单实用,跟操作系统紧密结合。

2、因为有很多监控项,如果写多个脚本会很乱,最好写成函数形式。

3、直接取accepts和handled的值没什么实际意义,它们的差值表示连接丢弃数量才是我们关心的。但是,这个计算不能放在zabbix-server中进行(item type — Calculation),因为zabbix在取两个值的时候有时间差,而这个时间差得到的结果会导致计算误差。所以必须在shell中算好,直接返回给zabbix-server。

ngx_status.sh代码如下:

#!/bin/bash

URL="http://192.168.7.227:88/ngx_status"
FILE="/tmp/ngx_status.txt"

function active(){
/usr/bin/curl -s $URL |grep Active|awk '{print $3}'
}

function reading(){
/usr/bin/curl -s $URL |grep Reading|awk '{print $2}'
}

function writing(){
/usr/bin/curl -s $URL |grep Writing|awk '{print $4}'
}

function waiting(){
/usr/bin/curl -s $URL |grep Waiting|awk '{print $6}'
}

function requests(){
/usr/bin/curl -s $URL |awk '{if(NR==3) print $3}'
}

function dropped(){
/usr/bin/curl -s $URL > $FILE
accepts=`awk '{if(NR==3) print $1}' $FILE`
handled=`awk '{if(NR==3) print $2}' $FILE`
drop=`expr $accepts - $handled`
echo "$drop"
}

function ping(){
/usr/sbin/pidof nginx|wc -l
}

#根据脚本参数执行对应应函数
$1

zabbix-agent端添加以下配置:

# cat /etc/zabbix/zabbix_agentd.d/nginx_status.conf
UserParameter=nginx.status[*],/etc/zabbix/zabbix_agentd.d/nginx_status.sh $1

创建zabbix模版

active/reading/writing/waiting/requests都是一样的,方法如下:

未分类

吞吐量是由计算得出:

未分类

上面使用计算的方法没必要,官方已经提供了内置的delta数据类型来处理此类需求:

未分类

nginx存活状态是个布尔量,创建方法:

未分类

未分类

可以对这个item配置trigger,当nginx挂了做相应操作。

最后,我们可以创建几个图表,方便分析,因为是测试环境,基本没啥访问量^_^:

未分类

模版文件,适用于zabbix-3.2.7-1:https://github.com/dmli30/shell/blob/master/zabbix/ngx_status_templates.xml

Zabbix 3.2.1运行在PHP 7.1.7出现的问题解决

安装完成用admin账号登陆后,出现红色的框框显示这个:

A non well formed numeric value encountered [zabbix.php:21 → require_once() → ZBase->run() → ZBase->processRequest() → CView->getOutput() → include() → make_status_of_zbx() → CFrontendSetup->checkRequirements() → CFrontendSetup->checkPhpMemoryLimit() → str2mem() in include/func.inc.php:410]
A non well formed numeric value encountered [zabbix.php:21 → require_once() → ZBase->run() → ZBase->processRequest() → CView->getOutput() → include() → make_status_of_zbx() → CFrontendSetup->checkRequirements() → CFrontendSetup->checkPhpPostMaxSize() → str2mem() in include/func.inc.php:410]
A non well formed numeric value encountered [zabbix.php:21 → require_once() → ZBase->run() → ZBase->processRequest() → CView->getOutput() → include() → make_status_of_zbx() → CFrontendSetup->checkRequirements() → CFrontendSetup->checkPhpUploadMaxFilesize() → str2mem() in include/func.inc.php:410]

网上查了一下,这是因为PHP 7.1.7类型强化,处理方法是找到Zabbix WEB目录下include/func.inc.php文件,修改它

sed -i '/$last = strtolower(substr($val, -1));/a$val = substr($val,0,-1);' func.inc.php

问题依然未能解决,后来查看了一下func.inc.php代码,跳转到报错的位置#410,通过网上的解决方法分析,应该是val这个变量类型问题,在403行后添加一行$val = substr($val,0,-1); 保存修改后的文件,重新访问zabbix web界面即可。

ZABBIX忘记登录密码重置方法

未分类

刚刚在群里吹牛逼,由于账号比较多,脑子容易瓦特. 结果忘记自己的zabbix登录密码下面是找回登录密码的例子

未修改之前(忘记登录密码)
[root@abcdocker ~]# mysql -uroot -p -e "select * from zabbix.usersG"
Enter password: 
*************************** 1. row ***************************
            userid: 1
             alias: Admin
              name: Zabbix
           surname: Administrator
            passwd: ab66b6e18854fa4d45499d0a04a47b64
               url: 
         autologin: 1
        autologout: 0
              lang: en_GB
           refresh: 30
              type: 3
             theme: default
    attempt_failed: 0
        attempt_ip: 14.130.112.2
     attempt_clock: 1501141026
     rows_per_page: 50

登录MySQL 修改密码

[root@abcdocker ~]# mysql -uroot -p
由于密码是md5加密的,我们可以查看默认的zabbix密码的md5
mysql> use zabbix;
mysql> update users set passwd='5fce1b3e34b520afeffb37ce08c7cd66' where userid='1';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0
解释:5fce1b3e34b520afeffb37ce08c7cd66  = zabbix
因为zabbix默认密码就是zabbix

登录 Web

用户名:Admin
密码:zabbix

未分类

提示:登陆上请马上修改密码

未分类

未分类

完!