目录

Life in Flow

知不知,尚矣;不知知,病矣。
不知不知,殆矣。

X

Zabbix

监控的意义

监视 是指对行为、活动或其他变动中信息的一种持续性关注,通常是为了对人达成影响、管理、指导或保护的目的

  • 监控主机或者架构状态
  • 控制、追责
  • 及时定位故障点,预先扩容(数据分析)

早期 Linux 的监控命令

定时任务 + 脚本

项目 命令
业务 API curl/wget
进程 ps/pstree/pgrep/pidstat/top/htop
CPU top/htop/vmstat/mpstat/cpuinfo/w/uptime/sar
内存 top/free/ps/iotop/vmstat/sar
磁盘 iotop/iostat/sar
网络 iftop(整体带宽使用情况)/nethogs(精确到进程)/nstat/ifstat/mtr/sar
硬件 Megacli(raid)/ipmitool(温度、CPU 风扇转速)/Im_sensors(温度)

监控层次与指标

单台服务

  • 业务信息:程序逻辑(与开发沟通书写一个监控页面)
  • 服务信息:各种服务的进程、端口、状态
  • 系统信息:CPU、mem、io、负载、网络
  • 硬件信息:磁盘、raid 状态、温度、风扇转速、机房温度&湿度

网络集群监控(用户访问流程)

  • DNS 解析与 CDN:通过全军访问测试工具(模仿用户再全国&全球各地访问站点)
    自建不差钱:全国各地(核心城市)、1 台服务器,定时访问你的原站/cdn/dns (对应的服务:smokeping)
    免费:https://www.17ce.com/
    商业:听云、监控宝(警告)
  • TCP 三次握手:网站负载均衡监控 (ss -ant)
  • HTTP 请求报文:监控 Web 日志查状态码、HTTPS 监控过期
  • 请求经过网站架构:nginx(负载均衡) --> Web 服务器 --> 缓存 --> 数据库 --> 存储
  • HTTP 响应报文:监控 Web 日志状态码
  • TCP 四次挥手:网站负载均衡监控 (ss -ant)
  • 断开链接

Zabbix 架构

arch

角色 服务 功能
客户端 zabbix-agent 数据采集
服务端 zabbix-server、zabbix-agent 数据收集、数据分析、报警、存储、ZabbixUI 展示

配置要求

规模 平台 CPU/MEM DB 受监控主机的数量
小型 CentOS Virtual Appliance MySQL InnoDB 100
中型 CentOS 2 CPU cores/2GB MySQL InnoDB 500
大型 RedHat Enterprise 4 CPU cores/8GB RAID10 MySQL InnoDB 或 PostgreSQL >1000
极大型 RedHat Enterprise Linux 8 CPU cores/16GB FAST RAID10 MySQL InnoDB 或 PostgreSQL >10000

角色

角色 主机名 eth0/eth1 配置
zabbix-server zabbixserver 192.168.10.66 1C2G
zabbix-agent web01 192.168.10.61 1C1G
zabbix-agent db01 192.168.10.62 1C1G

安装方式

安装方式
极速全自动 yum
混合安装:yum+ 自定义配置(最佳实践) lnmp(yum)、zabbix-server(yum)、zabbix-web(源码包)
docker
源码编译安装

Zabbix 用户手册 5.0

时间同步

 1# 安装ntp服务
 2yum install ntp 
 3# 开机启动服务
 4systemctl enable ntpd 
 5# 启动服务
 6systemctl start ntpd
 7# 更改时区
 8timedatectl set-timezone Asia/Shanghai
 9# 启用ntp同步
10timedatectl set-ntp yes 
11# 同步时间
12ntpq -p

Zabbix 服务端部署

配置 yum 源为阿里云

  1### 服务端
  2192.168.10.66
  3
  4### nginx (1.20.1-10.el7 )
  5[root@ZabbixServer ~]# yum install nginx -y
  6
  7
  8### php (7.2)
  9[root@ZabbixServer ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
 10# webtatic 要求
 11[root@ZabbixServer ~]# yum install epel-release.noarch -y   
 12[root@ZabbixServer ~]# curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
 13# webtatic源
 14[root@ZabbixServer ~]# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm  
 15[root@ZabbixServer ~]# yum install php72w-cli php72w-fpm php72w-gd php72w-mbstring php72w-bcmath php72w-xml php72w-ldap php72w-mysqlnd -y
 16
 17### 检测nginx、php
 18[root@ZabbixServer ~]# rpm -qa | egrep 'nginx|php72w'
 19nginx-1.20.1-10.el7.x86_64
 20php72w-common-7.2.34-1.w7.x86_64
 21php72w-xml-7.2.34-1.w7.x86_64
 22php72w-mysqlnd-7.2.34-1.w7.x86_64
 23php72w-ldap-7.2.34-1.w7.x86_64
 24php72w-cli-7.2.34-1.w7.x86_64
 25nginx-filesystem-1.20.1-10.el7.noarch
 26php72w-pdo-7.2.34-1.w7.x86_64
 27php72w-gd-7.2.34-1.w7.x86_64
 28php72w-fpm-7.2.34-1.w7.x86_64
 29php72w-bcmath-7.2.34-1.w7.x86_64
 30php72w-mbstring-7.2.34-1.w7.x86_64
 31
 32### nginx、php开机自启动
 33[root@ZabbixServer ~]# systemctl enable nginx php-fpm.service
 34[root@ZabbixServer ~]# systemctl start nginx php-fpm.service
 35
 36### 检查php端口
 37[root@ZabbixServer ~]# ss -lntup | grep 9000
 38tcp    LISTEN     0      128    127.0.0.1:9000                  *:*                   users:(("php-fpm",pid=12059,fd=8),("php-fpm",pid=12058,fd=8),("php-fpm",pid=12057,fd=8),("php-fpm",pid=12056,fd=8),("php-fpm",pid=12055,fd=8),("php-fpm",pid=12052,fd=6))
 39
 40### 配置nginx拦截php请求
 41[root@ZabbixServer ~]# vim /etc/nginx/conf.d/zabbix.confserver {
 42        listen 80;
 43        server_name zabbix.soulboy.com;
 44        root /code/zabbix;
 45        location / {
 46                index index.php;
 47        }
 48        location ~ \.php$ {
 49                fastcgi_pass 127.0.0.1:9000;
 50                fastcgi_index index.php;
 51                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 52                include fastcgi_params;
 53        }
 54}
 55# 检查语法重启
 56[root@ZabbixServer ~]# nginx -t
 57nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
 58nginx: configuration file /etc/nginx/nginx.conf test is successful
 59[root@ZabbixServer ~]# systemctl reload nginx
 60
 61### php配置
 62# 修改nginx用户
 63[root@ZabbixServer ~]# sed -ri '/^(user|group)/s#apache#nginx#g' /etc/php-fpm.d/www.conf
 64[root@ZabbixServer ~]# egrep '^(user|group)' /etc/php-fpm.d/www.conf
 65user = nginx
 66group = nginx
 67
 68# 修改php会话保持目录
 69[root@ZabbixServer ~]# grep 'var/lib/php/session' /etc/php-fpm.d/www.conf
 70php_value[session.save_path]    = /var/lib/php/session
 71[root@ZabbixServer ~]# mkdir -p /var/lib/php/session
 72[root@ZabbixServer ~]# chown nginx.nginx /var/lib/php/session
 73# 检测语法
 74[root@ZabbixServer ~]# php-fpm -t
 75[19-Sep-2023 15:53:53] NOTICE: configuration file /etc/php-fpm.conf test is successful
 76# 启动php
 77[root@ZabbixServer ~]# systemctl reload php-fpm.service
 78
 79### php+nginx测试
 80# 创建web目录
 81[root@ZabbixServer ~]# mkdir -p /code/zabbix
 82[root@ZabbixServer ~]# chown nginx.nginx /code/zabbix
 83[root@ZabbixServer ~]# vim /code/zabbix/info.php
 84[root@ZabbixServer ~]# cat /code/zabbix/info.php
 85<?php
 86phpinfo();
 87?>
 88
 89# 更改hosts文件
 90192.168.10.66	zabbix.soulboy.com
 91# 访问
 92http://zabbix.soulboy.com/info.php
 93
 94### mariadb
 95[root@ZabbixServer ~]# yum install mariadb-server -y
 96[root@ZabbixServer ~]# systemctl enable mariadb.service
 97[root@ZabbixServer ~]# systemctl start mariadb.service
 98
 99# 安全设置数据库
100[root@ZabbixServer ~]# mysql_secure_installation
101
102NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
103      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!
104
105In order to log into MariaDB to secure it, we'll need the current
106password for the root user.  If you've just installed MariaDB, and
107you haven't set the root password yet, the password will be blank,
108so you should just press enter here.
109
110Enter current password for root (enter for none):
111OK, successfully used password, moving on...
112
113Setting the root password ensures that nobody can log into the MariaDB
114root user without the proper authorisation.
115
116Set root password? [Y/n] y
117New password:
118Re-enter new password:
119Password updated successfully!
120Reloading privilege tables..
121 ... Success!  123456
122
123
124By default, a MariaDB installation has an anonymous user, allowing anyone
125to log into MariaDB without having to have a user account created for
126them.  This is intended only for testing, and to make the installation
127go a bit smoother.  You should remove them before moving into a
128production environment.
129
130Remove anonymous users? [Y/n] y
131 ... Success!
132
133Normally, root should only be allowed to connect from 'localhost'.  This
134ensures that someone cannot guess at the root password from the network.
135
136Disallow root login remotely? [Y/n] n
137 ... skipping.
138
139By default, MariaDB comes with a database named 'test' that anyone can
140access.  This is also intended only for testing, and should be removed
141before moving into a production environment.
142
143Remove test database and access to it? [Y/n] y
144 - Dropping test database...
145 ... Success!
146 - Removing privileges on test database...
147 ... Success!
148
149Reloading the privilege tables will ensure that all changes made so far
150will take effect immediately.
151
152Reload privilege tables now? [Y/n] y
153 ... Success!
154
155Cleaning up...
156
157All done!  If you've completed all of the above steps, your MariaDB
158installation should now be secure.
159
160Thanks for using MariaDB!
161
162# 登录
163[root@ZabbixServer ~]# mysql -uroot -p
164Welcome to the MariaDB monitor.  Commands end with ; or \g.
165Your MariaDB connection id is 11
166Server version: 5.5.68-MariaDB MariaDB Server
167
168Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
169
170Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
171
172MariaDB [(none)]> select user,host from mysql.user;
173+------+--------------+
174| user | host         |
175+------+--------------+
176| root | 127.0.0.1    |
177| root | ::1          |
178| root | localhost    |
179| root | zabbixserver |
180+------+--------------+
1814 rows in set (0.00 sec)
182
183### 为zabbix创建数据库
184[root@ZabbixServer ~]# mysql -uroot -p
185MariaDB [(none)]> create database zabbix character set utf8 collate utf8_bin;
186MariaDB [(none)]> create user 'zabbix'@'localhost' identified by '123456';
187MariaDB [(none)]> grant all privileges on zabbix.* to 'zabbix'@'localhost';
188MariaDB [(none)]> quit;
189
190### 安装zabbix服务端、客户端(监控自己)
191# 安装zabbix yum源
192[root@ZabbixServer ~]# rpm -Uvh https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm
193# 安装zabbix服务端、客户端(监控自己)
194[root@ZabbixServer ~]# yum install zabbix-server zabbix-agent2
195# zabbix数据库导入数据
196[root@ZabbixServer ~]# zcat /usr/share/doc/zabbix-server-mysql-5.0.37/create.sql.gz | mysql -uzabbix -p123456 zabbix
197
198# zabbix-server配置(让server可以写入DB),需要修改的配置就这么多
199[root@ZabbixServer ~]# vim /etc/zabbix/zabbix_server.conf
200DBHost=localhost
201DBName=zabbix
202DBUser=zabbix
203DBPassword=123456
204
205# zabbix-server默认配置
206[root@ZabbixServer ~]# grep '^[a-Z]' /etc/zabbix/zabbix_server.conf
207LogFile=/var/log/zabbix/zabbix_server.log
208LogFileSize=0
209PidFile=/var/run/zabbix/zabbix_server.pid
210SocketDir=/var/run/zabbix
211DBHost=localhost
212DBName=zabbix
213DBUser=zabbix
214DBPassword=123456
215SNMPTrapperFile=/var/log/snmptrap/snmptrap.log
216Timeout=4
217AlertScriptsPath=/usr/lib/zabbix/alertscripts
218ExternalScripts=/usr/lib/zabbix/externalscripts
219LogSlowQueries=3000
220StatsAllowedIP=127.0.0.1
221
222# 启动zabbix-server、并且添加自启动
223# zabbix-server的端口是10051、zabbix-agent的端口是10050
224[root@ZabbixServer ~]# systemctl enable zabbix-server.service
225[root@ZabbixServer ~]# systemctl start zabbix-server.service
226[root@ZabbixServer ~]# ss -lntup | grep zabbix
227
228### zabbix前端页面(源码包)
229# 不推荐yum(`yum install zabbix-web-mysql-scl zabbix-apache-conf-scl`),推荐使用源码包
230https://cdn.zabbix.com/zabbix/sources/stable/5.0/zabbix-5.0.37.tar.gz
231[root@ZabbixServer tmp]# tar xf /tmp/zabbix-5.0.37.tar.gz
232[root@ZabbixServer tmp]# mv /tmp/zabbix-5.0.37/ui/* /code/zabbix/
233[root@ZabbixServer tmp]# chown -R nginx.nginx /code/zabbix/
234
235### web页面安装(PHP程序代码可以连接DB、可以连接zabbix-server)
236http://zabbix.soulboy.com/
237
238# php最后的配置
239* Minimum required size of PHP post is 16M (configuration option "post_max_size").
240* Minimum required limit on execution time of PHP scripts is 300 (configuration option "max_execution_time").
241* Minimum required limit on input parse time for PHP scripts is 300 (configuration option "max_input_time").
242* Time zone for PHP is not set (configuration parameter "date.timezone").
243post_max_size			16M
244max_execution_time	300
245max_input_time		300
246date.timezone
247
248[root@ZabbixServer tmp]# vim /etc/php.ini
249post_max_size = 80M
250max_execution_time = 300
251max_input_time = 600
252date.timezone = Asia/Shanghai
253
254# 重启php
255[root@ZabbixServer tmp]# systemctl reload php-fpm.service
256
257# php配置文件新位置
258Configuration file "conf/zabbix.conf.php" created.
259
260
261### web前端管理用户名和密码
262Admin	zabbix

Zabbix-agent2 部署

zabbix-agent2 用 go 语言做了优化,并发性能要大于 zabbix-agent

 1### 安装zabbix-agent2
 2# yum源准备
 3[root@ZabbixServer ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
 4# webtatic 要求
 5[root@ZabbixServer ~]# yum install epel-release.noarch -y   
 6[root@ZabbixServer ~]# curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
 7# webtatic源
 8[root@ZabbixServer ~]# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm  
 9[root@ZabbixServer ~]# rpm -Uvh https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm
10# 安装zabbix服务端、客户端(监控自己)
11[root@ZabbixServer ~]# yum install zabbix-agent2
12# 安装
13[root@ZabbixServer tmp]# yum install zabbix-agent2
14
15# 修改配置文件
16[root@ZabbixServer tmp]# vim /etc/zabbix/zabbix_agent2.conf
17Server=127.0.0.1
18
19# 默认配置
20[root@ZabbixServer tmp]# grep '^[a-Z]' /etc/zabbix/zabbix_agent2.conf
21PidFile=/var/run/zabbix/zabbix_agent2.pid
22LogFile=/var/log/zabbix/zabbix_agent2.log
23LogFileSize=0
24Server=127.0.0.1
25ServerActive=127.0.0.1
26Hostname=Zabbix server
27Include=/etc/zabbix/zabbix_agent2.d/*.conf
28ControlSocket=/tmp/agent.sock
29
30# 启动zabbix-agent2
31[root@ZabbixServer tmp]# systemctl enable zabbix-agent2.service
32[root@ZabbixServer tmp]# systemctl start zabbix-agent2.service

Zabbix-Service 目录结构

 1[root@zabbixserver ~]# rpm -ql zabbix-server-mysql
 2# 日志切割
 3/etc/logrotate.d/zabbix-server
 4
 5# zabbix服务端配置文件
 6/etc/zabbix/zabbix_server.conf
 7
 8# 调用配置文件	 systemctl start/stop/restart 
 9/usr/lib/systemd/system/zabbix-server.service
10/usr/lib/tmpfiles.d/zabbix-server.conf		#临时备份文件
11
12# 报警使用脚本
13/usr/lib/zabbix/alertscripts
14
15# 额外扩展脚本(很少用)
16/usr/lib/zabbix/externalscripts
17
18# zabbix 服务端命令
19/usr/sbin/zabbix_server_mysql
20
21# zabbix建表语句
22/usr/share/doc/zabbix-server-mysql-5.0.37/create.sql.gz
23/usr/share/doc/zabbix-server-mysql-5.0.37/double.sql
24
25# 帮助文档
26/usr/share/man/man8/zabbix_server.8.gz
27
28# 日志文件目录
29/var/log/zabbix
30
31# pid文件目录
32/var/run/zabbix

zabbix_server.conf 配置选项参照表

 1LogFile=/var/log/zabbix/zabbix_server.log	# 日志文件
 2LogFileSize=0	#日志文件大小  0代表不限制  单位是MB
 3PidFile=/var/run/zabbix/zabbix_server.pid
 4SocketDir=/var/run/zabbix
 5DBHost=localhost	#连接数据库
 6DBName=zabbix
 7DBUser=zabbix
 8DBPassword=123456
 9SNMPTrapperFile=/var/log/snmptrap/snmptrap.log	#SNMP相关日志
10Timeout=4	# 超时时间 单位是秒
11AlertScriptsPath=/usr/lib/zabbix/alertscripts		# 报警脚本路径
12ExternalScripts=/usr/lib/zabbix/externalscripts	 
13LogSlowQueries=3000	# 慢查询日志,数据库查询消化的时间超过3000毫秒,单位是毫秒
14StatsAllowedIP=127.0.0.1	# 谁可以查看服务端状态,默认自己

zabbix_agent2.conf 配置选项参照表

1PidFile=/var/run/zabbix/zabbix_agent2.pid
2LogFile=/var/log/zabbix/zabbix_agent2.log
3LogFileSize=0
4Server=127.0.0.1	# zabbix 服务端ip
5ServerActive=127.0.0.1	# zabbix 客户端主动模式的服务端ip地址
6Hostname=Zabbix server	# 客户端主机名
7Include=/etc/zabbix/zabbix_agent2.d/*.conf	# 类似于nginx  include功能,分割配置文件
8ControlSocket=/tmp/agent.sock	# 套接字

Zabbix-agent2 监控流程

  1. 客户端部署 zabbix-agent2
  2. 修改配置文件指定 server 为 zabbix 服务端
  3. Web 页面配置 --> 主机中添加主机
  4. 添加后检测与检查数据

环境准备

 1### 配置阿里云yum
 2[root@zabbix-web ~]# yum install wget -y
 3① 备份默认源
 4[root@zabbix-web ~]#  mkdir /etc/yum.repos.d/backup
 5[root@zabbix-web ~]# mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup
 6
 7② 下载新CentOS-Base.repo
 8[root@zabbix-web ~]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
 9# webtatic 要求
10[root@zabbix-web ~]# yum install epel-release.noarch -y
11[root@zabbix-web ~]# curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
12# webtatic 要求
13[root@zabbix-web ~]# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
14[root@zabbix-web ~]# yum clean all 
15[root@zabbix-web ~]# yum makecache
16[root@zabbix-web ~]# yum repolist
17
18# 安装zabbix yum源
19[root@zabbix-web ~]#  rpm -Uvh https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm
20[root@zabbix-web ~]# yum install zabbix-agent2
21
22# 修改配置文件
23[root@zabbix-web ~]# grep '^[a-Z]' /etc/zabbix/zabbix_agent2.conf
24PidFile=/var/run/zabbix/zabbix_agent2.pid
25LogFile=/var/log/zabbix/zabbix_agent2.log
26LogFileSize=0
27Server=192.168.10.66
28ServerActive=127.0.0.1
29Hostname=Zabbix server
30Include=/etc/zabbix/zabbix_agent2.d/*.conf
31ControlSocket=/tmp/agent.sock
32
33# 添加开机自启动、启动服务
34[root@zabbixserver ~]# systemctl enable zabbix-agent2.service
35[root@zabbixserver ~]# systemctl start zabbix-agent2.service
36 [root@zabbix-web ~]# ss -lntup | grep 10050
37tcp    LISTEN     0      128      :::10050                :::*                   users:(("zabbix_agent2",pid=14095,fd=8))
38[root@zabbix-web ~]# ps -ef | grep zabbix
39zabbix   14095     1  0 16:01 ?        00:00:00 /usr/sbin/zabbix_agent2 -c /etc/zabbix/zabbix_agent2.conf
40root     14103  4003  0 16:01 pts/0    00:00:00 grep --color=auto zabbix
41
42# 测试客户端和服务端是否连接成功
43[root@zabbix-web ~]# nmap -p10051 192.168.10.66
44Starting Nmap 6.40 ( http://nmap.org ) at 2023-09-21 16:10 CST
45Nmap scan report for 192.168.10.66
46Host is up (0.00015s latency).
47PORT      STATE SERVICE
4810051/tcp open  unknown
49MAC Address: 08:00:27:F8:7A:E6 (Cadmus Computer Systems)
50
51Nmap done: 1 IP address (1 host up) scanned in 0.42 seconds
52
53# 排错思路(服务端向客户端索要数据)
54[root@zabbixserver ~]# yum install zabbix-get
55[root@zabbixserver ~]# zabbix_get -s 192.168.10.61 -p 10050 -k system.hostname
56zabbix-web

Web 中文乱码问题

微软雅黑字体下载

 1### zabbix-server web使用的字体
 2# windows字体文件路径
 3C:\Windows\Fonts\*  		# 很多字体
 4C:\Windows\Fonts\msyh.ttc 	# 微软雅黑
 5
 6# zabbix字体文件路径
 7[root@zabbixserver ~]# ll /code/zabbix/assets/fonts/DejaVuSans.ttf
 8
 9#  备份老字体
10[root@zabbixserver ~]# cp /code/zabbix/assets/fonts/DejaVuSans.ttf /code/zabbix/assets/fonts/DejaVuSans.ttf.bak
11
12# 替换新字体
13[root@zabbixserver ~]# cp /tmp/msyh.ttc /code/zabbix/assets/fonts/DejaVuSans.ttf
14cp: overwrite ‘/code/zabbix/assets/fonts/DejaVuSans.ttf’? y

中文乱码问题

Zabbix-Server WebManagement

账户密码

1user: Admin
2password: zabbix

服务端、客户端设置统一主机名

 1# 修改hosts文件
 2[root@zabbixserver ~]# cat /etc/hosts
 3127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
 4::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
 5192.168.10.66   zabbixserver
 6192.168.10.61   zabbix-web
 7
 8# 测试连通性
 9[root@zabbixserver ~]# ping zabbix-web
10PING zabbix-web (192.168.10.61) 56(84) bytes of data.
1164 bytes from zabbix-web (192.168.10.61): icmp_seq=1 ttl=64 time=0.182 ms
12[root@zabbixserver ~]# ping zabbix-web
13PING zabbix-web (192.168.10.61) 56(84) bytes of data.
1464 bytes from zabbix-web (192.168.10.61): icmp_seq=1 ttl=64 time=0.176 ms

新建主机
新建主机

关联模板
关联模板

应用集
应用集

自定义监控项

目的

11. 默认模板中没有我们要的监控项
22. 优化zabbix性能:优化

流程

  1. Zabbix-agent 创建 key(键值)与调试

    1书写监控命令:key(键值),键值就是一个可以被zabbix-server端识别的命令,用于获取zabbix客户端数据。
    2创建自定义key之前最好思考是否可以直接使用zabbix内置的key,如果内置key满足不了需求再考虑自定义key
    3查看内置key通过: zabbix_agent2 -p
    4	[root@zabbix-web ~]# zabbix_agent2 -p | awk '/^[a-z]+\./{print $1}'
    5调试Debug命令与脚本
    6写入到zabbix客户端配置文件UserParameter=key,command或脚本与调试zabbix_get
    
  2. Zabbix-server Web 页面(点鼠标)

    1web页面添加/修改模板
    2web页面分组
    
  3. Web 页面监控项:zabbix 服务端是否可以获取数据

  4. Web 页面触发器 trigger:什么时候报警

  5. Web 页面图形

示例需求:统计 web01 80 端口是否存在

 1### 内置key其实可以满足(假设不能满足)
 2[root@zabbix-web ~]# zabbix_agent2 -p | awk '/^[a-z]+\./{print $1}' | grep 80
 3
 4### 自定义监控项
 5# 定义出脚本或命令放在/etc/zabbix/zabbix_agent2.d目录下
 6
 7# 自定义key(命名规范尽量贴切,这里web)
 8[root@zabbix-web ~]# cat /etc/zabbix/zabbix_agent2.d/web.conf
 9#UserParameter=<key>,<shell command>
10UserParameter=nginx.alive,ss -lntup | grep -wc 80
11
12# 重启客户端
13[root@zabbix-web ~]# systemctl restart zabbix-agent2.service
14
15# zabbix-server 端进行测试
16[root@zabbixserver ~]# zabbix_get -s 192.168.10.61 -k nginx.alive
171

zabbix-server Web 配置监控项(监控项的主要目的是获取 agent 数据并写入 DB)
添加监控项

添加触发器 trigger

添加图形

监测验证

获取 nginx 的 7 中运行状态值

 1# 新建配置文件 /etc/nginx/nginx.conf 主配置文件中注释掉 server { }
 2[root@zabbix-web default.d]# cat /etc/nginx/default.d/default.conf
 3server {
 4        listen 80;
 5        server_name localhost default_server;
 6        root /code/default;
 7        location /nginx_status {
 8        stub_status on;
 9        }
10}
11
12# 重启服务并测试
13[root@zabbix-web default.d]# nginx -t
14nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
15nginx: configuration file /etc/nginx/nginx.conf test is successful
16
17[root@zabbix-web default.d]# service nginx restart
18Redirecting to /bin/systemctl restart nginx.service
19
20[root@zabbix-web default.d]# curl 192.168.10.61/nginx_status
21Active connections: 1
22server accepts handled requests
23 1 1 1
24Reading: 0 Writing: 1 Waiting: 0
25
26# 自定义shell监控脚本(这里的脚本并不是最终的key)
27[root@zabbix-web default.d]# cat /server/scripts/ngx_stats.sh
28#!/bin/bash
29#author: soulboy
30#desc: check nginx 7 status
31
32CMD="curl -s 192.168.10.61/nginx_status"
33
34case "$1" in
35        active)
36                $CMD | awk 'NR==1{print $NF}'
37                ;;
38        accept*)
39                $CMD | awk 'NR==3{print $1}'
40                ;;
41        handle*)
42                $CMD | awk 'NR==3{print $2}'
43                ;;
44        request*)
45                $CMD | awk 'NR==3{print $3}'
46                ;;
47        read*)
48                $CMD | awk 'END{print $2}'
49                ;;
50        write*)
51                $CMD | awk 'END{print $4}'
52                ;;
53        wait*)
54                $CMD | awk 'END{print $6}'
55                ;;
56        *)
57                echo "USAGE: $0 {active|accept|handle|request|read|write|wait}"
58esac
59
60
61# 定义键值(key)
62[root@zabbix-web default.d]# cat /etc/zabbix/zabbix_agent2.d/web.conf
63#UserParameter=<key>,<shell command>
64UserParameter=nginx.alive,ss -lntup | grep -wc 80
65#UserParameter=nginx.active /server/scripts/ngx_stats.sh active
66UserParameter=nginx.stats[*],sh /server/scripts/ngx_stats.sh "$1"
67
68# 重启服务
69[root@zabbix-web default.d]# systemctl restart zabbix-agent2.service
70
71
72# 在zabbix-server端进行测试
73[root@zabbixserver ~]# zabbix_get -s 192.168.10.61 -k nginx.stats[active]
741
75[root@zabbixserver ~]# zabbix_get -s 192.168.10.61 -k nginx.stats[read]
760

常见错误排查及解决方法

权限不足

1# 授权zabbix用户
2[root@zabbixserver ~]# visudo
3zabbix ALL=(ALL) NOPASSWD: ALL
4[root@zabbixserver ~]# grep zabbix /etc/sudoers
5zabbix ALL=(ALL) NOPASSWD: ALL
6
7# 在外置脚本命令中添加 sudo 
8[root@zabbix-web default.d]# cat /etc/zabbix/zabbix_agent2.d/web.conf
9UserParameter=nginx.stats[*],sudo sh /server/scripts/ngx_stats.sh "$1"

awk 取列

1自定义监控的时候推荐使用脚本,尤其是awk
2awk在取列的时候容易出现故障,$2 使用$$2

zabbix 脚本默认执行是有超时时间的,默认是 3 秒

1[root@zabbix-web default.d]# grep Timeout /etc/zabbix/zabbix_agent2.conf
2### Option: Timeout
3#       Spend no more than Timeout seconds on processing
4# Timeout=3

自定义模板

  1. 创建模板
  2. 创建应用集(监控项分类)applications
  3. 创建自定义监控项 items
  4. 创建创建触发器 triggers
  5. 创建图形 graphs
  6. 模板可以与多个机器关联(避免 Web 页面重复操作)

创建模板


添加应用集




复制触发器



复制图形



主机与模板关联



告警分类

告警方式 企业应用场景
发邮件 企业邮件,免费使用
企业微信-告警应用(机器人) 需要使用企业微信,免费
OA 系统(钉钉) 与阿里云,免费
短信 0.045/条左右(阿里云短信服务)
电话 按时长进行付费
第三方报警:onealert(省事儿) 只需要配置 onealert 平台信息即可,免费使用(限量),超出收费

邮件报警

1个人邮箱/企业邮箱
2开启个人邮箱 smtp功能,获取授权码
3配置zabbix 报警媒介类型
4配置用户接收报警
5配置动作(什么时候发邮件)

个人邮箱

收发方 邮箱地址 授权码
发送方 wcsb19900116 授权码:EZYQOZUQXBPXPGYY
接收方 410686931@qq.com

服务器地址

1**POP3服务器**: pop.126.com
2
3**SMTP服务器**: smtp.126.com
4
5**IMAP服务器**: imap.126.com

新建告警媒介类型

告警邮件内容

 1########### 问题模板(发生故障时候用的)
 2### 主题(中文替换)
 3故障名称: {EVENT.NAME}
 4
 5### 消息(中文替换)
 6故障始于 时间: {EVENT.TIME}  日期: {EVENT.DATE}
 7故障名称: {EVENT.NAME}
 8故障主机: {HOST.NAME}
 9故障等级: {EVENT.SEVERITY}
10额外信息: {EVENT.OPDATA}
11故障ID: {EVENT.ID}
12触发器地址:{TRIGGER.URL}
13
14########### 问题恢复模板(故障恢复时使用的模板)
15### 主题
16故障解决 in {EVENT.DURATION}: {EVENT.NAME}
17
18### 消息
19故障已经解决 时间:{EVENT.RECOVERY.TIME} 日期: {EVENT.RECOVERY.DATE}
20故障名称: {EVENT.NAME}
21故障持续时间: {EVENT.DURATION}
22故障主机: {HOST.NAME}
23故障级别: {EVENT.SEVERITY}
24故障ID: {EVENT.ID}
25{TRIGGER.URL}

配置发件人






测试

配置收件人

1运维组:111@qq.com
2开发组:222@qq.com
3CTO:666@qq.com

创建用户组


创建用户关联用户组




登录 dev01 用户

微信报警

1企业微信、钉钉、短信需
2	推荐:直接在群中新建机器人,然后获取webhook地址
3	不推荐:要获取企业微信id和告警机器人
4使用脚本(shell/python)调用企业微信api接口:输入收件人、信息
5配置告警媒介:发件人(微信)
6配置告警媒介:收件人(个人媒体类型)
7动作:默认的是用风吹草动就发(已完成)

自建告警机器人(推荐)

python 脚本

 1###  添加执行权限
 2[root@zabbixserver ~]# chmod +x /usr/lib/zabbix/alertscripts/wechat.py
 3
 4[root@zabbixserver ~]# vim /usr/lib/zabbix/alertscripts/wechat.py
 5#!/usr/bin/env python3
 6#_*_coding:utf-8 _*_
 7
 8import requests,sys,json,time
 9import urllib3
10urllib3.disable_warnings()
11
12def SendMessageURL(User,Subject,Messages):
13    ###机器人的Webhook
14    URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=f3faaa6a-a945-4x91-94c6-04fba371eb5b"
15    HEADERS = {"Content-Type": "application/json"}
16    Data = {
17        "msgtype": "markdown",
18        "markdown": {
19                "content": "# ...... \n <font color=\"warning\">%s</font> \n <font color=\"info\">%s</font> \n <@%s>"% (Subject,Messages,User),
20                #"mentioned_list" : [User],
21                #"content": \<font color="warning">Subject</font>  \n  Messages,
22                #"mentioned_list" :[User],
23                ###因为是故障告警群,所以需要@all,这个看自己选择
24                "mentioned_list" :[User,"@all"]
25                #"mentioned_mobile_list" : ["13800000000","@all"]
26            }
27    }
28    r = requests.post(url=URL, headers=HEADERS, json=Data, verify=False)
29    print(r.json())
30
31if __name__ == "__main__":
32    SENDTO = str(sys.argv[1])
33    SUBJECT = str(sys.argv[2])
34    MESSAGE = str(sys.argv[3])
35    Status = str(SendMessageURL(SENDTO,SUBJECT,MESSAGE))
36    print (Status)
37
38### 测试
39[root@zabbixserver python3.6]# python /usr/lib/zabbix/alertscripts/wechat.py WangChao 'Title' 'test content'
40{u'errcode': 0, u'errmsg': u'ok'}
41None

自建告警机器人(不推荐)

1### 企业id
2wwbsaf0f23xf547a376
3
4### 告警机器人
5agentId:1000002
6Secret:WQ73zrSGSqAGSQms0XX63gF1wrBgKASseSqO6I82PSQ

如果在群中推送消息不推荐这种


python 告警脚本

 1[root@zabbixserver ~]# vim /usr/lib/zabbix/alertscripts/wechat.py
 2#!/usr/bin/env python
 3#-*- coding: utf-8 -*-
 4import requests
 5import sys
 6import os
 7import json
 8import logging
 9
10logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s, %(filename)s, %(levelname)s, %(message)s',
11datefmt = '%a, %d %b %Y %H:%M:%S',
12filename = os.path.join('/tmp','weixin.log'),
13filemode = 'a')
14corpid='微信企业号corpid'
15appsecret='应用的Secret'
16agentid=应用的id
17#获取accesstoken
18token_url='https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + appsecret
19req=requests.get(token_url)
20accesstoken=req.json()['access_token']
21#发送消息
22msgsend_url='https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + accesstoken
23touser=sys.argv[1]
24subject=sys.argv[2]
25#toparty='3|4|5|6'
26message=sys.argv[2] + "\n\n" +sys.argv[3]
27params={
28"touser": touser,
29# "toparty": toparty,
30"msgtype": "text",
31"agentid": agentid,
32"text": {
33"content": message
34},
35"safe":0
36}
37req=requests.post(msgsend_url, data=json.dumps(params))
38logging.info('sendto:' + touser + ';;subject:' + subject + ';;message:' + message)
39
40
41###  添加执行权限
42[root@zabbixserver ~]# chmod +x /usr/lib/zabbix/alertscripts/wechat.py
43
44### ImportError: No module named requests
45[root@zabbixserver ~]# python /usr/lib/zabbix/alertscripts/wechat.py
46Traceback (most recent call last):
47  File "/usr/lib/zabbix/alertscripts/wechat.py", line 3, in <module>
48    import requests
49ImportError: No module named requests
50
51[root@zabbixserver ~]# yum install -y python-requests
52
53###

配置告警媒介:发件人(微信)

1{ALERT.SENDTO}
2{ALERT.SUBJECT}
3{ALERT.MESSAGE}


消息类型:问题

1故障名称: {EVENT.NAME}
2
3故障始于 时间: {EVENT.TIME} 日期: {EVENT.DATE}
4故障名称: {EVENT.NAME}
5故障主机: {HOST.NAME}
6严重程度: {EVENT.SEVERITY}
7额外信息: {EVENT.OPDATA}
8故障ID号: {EVENT.ID}
9故障地址: {TRIGGER.URL}

消息类型:问题恢复

1故障解决 in {EVENT.DURATION}: {EVENT.NAME}
2
3故障已经解决 时间: {EVENT.RECOVERY.TIME} 日期: {EVENT.RECOVERY.DATE}
4故障名称: {EVENT.NAME}
5故障持续时间: {EVENT.DURATION}
6故障主机: {HOST.NAME}
7故障级别: {EVENT.SEVERITY}
8故障ID号: {EVENT.ID}
9触发器:{TRIGGER.URL}

报错 /usr/bin/env: python3: No such file or directory

1[root@zabbixserver ~]# yum install  python3
2[root@zabbixserver ~]# yum install python-pip
3[root@zabbixserver ~]# cd /usr/lib/python3.6/
4[root@zabbixserver python3.6]# pip3 install requests

配置告警媒介:收件人(个人媒体类型)

动作:默认的是用风吹草动就发(已完成)

监控项类型

监控项类型 说明
zabbix 客户端模式(被动) 通用、常用,配合模板或自定义监控使用,适用于几乎所有情况:Linux、windows、android/ios
zabbix 客户端模式(主动) 默认是被动模式,主动模式 zabbix 客户端主动推送数据给服务端
简单检查 不需要客户端,功能少,只能检查网络情况(ping、tcp、udp)
SNMP Simple Network Management Protocal 简单网络管理协议、zabbix 监控网络设备使用(路由器、交换机)
内部检查 监控 zabbix 的内部进程:可以是 zabbix server 或 zabbix proxy 的运行情况
HTTP 代理 此模式由 zabbix server 发出 http 请求给客户端,根据响应进行二次处理加工
JMX Java-gateway 监控 Java 程序(Tomcat),未来推荐自定义监控(zabbix-agent2 + jmap/jstats)
IPMI 监控硬件(物理服务器、联想(IBM X86 架构 ThinkServer)、华为、浪潮、IBM(云计算类型服务器)、Dell) ,推荐直接使用自定义监控(ipmitool[温度] + megacli[RAID])

Zabbix-agent2 监控 windows

Zabbix agent 2 v5.0.38 下载

SNMP 监控网络设备

1启动设备的SNMP功能 端口161
2zabbix服务进行测试:能否获取到网络设备信息
3web添加主机(监控项)

SNMP 不同版本的差异

snmp 版本
v3 通过 用户名和密码 访问 snmp 信息
v2c 通过社区 id 访问 snmp 信息
v1

网络设备开启 SNMP 功能


zabbix-server 安装 snmp 监控命令
SNMP 常用 OID 合集

 1[root@zabbixserver ~]#  yum install net-snmp-utils -y
 2
 3# 命令
 4[root@zabbixserver ~]# rpm -ql net-snmp-utils
 5/usr/bin/encode_keychange
 6/usr/bin/snmpbulkget
 7/usr/bin/snmpbulkwalk
 8/usr/bin/snmpdelta
 9/usr/bin/snmpdf
10/usr/bin/snmpget
11/usr/bin/snmpgetnext
12/usr/bin/snmpinform
13/usr/bin/snmpnetstat
14/usr/bin/snmpset
15/usr/bin/snmpstatus
16/usr/bin/snmptable
17/usr/bin/snmptest
18/usr/bin/snmptls
19/usr/bin/snmptranslate
20/usr/bin/snmptrap
21/usr/bin/snmpusm
22/usr/bin/snmpvacm
23/usr/bin/snmpwalk
24
25# 获取系统信息 -c 后面是团体名称(仅限于v2c版本使用) -v 指定snmp版本  域名或ip 获取网络设备的信息(名称/oid)
26[root@zabbixserver ~]# snmpwalk -c oldboykx -v 2c 192.168.10.1 SysDesc
27[root@zabbixserver ~]# snmpwalk -c oldboykx -v 2c 192.168.10.1 .1.3.6.1.2.1.1.1.0

zabbix-server 自定义监控项




JMX(Java-gateway) 监控 Java 程序

监控 Java 方案
zabbix-java-gateway zabbix-java-gateway(可以是 zabbix-server 也可以单独运行在一台机器上) + jmx(tomcat) + 内置模版(zabbix-server-web)
自定义监控脚本 通过 jmap/jstat 实现自定义监控(不需要安装 zabbix-java-gateway,zabbix-server 不需要开启远程监控功能)

JMX 是 Java Management Extensions(Java 管理扩展) 的缩写,它是 Java 平台上用于管理和监控应用程序、系统和网络资源的一种标准化的管理和监控框架。JMX 提供了一种标准的方式,通过这种方式,开发人员可以暴露应用程序中的各种管理和监控信息,然后可以使用 JMX 客户端工具或应用程序来访问和操作这些信息。

如果只是监控 pid/端口信息通过 zabbix-agent2 就可以实现。
JMX 可以用来查看程序运行状态(JVM 虚拟机)

监控流程

1客户端 jdk(tomcat) 
2开启远程监控功能

JDK8+Tomcat9 部署参考

 1### 配置JDK8
 2[root@zabbix-web ~]# mkdir -p /usr/local/software
 3[root@zabbix-web ~]# cd /usr/local/software/
 4[root@zabbix-web software]# ll
 5total 192716
 6-rw-r--r--. 1 root root  11692853 Sep 23 08:04 apache-tomcat-9.0.80.tar.gz
 7-rw-r--r--. 1 root root 185646832 Sep 23 08:04 jdk-8u181-linux-x64.tar.gz
 8
 9[root@zabbix-web software]# tar -zxvf jdk-8u181-linux-x64.tar.gz
10[root@zabbix-web software]# mv jdk1.8.0_181 jdk8
11[root@zabbix-web software]# vim /etc/profile
12export JAVA_HOME=/usr/local/software/jdk8
13export PATH=$JAVA_HOME/bin:$PATH
14export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
15export JAVA_HOME PATH CLASSPATH
16
17[root@zabbix-web software]# source /etc/profile
18[root@zabbix-web software]# java -version
19java version "1.8.0_181"
20Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
21Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
22
23### 配置tomcat8
24[root@zabbix-web software]# tar xvf apache-tomcat-8.5.93.tar.gz
25[root@zabbix-web software]# mv apache-tomcat-8.5.93 /usr/local/tomcat
26
27[root@zabbix-web software]# vim /usr/local/tomcat/bin/catalina.sh
28CATALINA_OPTS="$CATALINA_OPTS \
29-Dcom.sun.management.jmxremote \
30-Dcom.sun.management.jmxremote.port=12345 \
31-Dcom.sun.management.jmxremote.ssl=false \
32-Dcom.sun.management.jmxremote.authenticate=false \
33-Dcom.sun.management.jmxremote.ssl=false \
34-Djava.rmi.server.hostname=192.168.10.61"
35
36# 开启JVM远程监控功能
37[root@zabbix-web software]# /usr/local/tomcat/bin/startup.sh
38[root@zabbix-web software]# ss -lntup | grep java
39tcp    LISTEN     0      50       :::37006                :::*                   users:(("java",pid=15706,fd=21))
40tcp    LISTEN     0      100      :::8080                 :::*                   users:(("java",pid=15706,fd=56))
41tcp    LISTEN     0      50       :::45206                :::*                   users:(("java",pid=15706,fd=19))
42tcp    LISTEN     0      50       :::12345                :::*                   users:(("java",pid=15706,fd=20))
43tcp    LISTEN     0      1      ::ffff:127.0.0.1:8005                 :::*                   users:(("java",pid=15706,fd=64))

zabbix-server 安装 java-gateway

 1[root@zabbixserver ~]# yum list | grep -i java-gateway
 2zabbix-java-gateway.x86_64               5.0.38-1.el7                  zabbix
 3
 4[root@zabbixserver ~]# yum install zabbix-java-gateway
 5
 6[root@zabbixserver ~]# rpm -ql zabbix-java-gateway
 7/etc/zabbix/zabbix_java_gateway.conf		#配置文件
 8/etc/zabbix/zabbix_java_gateway_logback.xml
 9/usr/lib/systemd/system/zabbix-java-gateway.service	# systemctl管理脚本
10/usr/lib/tmpfiles.d/zabbix-java-gateway.conf	#配置文件备份
11/usr/sbin/zabbix_java_gateway	# zabbix-java命令
12/usr/share/zabbix-java-gateway
13/usr/share/zabbix-java-gateway/bin
14/usr/share/zabbix-java-gateway/bin/zabbix-java-gateway-5.0.38.jar
15/usr/share/zabbix-java-gateway/lib
16/usr/share/zabbix-java-gateway/lib/android-json-4.3_r3.1.jar
17/usr/share/zabbix-java-gateway/lib/logback-classic-1.2.9.jar
18/usr/share/zabbix-java-gateway/lib/logback-core-1.2.9.jar
19/usr/share/zabbix-java-gateway/lib/slf4j-api-1.7.32.jar
20/var/log/zabbix
21/var/run/zabbix
22
23# 修改配置文件
24[root@zabbixserver ~]# vim /etc/zabbix/zabbix_java_gateway.conf
25LISTEN_PORT=10052
26PID_FILE="/var/run/zabbix/zabbix_java.pid"
27
28# 启动服务
29[root@zabbixserver ~]# systemctl enable zabbix-java-gateway.service
30[root@zabbixserver ~]# systemctl restart zabbix-java-gateway.service
31[root@zabbixserver ~]# ss -lntup | grep java
32tcp    LISTEN     0      50       :::10052                :::*                   users:(("java",pid=21683,fd=12))
33[root@zabbixserver ~]# ps auxf | grep java-gateway
34root     21835  0.0  0.0 112708   976 pts/0    S+   22:01   0:00  |       \_ grep --color=auto java-gateway
35zabbix   21683  0.0  2.0 2522280 42924 ?       Sl   21:55   0:00 java -server -Dlogback.configurationFile=/etc/zabbix/zabbix_java_gateway_logback.xml -classpath lib:lib/android-json-4.3_r3.1.jar:lib/logback-classic-1.2.9.jar:lib/logback-core-1.2.9.jar:lib/slf4j-api-1.7.32.jar:bin/zabbix-java-gateway-5.0.38.jar -Dzabbix.pidFile=/var/run/zabbix/zabbix_java.pid -Dzabbix.listenPort=10052 -Dsun.rmi.transport.tcp.responseTimeout=3000 com.zabbix.gateway.JavaGateway

修改 zabbix-server 主配置文件并重启 zabbix-server

1# 修改配置文件(让zabbix-server能调用zabbix-java-gateway服务)
2[root@zabbixserver ~]# vim /etc/zabbix/zabbix_server.conf
3JavaGateway=192.168.10.66	# 因为这里zabbix-java-gateway和zabbix-server 在同一台机器,协议也可以写成127.0.0.1JavaGatewayPort=10052
4StartJavaPollers=5		# zabbix_server专门用于接收zabbix-java-gateway的进程数
5
6# 重启
7[root@zabbixserver ~]# systemctl restart zabbix-server.service
8# 查看进程
9[root@zabbixserver ~]# ps -ef | grep poller

cmdline-jmxclient-0.10.3.jar 下载

1[root@zabbixserver ~]# java -jar /mnt/cmdline-jmxclient-0.10.3.jar - 192.168.10.61:12345

zabbix-server Web 添加监控主机
1

2

3

4

自定义监控脚本思路
通过 jmap/jstat 实现自定义监控(不需要安装 zabbix-java-gateway,zabbix-server 不需要开启远程监控功能)

 1### 脚本监控java思路
 2
 3用户输入参数 tomcat8080 (应用名称)   xxx(Eden Space)内存
 4* 根据应用找寻pid
 5* 根据pid导出内存使用情况(jmap -heap pid)
 6* 过滤出指定名字空间的使用率
 7
 8# 根据应用找寻pid
 9[root@zabbix-web software]# ps -aux | grep tomcat
10root     15706  0.0  9.2 2292272 93704 pts/0   Sl   09:18   0:06 /usr/local/software/jdk8/bin/java -Djava.util.logging.config.file=/usr/local/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava.protocol.handler.pkgs=org.apache.catalina.webresources -Dorg.apache.catalina.security.SecurityListener.UMASK=0027 -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=12345 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=192.168.10.61 -Dignore.endorsed.dirs= -classpath /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/usr/local/tomcat -Dcatalina.home=/usr/local/tomcat -Djava.io.tmpdir=/usr/local/tomcat/temp org.apache.catalina.startup.Bootstrap start
11root     22825  0.0  0.0 112720   984 pts/0    R+   11:11   0:00 grep --color=auto tomcat
12
13# 根据pid导出内存使用情况(jmap -heap pid)
14# 过滤出指定名字(Eden Space)空间的使用率
15[root@zabbix-web software]# jmap -heap 15706
16Attaching to process ID 15706, please wait...
17Debugger attached successfully.
18Server compiler detected.
19JVM version is 25.181-b13
20
21using thread-local object allocation.
22Mark Sweep Compact GC
23
24Heap Configuration:
25   MinHeapFreeRatio         = 40
26   MaxHeapFreeRatio         = 70
27   MaxHeapSize              = 260046848 (248.0MB)
28   NewSize                  = 5570560 (5.3125MB)
29   MaxNewSize               = 86638592 (82.625MB)
30   OldSize                  = 11206656 (10.6875MB)
31   NewRatio                 = 2
32   SurvivorRatio            = 8
33   MetaspaceSize            = 21807104 (20.796875MB)
34   CompressedClassSpaceSize = 1073741824 (1024.0MB)
35   MaxMetaspaceSize         = 17592186044415 MB
36   G1HeapRegionSize         = 0 (0.0MB)
37
38Heap Usage:
39New Generation (Eden + 1 Survivor Space):
40   capacity = 7602176 (7.25MB)
41   used     = 385136 (0.3672943115234375MB)
42   free     = 7217040 (6.8827056884765625MB)
43   5.066128434806035% used
44Eden Space:
45   capacity = 6815744 (6.5MB)
46   used     = 146976 (0.140167236328125MB)
47   free     = 6668768 (6.359832763671875MB)
48   2.1564190204326925% used
49From Space:
50   capacity = 786432 (0.75MB)
51   used     = 238160 (0.2271270751953125MB)
52   free     = 548272 (0.5228729248046875MB)
53   30.283610026041668% used
54To Space:
55   capacity = 786432 (0.75MB)
56   used     = 0 (0.0MB)
57   free     = 786432 (0.75MB)
58   0.0% used
59tenured generation:
60   capacity = 16658432 (15.88671875MB)
61   used     = 10825208 (10.323722839355469MB)
62   free     = 5833224 (5.562995910644531MB)
63   64.98335497602656% used
64
6515701 interned Strings occupying 1398384 bytes.

IPMI 监控

监控硬件(物理服务器、联想(IBM X86 架构 ThinkServer)、华为、浪潮、IBM(云计算类型服务器)、Dell) ,推荐直接使用自定义监控(ipmitool[温度] + megacli[RAID])

11. IPMI监控
22. 自定义脚本监控(更加推荐)

IPMI 监控

1# BIOS开启IPMI功能
2
3# 修改zabbix-server配置
4[root@zabbixserver ~]# vim /etc/zabbix/zabbix_server.conf
5StartIPMIPollers=3
6
7# 添加监控主机(zabbix-server-web)

自定义脚本监控(ipmitool[温度] + megacli[RAID]

1[root@zabbix-web software]# yum install -y ipmitool megacli
2
3# 虚拟机中执行获取不到,必须在物理机上执行
4[root@zabbix-web software]# ipmitool sensor

自动发现与自动注册

安装完毕 zabbix-agent2 的节点快速加入到被监控主机 zabbix-server-web 页面中(批量安装 zabbix-agent2 可以使用 ansible)

方式 共同点 区别
自动发现 自动添加主机并关联模板,启动主机 1、使用简单吗。 2、效率较低。 3、server 端压力较大
自动注册 自动添加主机并关联模板,启动主机 1、客户端主动请求注册 2、配置繁琐一点

自动发现

自动注册

自动发现

  1. 配置自动发现规则:发现主机
  2. 启动自动发现动作:发现主机后关联模版、添加主机、加入主机组、启动
 1# yum源准备
 2[root@zabbix-web software]# curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
 3# webtatic 要求
 4[root@zabbix-web software]# yum install epel-release.noarch -y   
 5[[root@zabbix-web software]# curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
 6# webtatic源
 7[root@zabbix-web software]# rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm  
 8[root@zabbix-web software]# rpm -Uvh https://repo.zabbix.com/zabbix/5.0/rhel/7/x86_64/zabbix-release-5.0-1.el7.noarch.rpm
 9# 安装zabbix-agent2
10[root@zabbix-web software]# yum install zabbix-agent2
11
12### 客户端安装agent2并且配置Server指向zabbix-server
13[root@zabbix-web software]# vim /etc/zabbix/zabbix_agent2.conf
14Server=192.168.10.66
15[root@zabbix-web software]# systemctl start zabbix-agent2.service

配置规则
配置规则

配置动作
配置动作
配置动作
配置动作

grafana

从数据库中获取 zabbix 监控数据,并且在 Grafana 中进行展示是
Grafana 可以单独部署在一台机器,也可以和 zabbix-server 部署在有一起,主要看负载情况。

grafana-8.0.6-1.x86_64.rpm 下载

grafana-9.5.8-1.x86_64.rpm 下载

安装 grafana 及插件

 1### 安装 grafana
 2[root@zabbixserver ~]# yum install https://mirrors.tuna.tsinghua.edu.cn/grafana/yum/rpm/Packages/grafana-9.5.8-1.x86_64.rpm
 3[root@zabbixserver ~]# rpm -ql grafana 
 4/etc/grafana	# 配置文件目录
 5/etc/init.d/grafana-server	# 服务启动脚本
 6/etc/sysconfig/grafana-server	# 配置文件
 7/usr/lib/systemd/system/grafana-server.service	# 服务端管理配置systemctl
 8/usr/sbin/grafana-cli	# grafana 管理命令 客户端
 9/usr/sbin/grafana-server	# 服务端命令
10/usr/share/grafana/public	# 家目录
11 
12# 启动服务
13[root@zabbixserver ~]# systemctl enable grafana-server.service
14[root@zabbixserver ~]# systemctl start grafana-server.service
15[root@zabbixserver ~]# ps -ef | grep grafana
16grafana  27277     1  0 01:34 ?        00:00:00 /usr/sbin/grafana-server --config=/etc/grafana/grafana.ini --pidfile=/var/run/grafana/grafana-server.pid --packaging=rpm cfg:default.paths.logs=/var/log/grafana cfg:default.paths.data=/var/lib/grafana cfg:default.paths.plugins=/var/lib/grafana/plugins cfg:default.paths.provisioning=/etc/grafana/provisioning
17root     27303 18260  0 01:35 pts/0    00:00:00 grep --color=auto grafana
18# 默认端口是3000
19[root@zabbixserver ~]# ss -lntup | grep grafana
20tcp    LISTEN     0      128      :::3000                 :::*                   users:(("grafana-server",pid=27277,fd=8))
21
22# web页面地址
23http://192.168.10.66:3000
24user:admin
25password:admin
26
27### grafana 扩展插件(grafana默认无法从zabbix数据库中获取数据)
28[root@zabbixserver ~]# grafana-cli plugins list-remote | grep -i zabbix
29id: alexanderzobnin-zabbix-app version: 4.4.1
30
31[root@zabbixserver ~]# grafana-cli plugins install alexanderzobnin-zabbix-app 4.4.1 # 这里可以指定版本,如果不指定就安装最新版本
32✔ Downloaded and extracted alexanderzobnin-zabbix-app v4.4.1 zip successfully to /var/lib/grafana/plugins/alexanderzobnin-zabbix-app
33
34Please restart Grafana after installing or removing plugins. Refer to Grafana documentation for instructions if necessary.
35
36
37# Grafana版本9以上,zabbix版本5.0,使用默认zabbix插件,Dashboards加载的时候报错:Failed to get plugin dashboards
38grafana-cli plugins remove alexanderzobnin-zabbix-app
39grafana-cli plugins install alexanderzobnin-zabbix-app 4.2.10
40systemctl restart grafana-server
41
42#  插件其实下载到了这里
43[root@zabbixserver ~]# du -sh /var/lib/grafana/plugins/alexanderzobnin-zabbix-app
4485M     /var/lib/grafana/plugins/alexanderzobnin-zabbix-app
45
46# 重启 grafana服务
47[root@zabbixserver ~]# systemctl restart grafana-server.service

启动 grafana 的 zabbix 插件


grafana Web 页面配置(连接 zabbix API 通过各种查询获取数据)

grafana Web 页面添加与配置图形 dashboard

导入模板
dashboards 官方模板

监控维度

任何一台机器(从下到上)

  • API 接口监控
  • 业务/app 监控
  • 服务监控
  • 系统监控
  • 硬件监控

按照访问顺序监控(分层):dns/cdn、安全组、负载、Web 数据库、存储、备份。

image.png

监控 DNS

用户访问流程 DNS 解析

DNS 解析

DNS 是否可用
可以 ping 通就表示 dns 可用
自定义带有参数的键值
check.ping[*]:"$1"是域名,可以解析返回 1,否则返回 0

dig 命令:yum install -y bind-utils

chmod +x /usr/lib/zabbix/externalscripts/check_dns_advanced.sh
[root@zabbixserver externalscripts]# ./check_dns_advanced.sh 8.8.8.8 zhizhexiaonan.com status 1

 1#!/bin/bash
 2
 3# check_dns_advanced.sh
 4# 用途:检查 DNS 服务器是否正常工作,并返回详细信息
 5# 依赖:dig 命令
 6
 7# 使用方法:./check_dns_advanced.sh <DNS服务器IP> <要查询的域名> <检查类型>
 8# 检查类型:
 9# status - 返回状态(0或1)
10# time - 返回响应时间(毫秒)
11# records - 返回记录数量
12
13if [ $# -ne 3 ]; then
14    echo "使用方法: $0 <DNS服务器IP> <要查询的域名> <检查类型>"
15    echo "检查类型: status|time|records"
16    echo "例如: $0 8.8.8.8 www.baidu.com status"
17    exit 1
18fi
19
20DNS_SERVER=$1
21DOMAIN=$2
22CHECK_TYPE=$3
23
24# 检查是否安装了 dig
25if ! command -v dig &> /dev/null; then
26    echo "请先安装 dig 命令 (dnsutils 包)"
27    exit 1
28fi
29
30# 执行 DNS 查询
31do_query() {
32    dig @"$DNS_SERVER" "$DOMAIN" +stats +tries=1 +time=2
33}
34
35# 检查 DNS 状态
36check_status() {
37   local result
38   local count
39   result=$(do_query)
40
41   count=$(echo "$result" | grep 121.199.170.240 | wc -l)
42   if [ "$count" -eq 1 ]; then
43       echo 1
44   else
45       echo 0
46   fi
47    #result=$(do_query)
48    #if [ $? -eq 0 ] && echo "$result" | grep -q "ANSWER: [1-9]"; then
49    #    echo 1
50    #else
51    #    echo 0
52    #fi
53}
54
55# 获取响应时间(毫秒)
56check_time() {
57    local result
58    result=$(do_query)
59    if [ $? -eq 0 ]; then
60        echo "$result" | grep "Query time:" | awk '{print $4}'
61    else
62        echo 9999
63    fi
64}
65
66# 获取返回的记录数量
67check_records() {
68    local result
69    result=$(do_query)
70    if [ $? -eq 0 ]; then
71        echo "$result" | grep "ANSWER:" | awk '{print $2}'
72    else
73        echo 0
74    fi
75}
76
77# 根据检查类型执行相应的检查
78case $CHECK_TYPE in
79    status)
80        check_status
81        ;;
82    time)
83        check_time
84        ;;
85    records)
86        check_records
87        ;;
88    *)
89        echo "无效的检查类型"
90        exit 1
91        ;;
92esac

使用增强版本时,你可以创建多个监控项

  • DNS 状态监控
    1check_dns_advanced.sh[8.8.8.8,zhizhexiaonan.com,status]
    

image.png

  • DNS 响应时间监控
    1check_dns_advanced.sh[8.8.8.8,zhizhexiaonan.com,time]
    

image.png

设置相应的触发器

  • DNS 服务器故障
    1{主机名:check_dns_advanced.sh[8.8.8.8,hizhexiaonan.com,status].last()}=0
    

image.png

  • DNS 响应时间过长
    1{主机名:check_dns_advanced.sh[8.8.8.8,hizhexiaonan.com,time].last()}>1000
    

image.png

域名过期时间

域名过期时间(yum install -y whois)还剩下多少天

check.domain[*]:"$1"是域名,显示这个域名还有多少天过期 ,过滤 Expiry

./check_domain_expiry.sh zhizhexiaonan.com
chmod +x /usr/lib/zabbix/externalscripts/check_domain_expiry.sh

 1### 脚本位置
 2vim /usr/lib/zabbix/externalscripts/check_domain_expiry.sh
 3#!/bin/bash
 4
 5# check_domain_expiry.sh
 6# 用途:检查域名过期时间并返回剩余天数
 7# 依赖:whois 命令
 8
 9# 检查是否安装了 whois
10if ! command -v whois &> /dev/null; then
11    echo "请先安装 whois 命令"
12    exit 1
13fi
14
15# 检查参数
16if [ $# -ne 1 ]; then
17    echo "使用方法: $0 domain.com"
18    exit 1
19fi
20
21DOMAIN=$1
22
23# 获取过期时间
24get_expiry_date() {
25    local domain=$1
26    local expiry_date=""
27    
28    # 获取 whois 信息
29    whois_info=$(whois "$domain")
30    
31    # 尝试多种可能的日期格式
32    expiry_date=$(echo "$whois_info" | grep -i "Expiry Date:" | cut -d':' -f2- | sed 's/^[[:space:]]*//' | head -1)
33    
34    if [ -z "$expiry_date" ]; then
35        expiry_date=$(echo "$whois_info" | grep -i "Registry Expiry Date:" | cut -d':' -f2- | sed 's/^[[:space:]]*//' | head -1)
36    fi
37    
38    if [ -z "$expiry_date" ]; then
39        expiry_date=$(echo "$whois_info" | grep -i "Expiration Date:" | cut -d':' -f2- | sed 's/^[[:space:]]*//' | head -1)
40    fi
41
42    # 处理可能的日期格式
43    if [[ $expiry_date == *"T"* ]]; then
44        # 处理类似 2024-03-20T15:41:46Z 格式
45        expiry_date=$(echo "$expiry_date" | cut -dT -f1)
46    fi
47    
48    echo "$expiry_date"
49}
50
51# 计算剩余天数
52calculate_days() {
53    local expiry_date=$1
54    local current_timestamp=$(date +%s)
55    local expiry_timestamp
56    
57    # 尝试转换日期
58    if ! expiry_timestamp=$(date -d "$expiry_date" +%s 2>/dev/null); then
59        echo "无法解析日期格式: $expiry_date" >&2
60        return 1
61    fi
62    
63    local days_remaining=$(( (expiry_timestamp - current_timestamp) / 86400 ))
64    echo "$days_remaining"
65}
66
67# 调试信息
68debug() {
69    echo "Domain: $DOMAIN" >&2
70    echo "Raw whois info:" >&2
71    whois "$DOMAIN" >&2
72}
73
74# 主逻辑
75expiry_date=$(get_expiry_date "$DOMAIN")
76
77if [ -z "$expiry_date" ]; then
78    debug
79    echo "无法获取域名 $DOMAIN 的过期时间"
80    exit 1
81fi
82
83if ! days_remaining=$(calculate_days "$expiry_date"); then
84    debug
85    exit 1
86fi
87
88echo "$days_remaining"

定义监控项

image.png

定义触发器

image.png

https 证书过期时间

chmod +x /usr/lib/zabbix/externalscripts/check_ssl_cert.sh
./check_ssl_cert.sh tstiot.chengtakj.com 443

 1#!/bin/bash
 2
 3# check_ssl_cert.sh
 4# 用途:检查 HTTPS 证书过期时间
 5# 依赖:openssl
 6
 7# 使用方法:./check_ssl_cert.sh <域名> <端口>
 8
 9# 检查参数
10if [ $# -lt 1 ] || [ $# -gt 2 ]; then
11    echo "使用方法: $0 <域名> [端口]"
12    echo "例如: $0 www.example.com 443"
13    exit 1
14fi
15
16DOMAIN=$1
17PORT=${2:-443}  # 如果没有指定端口,默认使用443
18
19# 检查是否安装了 openssl
20if ! command -v openssl &> /dev/null; then
21    echo "请先安装 openssl"
22    exit 1
23fi
24
25# 获取证书过期时间并计算剩余天数
26check_cert() {
27    local domain=$1
28    local port=$2
29    local end_date
30    local current_date
31    local end_epoch
32    local current_epoch
33    local days_remaining
34
35    # 获取证书结束时间
36    end_date=$(timeout 10 openssl s_client -connect "${domain}:${port}" -servername "${domain}" 2>/dev/null </dev/null \
37        | openssl x509 -noout -enddate 2>/dev/null \
38        | sed -n 's/notAfter=//p')
39
40    # 如果无法获取证书信息
41    if [ -z "$end_date" ]; then
42        echo "ERROR: 无法获取证书信息"
43        exit 1
44    fi
45
46    # 转换日期为时间戳
47    end_epoch=$(date -d "${end_date}" +%s)
48    current_epoch=$(date +%s)
49
50    # 计算剩余天数
51    days_remaining=$(( (end_epoch - current_epoch) / 86400 ))
52
53    echo "$days_remaining"
54}
55
56# 执行检查
57result=$(check_cert "$DOMAIN" "$PORT")
58
59# 输出结果
60if [[ "$result" =~ ^[0-9]+$ ]]; then
61    echo "$result"
62else
63    echo "0"
64fi

监控项

image.png

触发器

image.png

Web 监控

https://tstiot.chengtakj.com/

监控项

image.png

image.png

触发器

image.png

MySQL

MySQL 端使用 agent2 进行本地数据收集

1CREATE USER 'zabbix'@'localhost' IDENTIFIED BY 'xxxxxxxxxx';
2GRANT USAGE,REPLICATION CLIENT,PROCESS,SHOW DATABASES,SHOW VIEW ON *.* TO 'zabbix'@'localhost';
3FLUSH PRIVILEGES;

主机定义宏

1{$MYSQL.DSN} = tcp://localhost:3306
2{$MYSQL.USER} = zabbix
3{$MYSQL.PASSWORD} = your_password

image.png

关联 MySQL 模板
Configuration -> Templates -> 选择 "Template DB MySQL by Zabbix agent 2" -> Macros
点击 "Add" 添加相同的宏变量

image.png

创建主机宏

image.png

相关监控指标

连接相关

1- mysql.connections.max_used    # 同时使用的最大连接数
2- mysql.connections.current     # 当前活跃连接数
3- mysql.connections.aborted     # 已中断的连接数
4- mysql.connections.total       # 尝试连接到MySQL服务器的总数

性能指标

1- mysql.queries.rate           # 每秒查询率(QPS)
2- mysql.questions.rate        # 每秒客户端发送的语句数
3- mysql.slow_queries.rate     # 慢查询数量
4- mysql.operations.rate       # 各类操作数(select/insert/update/delete)

缓冲池(Buffer Pool)指标

1- mysql.buffer_pool.pages.total    # 缓冲池总页数
2- mysql.buffer_pool.pages.free     # 空闲页数
3- mysql.buffer_pool.pages.dirty    # 脏页数
4- mysql.buffer_pool.read_requests  # 缓冲池读请求数
5- mysql.buffer_pool.write_requests # 缓冲池写请求数

线程指标

1- mysql.threads.connected      # 当前连接的线程数
2- mysql.threads.running       # 活动线程数
3- mysql.threads.created      # 创建用于处理连接的线程数
4- mysql.threads.cached       # 线程缓存中的线程数

表缓存

1- mysql.table.open_cache.hits    # 表缓存命中数
2- mysql.table.open_cache.misses  # 表缓存未命中数

事务和锁

1- mysql.trx.count              # 当前事务数
2- mysql.locks.immediate        # 立即获得的表锁数量
3- mysql.locks.waited          # 需要等待的表锁数量

MySQL 自定义监控项

在 zabbix_Agent 端定义配置文件

1[root@iZbp19if2e8jvz5vlw7343Z zabbix_agent2.d]# cat /etc/zabbix/zabbix_agent2.d/mysql.conf 
2UserParameter=mysql.txq[*],sh /etc/zabbix/zabbix_agent2.d/mysql_trx_monitor.sh "$1"

在 zabbix_Agent 端自定义 shell 脚本

 1#!/bin/bash
 2
 3MYSQL_USER="zabbix"
 4MYSQL_PASS="xxxxxxx"
 5
 6# MySQL连接命令
 7MYSQL_CMD="mysql -u${MYSQL_USER} -p${MYSQL_PASS} -N"
 8
 9# 统计事务信息
10case "$1" in
11    'trx_count')
12        # 统计总事务数
13        ${MYSQL_CMD} -e "SELECT COUNT(*) FROM information_schema.innodb_trx;" 2>/dev/null
14        ;;
15    'long_trx')
16        # 统计运行超过10秒的事务数
17        ${MYSQL_CMD} -e "SELECT COUNT(*) FROM information_schema.innodb_trx WHERE TIME_TO_SEC(TIMEDIFF(NOW(), trx_started)) > 10;" 2>/dev/null
18        ;;
19    'locked_trx')
20        # 统计等待锁的事务数
21        ${MYSQL_CMD} -e "SELECT COUNT(*) FROM information_schema.innodb_trx WHERE trx_requested_lock_id IS NOT NULL;" 2>/dev/null
22        ;;
23    'long_queries')
24        # 统计运行超过10秒的查询数
25        ${MYSQL_CMD} -e "SELECT COUNT(*) FROM information_schema.processlist WHERE command='Query' AND time > 10;" 2>/dev/null
26        ;;
27    *)
28        echo "Usage: $0 {trx_count|long_trx|locked_trx|long_queries}"   
29        exit 1
30        ;;
31esac

重启 zabbix_agent2(加载新的配置文件)

1systemctl restart zabbix-agent2.service

监控项

 1### 监控项名称
 2mysql.txq.count
 3mysql.txq.long
 4mysql.txq.locked
 5mysql.txq.queries
 6
 7### 监控项键值
 8mysql.txq[trx_count]
 9mysql.txq[long_trx]
10mysql.txq[locked_trx]
11mysql.txq[long_queries]

3a466c1726df5ab6750cb6ac050ad58.png

DDNS

安装阿里云 aliyun-cli

 1# 下载
 2wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz -O aliyun-cli.tgz
 3
 4# 解压
 5tar -xvf aliyun-cli.tgz
 6
 7# 移动到正确位置
 8sudo mv aliyun /usr/local/bin/
 9
10# 设置执行权限
11sudo chmod +x /usr/local/bin/aliyun
12
13# 创建日志文件
14touch /var/log/dns_update.log
15
16# 授权日志文件
17chmod 777 /var/log/dns_update.log
18
19### aliyun-cli 命令时遇到的问题。由于 Zabbix Server 通常以 zabbix 用户运行
20
21chmod 777 -R  /var/lib/zabbix

脚本
chmod +x /usr/lib/zabbix/externalscripts/dns_update.sh

 1#!/bin/bash
 2
 3# 设置 HOME 环境变量
 4export HOME="/var/lib/zabbix"
 5
 6# 确保 .aliyun 目录存在
 7mkdir -p "$HOME/.aliyun"
 8chown zabbix:zabbix "$HOME/.aliyun"
 9
10# 配置信息
11ACCESS_KEY_ID="LTAI5tJipLu2sQ2G5RmsZXnA"
12ACCESS_KEY_SECRET="1r43YfsGglevTOzeYFv2KEwUBwHcVl"
13DOMAIN="abc1024.tech"      # 你的域名
14RR="www"                   # 主机记录
15NEW_IP="192.168.1.1"       # 新的IP地址
16LOG_FILE="/var/log/dns_update.log"
17
18# 日志函数
19log_message() {
20    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
21    echo "$1"
22}
23
24# 确保日志目录存在
25# mkdir -p "$(dirname "$LOG_FILE")"
26
27
28# 配置aliyun CLI
29aliyun configure set \
30    --profile default \
31    --mode AK \
32    --region cn-hangzhou \
33    --access-key-id "$ACCESS_KEY_ID" \
34    --access-key-secret "$ACCESS_KEY_SECRET"
35
36# 获取记录ID
37log_message "正在查询记录 $RR.$DOMAIN ..."
38
39RECORD_INFO=$(aliyun alidns DescribeDomainRecords \
40    --DomainName "$DOMAIN" \
41    --RRKeyWord "$RR" \
42    --Type A)
43
44# 打印调试信息
45echo "Record Info: $RECORD_INFO"
46
47# 检查API调用是否成功
48if [ $? -ne 0 ]; then
49    log_message "错误: 无法获取记录信息"
50    exit 1
51fi
52
53# 提取记录ID
54RECORD_ID=$(echo "$RECORD_INFO" |  grep RecordId | awk -F'"' '{print $4}')
55
56
57# 获取当前IP
58CURRENT_IP=$(echo "$RECORD_INFO" | grep -o '"Value":"[^"]*"' | cut -d'"' -f4)
59
60log_message "当前记录: $RR.$DOMAIN -> $CURRENT_IP"
61log_message "准备更新为: $NEW_IP"
62
63# 更新DNS记录
64if [ "$CURRENT_IP" != "$NEW_IP" ]; then
65    log_message "正在更新DNS记录..."
66
67    UPDATE_RESULT=$(aliyun alidns UpdateDomainRecord \
68        --RecordId "$RECORD_ID" \
69        --RR "$RR" \
70        --Type "A" \
71        --Value "$NEW_IP")
72
73    if [ $? -eq 0 ]; then
74        log_message "DNS记录更新成功"
75    else
76        log_message "DNS记录更新失败: $UPDATE_RESULT"
77        exit 1
78    fi
79else
80    log_message "IP地址相同,无需更新"
81fi

添加 Action

image.png

image.png

TimescaleDB VS TRDB(Mysql)

优点

  • 更快的数据写入(3-5 倍)
  • 更高效的查询性能(特别是时序查询)
  • 更好的数据压缩(可达 2-10 倍)
  • 自动分区管理
  • 更适合处理大规模时序数据

适用场景

  • 大规模部署(10000+NVPS)
  • 需要长期存储历史数据
  • 有复杂的时序查询需求
  • 监控项超过 100000 个
  • 对查询性能要求高

资源消耗

  • CPU:更多核心有助于并行查询
  • 内存:建议 16GB 以上
  • 磁盘:SSD 最佳
  • 网络:高带宽需求

image.png

image.png

成本考虑

MySQL 硬件成本较低

TimescaleDB 需要更好的硬件,成本更高

选择建议

  • 小规模监控:MySQL 足够
  • 大规模监控:TimescaleDB 性价比更高

Zabbix 中查看 NVPS (每秒新值数)

 1-- 查看最近一小时的 NVPS
 2SELECT COUNT(*) / 3600 as nvps 
 3FROM history 
 4WHERE clock > UNIX_TIMESTAMP(NOW() - INTERVAL 1 HOUR);
 5
 6-- 更详细的查询(包含所有历史表)
 7SELECT 
 8    (
 9        (SELECT COUNT(*) FROM history) +
10        (SELECT COUNT(*) FROM history_uint) +
11        (SELECT COUNT(*) FROM history_str) +
12        (SELECT COUNT(*) FROM history_text) +
13        (SELECT COUNT(*) FROM history_log)
14    ) / (
15        SELECT (MAX(clock) - MIN(clock))
16        FROM history
17    ) as nvps;

image.png

image.png

zabbix 基于 NVPS 作为判断条件, 硬件配置 4 核处理器,8G 内存,SSD 硬盘 40GB,应该选择 MySQL 还是 TimescaleDB ?

选择 MySQ 原因

硬件配置分析

  • CPU (4 核):不满足 TimescaleDB 推荐的最低要求(8 核)
  • 内存 (8GB):低于 TimescaleDB 推荐的最低要求(16GB)
  • 存储 (40GB SSD):对于初期使用够用,但需要注意监控使用量

MySQL 适配性

  • 这个配置适合运行 MySQL
  • MySQL 在这个配置下可以支持约 1000-2000 NVPS
  • 资源占用相对较小

TimescaleDB 不适合的原因

  • 硬件规格不足以发挥 TimescaleDB 的优势
  • 可能会出现性能瓶颈
  • 内存压力会很大

Prometheus VS Zabbix VS Nagios

  • 如果你正在使用或计划使用 Kubernetes 或其他现代云技术,且需要强大的时间序列数据分析能力,Prometheus 是最佳选择。
  • 如果你需要广泛的操作系统和应用程序支持,并且希望有灵活的配置和强大的自定义能力,Zabbix 是个好选择。
  • 如果你需要快速上手且对性能有基本要求,同时希望有成熟的社区支持和大量的插件资源,Nagios 是不错的选择。

作者:Soulboy