├── .DS_Store ├── LICENSE ├── README.md ├── charter-03 ├── .DS_Store ├── Zabbix书籍V2-第3章-操作命令.pdf └── readme.md ├── charter-05 ├── .DS_Store ├── Zabbix书籍V2-第5章-操作命令.pdf └── readme.md ├── charter-06 ├── .DS_Store ├── Zabbix书籍V2-第6章-操作命令.pdf ├── img │ └── image-20190912103506648.png └── readme.md ├── charter-08 ├── Zabbix书籍V2-第8章-操作命令.pdf └── readme.md ├── charter-09 ├── Zabbix书籍V2-第9章-操作命令.pdf └── readme.md ├── charter-10 ├── Zabbix书籍V2-第10章-操作命令.pdf └── readme.md ├── charter-11 ├── Zabbix书籍V2-第11章-操作命令.pdf ├── img │ ├── image-20190912140906308.png │ ├── image-20190912141013345.png │ ├── image-20190912141055263.png │ ├── image-20190912141125266.png │ ├── image-20190912141145900.png │ ├── image-20190912141255101.png │ ├── image-20190912141327627.png │ ├── image-20190912141344256.png │ ├── image-20190912141438566.png │ ├── image-20190912141500653.png │ ├── image-20190912141528027.png │ ├── image-20190912141549043.png │ ├── image-20190912141625547.png │ ├── image-20190912141658896.png │ ├── image-20190912141720320.png │ ├── image-20190912141745765.png │ ├── image-20190912141801977.png │ └── image-20190912141829144.png └── readme.md ├── charter-12 ├── Zabbix书籍V2-第12章-操作命令.pdf └── readme.md ├── charter-13 ├── Zabbix书籍V2-第13章-操作命令.pdf └── readme.md ├── charter-14 ├── Zabbix书籍V2-第14章-操作命令.pdf └── readme.md ├── charter-15 ├── Zabbix书籍V2-第15章-操作命令.pdf └── readme.md └── 勘误 ├── .DS_Store └── 第一次印刷 └── readme.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/.DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zabbix_v2 2 | 《Zabbix企业级分布式监控系统第2版》随书代码 3 | -------------------------------------------------------------------------------- /charter-03/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-03/.DS_Store -------------------------------------------------------------------------------- /charter-03/Zabbix书籍V2-第3章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-03/Zabbix书籍V2-第3章-操作命令.pdf -------------------------------------------------------------------------------- /charter-03/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | 8 | 9 | # 30页 10 | 11 | ```shell 12 | 6.时间同步需求 13 | Zabbix-Server对时间的精准要求比较高,时间对数据的计算等都有影响,因此必须设置NTP自动同步时间。 14 | 15 | shell# yum install ntp -y 16 | shell# systemctl enable ntpd 17 | shell# systemctl start ntpd 18 | 19 | 当然,也可以使用crontab进行同步,但在实际的生产环境中不推荐定时任务的同步,而是推荐上面的NTP同步方式。如下所示,使用crontab进行时间同步。 20 | 21 | */30 * * * * /usr/sbin/ntpdate pool.ntp.org 22 | ``` 23 | 24 | 25 | 26 | # 31页 27 | 28 | ```shell 29 | 安装Zabbix的RPM包软件仓库官方源,如图3-5所示。 30 | 31 | #CentOS 7,4.X版本的安装 32 | shell# rpm -ivh http://repo.zabbix.com/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-1.el7.noarch.rpm 33 | 34 | #CentOS 7,3.X版本的安装 35 | shell# rpm -ivh http://repo.zabbix.com/zabbix/3.0/rhel/7/x86_64/zabbix-release-3.0-1.el7.noarch.rpm 36 | 注意:由于软件版本的更新,如果以上链接失效,读者可在http://repo.zabbix.com/ zabbix/4.0/rhel/7/x86_64/中找到软件包。 37 | ``` 38 | 39 | # 33-34页 40 | 41 | ```shell 42 | 安装Zabbix-Server服务器端,由于服务器端也是需要监控的,故这里也一并安装了Zabbix-Agent。 43 | 44 | #此处是4.0的安装命令,3.0的安装命令与之相同 45 | shell# yum install zabbix-server-mysql zabbix-web-mysql zabbix-agent zabbix-get -y 46 | #在Zabbix-Server服务器上安装Zabbix-Agent,是为了通过Agent方式监控Zabbix-Sever服务器本身的运行情况 47 | 48 | 此过程安装的软件包如下: 49 | 50 | Installing : libzip-0.10.1-8.el7.x86_64 1/37 51 | Installing : php-common-5.4.16-45.el7.x86_64 2/37 52 | Installing : php-bcmath-5.4.16-45.el7.x86_64 3/37 53 | …… 54 | Installing : php-pdo-5.4.16-45.el7.x86_64 8/37 55 | Installing : php-mysql-5.4.16-45.el7.x86_64 9/37 56 | …… 57 | Installing : httpd-2.4.6-80.el7.centos.1.x86_64 28/37 58 | Installing : php-5.4.16-45.el7.x86_64 29/37 59 | …… 60 | Installing : zabbix-web-mysql-4.0.0-1.1rc3.el7.noarch 32/37 61 | Installing : zabbix-web-4.0.0-1.1rc3.el7.noarch 33/37 62 | Installing : fping-3.10-1.el7.x86_64 34/37 63 | Installing : zabbix-server-mysql-4.0.0-1.1rc3.el7.x86_64 35/37 64 | Installing : zabbix-agent-4.0.0-1.1rc3.el7.x86_64 36/37 65 | Installing : zabbix-get-4.0.0-1.1rc3.el7.x86_64 37/37 66 | 67 | 3.2.2 安装MySQL 68 | 在CentOS 7系统包仓库安装源中,我们需要安装mariadb-server,而不是MySQL数据库服务(7.0以后版本用MariaDB替换了MySQL),命令如下: 69 | 70 | shell# yum -y install mariadb-server 71 | 72 | 所需的依赖包如下: 73 | 74 | Installing : 1:mariadb-5.5.56-2.el7.x86_64 1/10 75 | Installing : libaio-0.3.109-13.el7.x86_64 2/10 76 | Installing : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64 3/10 77 | Installing : perl-Net-Daemon-0.48-5.el7.noarch 4/10 78 | Installing : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64 5/10 79 | Installing : perl-IO-Compress-2.061-2.el7.noarch 6/10 80 | Installing : perl-PlRPC-0.2020-14.el7.noarch 7/10 81 | Installing : perl-DBI-1.627-4.el7.x86_64 8/10 82 | Installing : perl-DBD-MySQL-4.023-6.el7.x86_64 9/10 83 | Installing : 1:mariadb-server-5.5.56-2.el7.x86_64 10/10 84 | 85 | 修改MySQL配置文件如下(粗体字部分很重要),使用以下命令: 86 | 87 | shell# vi /etc/my.cnf 88 | [mysqld] 89 | datadir=/var/lib/mysql 90 | socket=/var/lib/mysql/mysql.sock 91 | user=mysql 92 | # Disabling symbolic-links is recommended to prevent assorted security risks 93 | symbolic-links=0 94 | character-set-server=utf8 #设置字符集为UTF-8 95 | innodb_file_per_table=1 #让InnoDB的每个表文件单独存储 96 | 97 | [mysqld_safe] 98 | log-error=/var/log/mysqld.log 99 | pid-file=/var/run/mysqld/mysqld.pid 100 | # 需要注意的是,以上MySQL配置参数仅满足小规模监控环境使用,适合初次接触MySQL的读者调整。 101 | # 如监控环境为中型规模(如1000设备以上),需要调整更多的MySQL配置参数,可参考https://github.com/zabbix-book/MySQL_conf中提供的参数。 102 | # 如监控环境为大型规模(如8000设备以上),需要使用MySQL集群相关技术,如读写分离,数据库集群等。建议熟悉MySQL集群技术的读者采用。 103 | 104 | 启动服务,使用以下命令: 105 | 106 | shell# systemctl start mariadb #启动服务 107 | 108 | 设置开机自启动,使用以下命令: 109 | 110 | shell# systemctl enable mariadb #设置开机自启动 111 | Created symlink from /etc/systemd/system/multi-user.target.wants/mariadb. service to /usr/lib/systemd/system/mariadb.service. 112 | ``` 113 | 114 | 115 | 116 | # 35页 117 | 118 | ```shell 119 | 1.创建Zabbix数据库 120 | 首先设置MySQL的root用户密码,然后创建zabbix数据库,设置访问策略,使用以下命令: 121 | 122 | shell# mysqladmin -uroot password admin #设置root用户密码为admin 123 | shell# mysql -uroot -padmin #登录MySQL 124 | #创建数据库,名称为zabbix,并将其字符集设置为UTF8 125 | mysql> create database zabbix character set utf8; 126 | #设置zabbix数据库的所有权限,允许用户zabbix的IP地址127.0.0.1和localhost访问,并将zabbix账号的密码设置为zabbix 127 | mysql> grant all privileges on zabbix.* to zabbix@'localhost' identified by 'zabbix'; 128 | mysql> grant all privileges on zabbix.* to zabbix@'127.0.0.1' identified by 'zabbix'; 129 | #刷新权限,使其立即生效 130 | mysql> flush privileges; 131 | ``` 132 | 133 | ```shell 134 | 导入Zabbix库的数据文件,使用以下命令: 135 | 136 | shell# cd /usr/share/doc/zabbix-server-mysql-4.0.0 #进入对应版本目录 137 | shell# gunzip create.sql.gz #将SQL文件解压缩 138 | shell# mysql -uzabbix -pzabbix -h127.0.0.1 #以zabbix用户登录 139 | mysql> use zabbix #切换到zabbix数据库 140 | mysql> source /usr/share/doc/zabbix-server-mysql-4.0.0/create.sql; 141 | #导入SQL文件 142 | #上面的4.0.0代表实际的版本,读者拿到本书后,其版本会发生变化,因此可以通过命令ls /usr/ share/doc|grep zabbix 来查看实际路径 143 | #create.sql是zabbix源码包中的3个SQL文件的合集,即分别为schame.sql、images.sql和data.sql,其中schema.sql是表结构;images.sql是图片相关数据; data.sql是模板等相关数据 144 | # 如果是以源码方式安装Zabbix-Server的,则需要将这3个文件全部导入 145 | # 如果是以源码方式安装Zabbix-Porxy的,则只能导入schames.sql 146 | 147 | Zabbix-Proxy的安装和配置是后续章节的内容,这里仅列出SQL导入命令,以便加深印象。 148 | 149 | shell# cd /usr/share/doc/zabbix-proxy-mysql-4.0.0 #进入对应版本目录 150 | shell# gunzip schema.sql.gz #将SQL文件解压缩 151 | mysql> use zabbix-porxy #切换到zabbix-proxy库 152 | mysql> source /usr/share/doc/zabbix-proxy-mysql-4.0.0/schema.sql; 153 | #导入SQL文件 154 | ``` 155 | 156 | # 36页 157 | 158 | ```shell 159 | 配置zabbix_server.conf文件如下: 160 | 1.默认参数 161 | 162 | shell# egrep -v "(^#|^$)" /etc/zabbix/zabbix_server.conf 163 | LogFile=/var/log/zabbix/zabbix_server.log 164 | LogFileSize=0 165 | PidFile=/var/run/zabbix/zabbix_server.pid 166 | SocketDir=/var/run/zabbix 167 | DBName=zabbix 168 | DBUser=zabbix 169 | SNMPTrapperFile=/var/log/snmptrap/snmptrap.log 170 | Timeout=4 171 | AlertScriptsPath=/usr/lib/zabbix/alertscripts 172 | ExternalScripts=/usr/lib/zabbix/externalscripts 173 | LogSlowQueries=3000 174 | 2.修改后的参数(可参考) 175 | 176 | shell# egrep -v "(^#|^$)" /etc/zabbix/zabbix_server.conf 177 | LogFile=/var/log/zabbix/zabbix_server.log 178 | LogFileSize=0 179 | PidFile=/var/run/zabbix/zabbix_server.pid 180 | DBHost=127.0.0.1 #需要修改 181 | DBName=zabbix #默认 182 | DBUser=zabbix #默认 183 | DBPassword=zabbix #需要修改 184 | DBSocket=/var/lib/mysql/mysql.sock #默认 185 | DBPort=3306 #默认 186 | StartPollers=100 #约5台服务器开一个进程,最大1000 187 | StartIPMIPollers=10 #视IPMI监控主机个数而定 188 | StartPollersUnreachable=10 #不可达主机重试获取数据进程个数 189 | StartTrappers=10 #Trapper进程个数 190 | StartPingers=10 #Ping进程个数 191 | StartDiscoverers=10 #自动发现进程个数 192 | SNMPTrapperFile=/var/log/snmptt/snmptt.log 193 | MaxHousekeeperDelete=500 194 | CacheSize=256M #可根据实际情况修改 195 | HistoryCacheSize=128M #可根据实际情况修改 196 | TrendCacheSize=128M #可根据实际情况修改 197 | HistoryTextCacheSize=128M #可根据实际情况修改 198 | ValueCacheSize=2048M #可根据实际情况修改 199 | Timeout=30 #此处需要修改,最大执行时间长(30秒以内) 200 | TrapperTimeout=300 201 | UnreachablePeriod=45 202 | UnavailableDelay=60 203 | UnreachableDelay=15 204 | AlertScriptsPath=/etc/zabbix/alertscripts 205 | ExternalScripts=/etc/zabbix/externalscripts 206 | FpingLocation=/usr/sbin/fping 207 | LogSlowQueries=10000 208 | StartProxyPollers=50 209 | ProxyConfigFrequency=3600 210 | 211 | 以上参数只需关注粗体字部分,这部分为性能参数,需要根据实际情况进行调整。 212 | ``` 213 | 214 | 215 | 216 | # 37页 217 | 218 | ```shell 219 | shell# mkdir -p /etc/zabbix/alertscripts /etc/zabbix/externalscripts 220 | ``` 221 | 222 | 223 | 224 | ```shell 225 | 3.开启Zabbix-Server服务 226 | 启动Zabbix-Server相关服务,使用以下命令: 227 | 228 | #CentOS7 229 | shell# systemctl start zabbix-server 230 | shell# systemctl start httpd 231 | #查看进程 232 | shell# ps -ef |grep zabbix 233 | #查看日志 234 | shell# tail -f /var/log/zabbix/zabbix_server.log 235 | #如遇到此提示connection to database 'zabbix' failed: [1045] Access denied for user 'zabbix'@'localhost' (using password: NO),请检查/etc/zabbix/zabbix_ server.conf配置文件数据库连接相关信息是否配置正确 236 | 237 | 添加开机启动项,使用以下命令: 238 | 239 | shell# systemctl enable zabbix-server 240 | Created symlink from /etc/systemd/system/multi-user.target.wants/zabbix-server.service to /usr/lib/systemd/system/zabbix-server.service. 241 | shell# systemctl enable httpd 242 | Created symlink from /etc/systemd/system/multi-user.target.wants/httpd.service to /usr/lib/systemd/system/httpd.service. 243 | ``` 244 | 245 | 246 | 247 | # 38页 248 | 249 | ```shell 250 | 1.防火墙的设置 251 | 如CentOS操作系统存在防火墙,则需允许相关端口能够访问,配置命令如下: 252 | 253 | #CentOS 6操作系统防火墙规则设置 254 | shell# iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT 255 | shell# iptables -A IN_public_allow -p tcp -m tcp --dport 80 -m conntrack --ctstate NEW -j ACCEPT 256 | shell# iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 10051 -j ACCEPT 257 | shell# iptables -A OUTPUT -m state --state NEW -m tcp -p tcp --dport 10050 -j ACCEPT 258 | shell# iptables -A INPUT -m state --state NEW -m tcp -p tcp --sport 10050 -j ACCEPT 259 | #规则设置完成后,均需永久保存,用如下语句 260 | shell# iptables-save >/tmp/ip.txt 261 | shell# iptables-restore 301 | Options FollowSymLinks 302 | AllowOverride None 303 | Order allow,deny 304 | Allow from all 305 | php_value date.timezone Asia/Shanghai #修改此参数 306 | php_value max_execution_time 300 307 | php_value post_max_size 16M 308 | php_value max_input_time 300 309 | php_value memory_limit 128M 310 | php_value upload_max_filesize 2M 311 | 312 | shell# systemctl restart httpd 313 | ``` 314 | 315 | 316 | 317 | # 43页 318 | 319 | ```shell 320 | Zabbix-Web连接数据库和Zabbix-Server端口的相关配置信息如下: 321 | shell# cat /etc/zabbix/web/zabbix.conf.php 322 | 376 | ``` 377 | 378 | 379 | 380 | # 49-50页 381 | 382 | ```shell 383 | shell# zabbix_server -R housekeeper_execute 384 | zabbix_server [1572]: command sent successfully 385 | shell# tail -f /var/log/zabbix/zabbix_server.log 386 | 1325:20181013:094504.049 forced execution of the housekeeper 387 |   1325:20181013:094504.049 executing housekeeper 388 |   1325:20181013:094504.494 housekeeper [deleted 2255 hist/trends, 0 items/triggers, 27 events, 1716 problems, 0 sessions, 0 alarms, 6 audit items in 0.444276 sec, idle for 1 hour(s)] 389 | 在线执行重载配置缓存,命令如下: 390 | 391 | shell## zabbix_server -R config_cache_reload 392 | shell# tail -f /var/log/zabbix/zabbix_server.log #查看日志 393 | 1321:20181013:094908 forced reloading of the configuration cache 394 | 在线调整日志运行级别,命令如下: 395 | 396 | #降低日志运行级别,执行一次,降低一个级别。当前日志级别为4 397 | shell# zabbix_server -R log_level_decrease 398 | zabbix_server [2111]: command sent successfully 399 | shell# tail -f /var/log/zabbix/zabbix_server.log #查看日志 400 | 1349:20181013:095908.3 log level has been decreased to 3 (warning) 401 | 402 | #降低日志运行级别,执行一次,降低一个级别。当前日志级别为3 403 | shell# zabbix_server -R log_level_decrease 404 | zabbix_server [2120]: command sent successfully 405 | shell# tail -f /var/log/zabbix/zabbix_server.log #查看日志 406 | 1361:20181013:095920.244 log level has been decreased to 2 (error) 407 | 408 | #增加日志运行级别,执行一次,增加一个级别。当前日志级别为0 409 | shell# zabbix_server -R log_level_increase 410 | zabbix_server [2256]: command sent successfully 411 | shell# tail -f /var/log/zabbix/zabbix_server.log #查看日志 412 | 1360:20181013:100341 log level has been increased to 1 (critical) 413 | 414 | #调整某个进程(pid)的日志运行级别 415 | shell# ps -ef |grep zabbix 416 | zabbix 955    /usr/sbin/zabbix_server -c /etc/zabbix/zabbix_server.conf 417 | zabbix  1321 955  0 09:40 ? 00:00:00 /usr/sbin/zabbix_server: configuration syncer [synced configuration in 0.030468 sec, idle 60 sec] 418 | zabbix  1322 955  0 09:40 ? 00:00:00 /usr/sbin/zabbix_server: alerter #1 started 419 | zabbix  1323 955  0 09:40 ? 00:00:00 /usr/sbin/zabbix_server: alerter #2 started 420 | zabbix  1324 955  0 09:40 ? 00:00:00 /usr/sbin/zabbix_server: alerter #3 started 421 | 422 | #调整进程pid为1322的日志运行级别 423 | shell# zabbix_server -R log_level_increase=1322 424 | shell# tail -f /var/log/zabbix/zabbix_server.log #查看日志 425 | 1322:20181013:100800.998 log level has been increased to 2 (error) 426 | 427 | #调整增加poller进程的日志运行级别。 428 | shell# zabbix_server -R log_level_increase=poller 429 | 430 | #调整增加poller的第3个进程的日志运行级别。 431 | shell# zabbix_server -R log_level_increase=poller,3 432 | ``` 433 | 434 | 435 | 436 | # 51页 437 | 438 | ```shell 439 | 在这里,我们对需要进行监控的客户端服务器安装Zabbix-Agent,使用RPM方式进行安装,命令如下所示: 440 | 441 | shell# rpm -ivh http://repo.zabbix.com/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-1.el7.noarch.rpm #安装Zabbix官方的yum源 442 | shell# yum install -y zabbix zabbix-agent 443 | # 由于Zabbix-Server服务器本身也需要监控,所以在Zabbix-Server服务器中也同样需要安装Zabbix-Agent 444 | ``` 445 | 446 | ```shell 447 | 如操作系统开启了防火墙,为允许端口能够正常通信,则需使用下列命令进行配置: 448 | 449 | #CentOS 6 450 | shell# vi /etc/sysconfig/iptables 451 | -A INPUT -m state --state NEW -m tcp -p tcp --dport 10050 -j ACCEPT 452 | -A OUTPUT -m state --state NEW -m tcp -p tcp --dport 10051 -j ACCEPT 453 | shell# service iptables restart 454 | #CentOS 7 455 | shell# firewall-cmd --permanent --add-port=10050/tcp 456 | shell# firewall-cmd --reload 457 | ``` 458 | 459 | 460 | 461 | # 52页 462 | 463 | ```shell 464 | shell# egrep -v "(^#|^$)" /etc/zabbix/zabbix_agentd.conf 465 | PidFile=/var/run/zabbix/zabbix_agentd.pid #pid文件路径 466 | LogFile=/var/log/zabbix/zabbix_agentd.log #日志文件路径 467 | LogFileSize=0 #日志切割大小,0表示不切割 468 | Server=127.0.0.1,10.0.2.50 #被动模式,Zabbix-Server的IP地址 469 | ServerActive=127.0.0.1,10.0.2.50 #主动模式,Zabbix-Server的IP地址 470 | Hostname=Zabbix server #本机的Hostname,使用主动模式则必须配置 471 | Include=/etc/zabbix/zabbix_agentd.d/ #包含的子配置文件 472 | UnsafeUserParameters=1 #启用特殊字符,用于自定义监控 473 | ``` 474 | 475 | 476 | 477 | ```shell 478 | 配置完成后,使用如下命令进行启动Zabbix-Agent: 479 | #CentOS 7 480 | shell# systemctl enable zabbix-agent #添加到开机启动项 481 | shell# systemctl start zabbix-agent #启动服务 482 | 483 | #CentOS 6 484 | shell# chkconfig zabbix-agent on #添加到开机启动项 485 | shell# service zabbix-agent start #启动服务 486 | ``` 487 | 488 | 489 | 490 | # 53页 491 | 492 | ```shell 493 | 在CentOS下配置SNMP监控,命令如下: 494 | 495 | shell# yum -y install net-snmp 496 | shell# vim /etc/snmp/snmpd.conf 497 | com2sec mynetwork 192.168.0.240 public_monitor 498 | com2sec mynetwork 127.0.0.1 public 499 | group MyROGroup v2c mynetwork 500 | access MyROGroup "" any noauth prefix all none none 501 | view all included .1 80 502 | 503 | #CentOS 7 504 | shell# systemctl enable snmpd #添加到开机启动项 505 | shell# systemctl start snmpd #启动服务 506 | 507 | #CentOS 6 508 | shell# chkconfig snmpd on #添加到开机启动项 509 | shell# service snmpd restart #启动服务 510 | ``` 511 | 512 | # 54页 513 | 514 | ```shell 515 | 使用以下命令注册Zabbix Agent服务,运行结果如图3-26所示。 516 | cmd> zabbix_agentd.exe --install -c "c:\Program Files\zabbix_agents_ 4.0.0.win\conf\zabbix_agentd.win.conf" #路径中有空格,应该用双引号,-c后面是配置文件路径 517 | ``` 518 | 519 | 520 | 521 | # 55页 522 | 523 | ```shell 524 | (1)采用Windows的net命令控制服务。 525 | 启动服务: 526 | 527 | C:\> net start "Zabbix Agent" 528 | Zabbix Agent 服务正在启动 . 529 | Zabbix Agent 服务已经启动成功。 530 | 停止服务: 531 | 532 | C:\> net stop "Zabbix Agent" 533 | Zabbix Agent 服务已成功停止。 534 | (2)采用程序命令方式控制服务。 535 | 启动服务: 536 | 537 | c:\Program Files\zabbix_agents_4.0.0.win\bin\win64> zabbix_agentd.exe -s -c "c:\Program Files\zabbix_agents_4.0.0.win\conf\zabbix_agentd.win.conf" 538 | Zabbix_agentd.exe [8456]: service [Zabbix Agent] started successfully 539 | 停止服务: 540 | 541 | c:\Program Files\zabbix_agents_4.0.0.win\bin\win64> zabbix_agentd.exe -x -c "c:\Program Files\zabbix_agents_4.0.0.win\conf\zabbix_agentd.win.conf" 542 | Zabbix_agentd.exe [9040]: service [Zabbix Agent] stopped successfully 543 | 卸载服务: 544 | 545 | c:\Program Files\zabbix_agents_4.0.0.win\bin\win64> zabbix_agentd.exe -d -c "c:\Program Files\zabbix_agents_4.0.0.win\conf\zabbix_agentd.win.conf" 546 | zabbix_agentd.exe [2440]: service [Zabbix Agent] uninstalled successfully 547 | zabbix_agentd.exe [2440]: event source [Zabbix Agent] uninstalled successfully 548 | ``` 549 | 550 | # 57页 551 | 552 | ```shell 553 | shell# zabbix_get -s 192.168.0.240 -k system.uname 554 | Linux zabbix.itnihao.com 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 X86_64 555 | shell# zabbix_get -s 192.168.0.103 -k system.uname 556 | Windows ITNIHAO-COM 6.1.7601 Microsoft Windows 7 Ultimate Edition Service Pack 1 x64 557 | shell# zabbix_get -s 192.168.0.240 -p 10050 -I 127.0.0.1 -k system.uname 558 | Linux zabbix.itnihao.com 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 X86_64 559 | ``` 560 | 561 | 562 | 563 | # 60页 564 | 565 | ```sql 566 | mysql> select table_name, (data_length+index_length)/1024/1024 as total_mb, table_rows from information_schema.tables where table_schema='zabbix'; 567 | ``` 568 | 569 | 570 | 571 | # 62-66页 572 | 573 | 代码在 https://github.com/zabbix-book/partitiontables_zabbix 574 | 575 | 576 | 577 | # 67页 578 | 579 | ```mysql 580 | 清空语句如下: 581 | mysql> use zabbix; 582 | mysql> truncate table history; 583 | mysql> optimize table history; 584 | mysql> truncate table history_str; 585 | mysql> optimize table history_str; 586 | mysql> truncate table history_uint; 587 | mysql> optimize table history_uint; 588 | mysql> truncate table history_log; 589 | mysql> optimize table history_log; 590 | mysql> truncate table history_text; 591 | mysql> optimize table history_text; 592 | mysql> truncate table trends; 593 | mysql> optimize table trends; 594 | mysql> truncate table trends_uint; 595 | mysql> optimize table trends_uint; 596 | ``` 597 | 598 | 599 | 600 | ```sql 601 | 2.运行表分区脚本 602 | 为了防止网络中断后引起脚本运行中断而造成数据库故障,我们应该选用screen后台执行的方法。如果没有screen程序,请先安装(运维人员要处处具有谨慎的态度)。 603 | 604 | shell# screen -R zabbix 605 | shell# sh partitiontables_zabbix.sh 606 | table history create partitions p20180716 607 | table history_log create partitions p20180716 608 | table history_str create partitions p20180716 609 | table history_text create partitions p20180716 610 | table history_uint create partitions p20180716 611 | table history create partitions p20180717 612 | table history_log create partitions p20180717 613 | table history_str create partitions p20180717 614 | table history_text create partitions p20180717 615 | table history_uint create partitions p20180717 616 | #中间省略部分输出内容 617 | table trends create partitions p201807 618 | table trends_uint create partitions p201807 619 | table trends create partitions p201808 620 | table trends_uint create partitions p201808 621 | ``` 622 | 623 | 624 | 625 | # 68页 626 | 627 | ``` 628 | 进入screen,可以查看后台运行的任务: 629 | shell# screen -R zabbix 630 | 631 | shell# crontab -e 632 | 1 0 * * * /usr/sbin/partitiontables_zabbix.sh 633 | Shell# chmod 700 /usr/sbin/partitiontables_zabbix.sh 634 | ``` 635 | 636 | 637 | 638 | ```sql 639 | 验证表分区是否成功,可以查看history表结构,输出如下: 640 | 641 | MariaDB [zabbix]> show create table history\G; 642 | *************************** 1. row *************************** 643 | Table: history 644 | Create Table: CREATE TABLE `history` ( 645 | `itemid` bigint(20) unsigned NOT NULL, 646 | `clock` int(11) NOT NULL DEFAULT '0', 647 | `value` double(16,4) NOT NULL DEFAULT '0.0000', 648 | `ns` int(11) NOT NULL DEFAULT '0', 649 | KEY `history_1` (`itemid`,`clock`) 650 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 651 | /*!50100 PARTITION BY RANGE ( clock) 652 | (PARTITION p20180716 VALUES LESS THAN (1531756799) ENGINE = InnoDB, 653 | PARTITION p20180717 VALUES LESS THAN (1531843199) ENGINE = InnoDB, 654 | PARTITION p20180718 VALUES LESS THAN (1531929599) ENGINE = InnoDB, 655 | PARTITION p20180719 VALUES LESS THAN (1532015999) ENGINE = InnoDB, 656 | PARTITION p20180720 VALUES LESS THAN (1532102399) ENGINE = InnoDB, 657 | PARTITION p20180721 VALUES LESS THAN (1532188799) ENGINE = InnoDB, 658 | PARTITION p20180722 VALUES LESS THAN (1532275199) ENGINE = InnoDB, 659 | PARTITION p20180723 VALUES LESS THAN (1532361599) ENGINE = InnoDB)*/ 660 | /*粗体字部分为表分区*/ 661 | 1 row in set (0.00 sec) 662 | ERROR: No query specified 663 | MariaDB [zabbix]> 664 | ``` 665 | 666 | 667 | 668 | # 69页 669 | 670 | ```sql 671 | 在表分区中,使用的是时间戳格式进行日期区间划分,如读者需要将时间转换为时间戳数值格式,使用如下命令进行转换: 672 | 673 | shell# date -d "2018-07-16" +%s 674 | 1531756799 675 | 将时间戳数值转换为时间格式,命令如下: 676 | 677 | shell# date -d @1531756799 "+%Y-%m-%d" 678 | 2018-07-16 679 | 下面的SQL查询语句是查询指定时间段的数据,以验证数据是否写入。 680 | 681 | mysql> select count(*) from history where clock > 1531670399 and clock <1531756799; 682 | +----------+ 683 | | count(*) | 684 | +----------+ 685 | | 1356 | 686 | +----------+ 687 | 1 row in set (0.13 sec) 688 | mysql> select count(*) from history_uint where clock > 1531670399 and clock <1531756799; 689 | +----------+ 690 | | count(*) | 691 | +----------+ 692 | | 6302 | 693 | +----------+ 694 | 1 row in set (0.05 sec) 695 | ``` 696 | 697 | # 70-72页 698 | 699 | 参考 https://github.com/zabbix-book/zabbix-mysql-backup 700 | 701 | # 73页 702 | 703 | ```shell 704 | 该脚本的使用方法如下: 705 | shell# bash /usr/sbin/zabbix_mysqldump.sh mysqldump #备份数据 706 | shell# bash /usr/sbin/zabbix_mysqldump.sh mysqlimport #恢复数据 707 | ``` 708 | 709 | ```shell 710 | (1)备份软件相关文件和配置文件,命令如下: 711 | 712 | shell# mkdir -p /data/zabbix/backup 713 | shell# cp -r /etc/zabbix /data/zabbix/backup/zabbix_conf 714 | shell# cp -r /usr/share/zabbix /data/zabbix/backup/zabbix_web 715 | shell# cp -r /usr/sbin/zabbix_server /data/zabbix/backup/zabbix_server 716 | shell# cp -r /usr/sbin/zabbix_proxy /data/zabbix/backup/zabbix_proxy 717 | shell# cp -r /usr/share/doc/zabbix-* /data/zabbix-backup/ 718 | ``` 719 | 720 | ```shell 721 | (3)升级软件,相关操作命令如下: 722 | shell# rpm -Uvh https://repo.zabbix.com/zabbix/4.0/rhel/7/x86_64/zabbix-release-4.0-1.el7.centos.noarch.rpm 723 | shell# systemctl stop zabbix-server #停止zabbix-server[注释对吗?] 724 | shell# systemctl stop zabbix-proxy #停止zabbix-proxy[注释对吗?] 725 | shell# yum upgrade zabbix-server-mysql zabbix-web-mysql zabbix-agent zabbix-get -y 726 | shell# systemctl start zabbix-server #开启zabbix-server 727 | shell# systemctl start zabbix-proxy #开启zabbix-proxy 728 | shell# ps -ef |grep zabbix #查看进程 729 | shell# tail -f /var/log/zabbix/zabbix_server.log #查看日志 730 | ``` 731 | 732 | -------------------------------------------------------------------------------- /charter-05/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-05/.DS_Store -------------------------------------------------------------------------------- /charter-05/Zabbix书籍V2-第5章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-05/Zabbix书籍V2-第5章-操作命令.pdf -------------------------------------------------------------------------------- /charter-05/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | # 124页 8 | 9 | ```sql 10 | 监控项存在于zabbix.items表中: 11 | 12 | mysql> select * from zabbix.items limit 1\G; 13 | ``` 14 | 15 | # 126页 16 | 17 | ```shell 18 | shell# zabbix_get -s 127.0.0.1 -k vm.memory.size[pavailable] 19 | 89.833440 20 | ``` 21 | 22 | 23 | 24 | # 131页 25 | 26 | ```shell 27 | 5.2.3 key的参数数组应用实例 28 | 多个参数之间用逗号(,)隔开,每个参数对key分别传递参数的值。 29 | 30 | UserParameter=wc[*],grep -c "$2" $1 31 | 上述语句表示把$2、$1的值传递给key,测试如下: 32 | 33 | shell# zabbix_get -s 127.0.0.1 -k wc[/etc/passwd,root] 34 | 注意,这里的/etc/passwd为$1,root为$2,则key最终运行的命令为grep -c root /etc/passwd。 35 | 如果方括号“[]”中有多个参数的值,那么各值之间用逗号(,)隔开。例如: 36 | 37 | icmpping[,,200,,500] 38 | 5.2.4 用户自定义参数 39 | 用户自定义参数(UserParameter)仅支持Agent的方式,对于其他方式它是不支持的。 40 | 1. key自定义的语法格式 41 | 在/etc/zabbix/zabbix_agentd.conf中配置参数,写法如下: 42 | 43 | UserParameter=key,command 44 | 除了上面这种写法,还支持参数传递的写法,具体如下: 45 | 46 | UserParameter=key[*],command $1 $2 $3 …… 47 | ``` 48 | 49 | ```shell 50 | shell# vim /etc/zabbix/zabbix_agentd.conf 51 | UnsafeUserParameters=1 52 | 前面已经介绍了key名称的 53 | ``` 54 | 55 | # 132页 56 | 57 | ```shell 58 | 4. 自定义key的例子 59 | 在 /etc/zabbix/zabbix_agentd.conf后面添加如下内容: 60 | 61 | UserParameter=get.os.type,head -1 /etc/issue 62 | 然后重启zabbix_agentd服务(注意,修改配置后必须重启服务)。 63 | 64 | shell# service zabbix_agentd restart 65 | 运行测试命令,查看key,语句如下: 66 | 67 | shell# zabbix_get -s 127.0.0.1 -k get.os.type 68 | CentOS release 6.5 (Final) 69 | ``` 70 | 71 | 72 | 73 | ```shell 74 | 5. 子配置文件的配置 75 | 为了便于维护和分类管理,UserParameter的内容可以单独写一个配置文件。 76 | 77 | shell# vim /etc/zabbix/zabbix_agentd.conf 78 | Include=/etc/zabbix/zabbix_agentd.conf.d/ 79 | ``` 80 | 81 | 82 | 83 | # 133页 84 | 85 | ```shell 86 | (1)修改Agent配置文件。 87 | shell# vim /etc/zabbix/zabbix_agentd.conf 88 | UnsafeUserParameters=1 #处理特殊字符 89 | Include=/etc/zabbix/zabbix_agentd.conf.d/ #子配置文件路径 90 | (2)修改子配置文件。 91 | 92 | shell# vim /etc/zabbix/zabbix_agentd.conf.d/get_os_type.conf 93 | UserParameter=get.os.type,head -1 /etc/issue 94 | #自定义key,如有参数传递,请参考前面的内容 95 | (3)重启服务测试key。 96 | 97 | shell# service zabbix-agent restart #重启服务 98 | shell# zabbix_get -s 127.0.0.1 -k get.os.type #测试key获取参数 99 | CentOS release 6.4 (Final) #key获取的值 100 | (4)用zabbix_agentd查看key是否被支持。 101 | 102 | shell# zabbix_agentd -p|grep get\.os 103 | get.os.type [t|CentOS release 6.5 (Final)] 104 | 如果能看到key名称,且能看到获取到的数据,则说明自定义的key是正确的。 105 | (5)在Web页面添加Item,注意数据类型的选择。 106 | ``` 107 | 108 | 109 | 110 | #135页 111 | 112 | ```shell 113 | 用zabbix_get测试数据获取情况(关于zabbix_get的用法请参考3.7节): 114 | 115 | [root@www ~]# zabbix_get -s 127.0.0.1 -k net.if.in[eth0,bytes] 116 | 358589160 117 | ``` 118 | 119 | 120 | 121 | #136-138页 122 | 123 | ```python 124 | 如果想获取网卡接收的数据包数量,用net.if.in[eth0,packets]即可。 125 | 126 | [root@www ~]# zabbix_get -s 127.0.0.1 -k net.if.in[eth0,packets] 127 | 257021 128 | 这里的packets其实就是在ifconfig命令中看到的packets。 129 | 130 | [root@www ~]# ifconfig 131 | eth0 Link encap:Ethernet HWaddr 00:0C:29:12:F6:05 132 | inetaddr:192.168.1.9 Bcast:192.168.1.255 Mask:255.255.255.0 133 | inet6 addr: fe80::20c:29ff:fe12:f605/64 Scope:Link 134 | UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 135 | RX packets:257021 errors:0 dropped:0 overruns:0 frame:0 136 | TX packets:165997 errors:0 dropped:0 overruns:0 carrier:0 137 | collisions:0 txqueuelen:1000 138 | RX bytes:357444550 (340.8 MiB) TX bytes:11420540 (10.8 MiB) 139 | 另外,关于网卡流量监控的key如下(具体用法见官方文档解释): 140 | 141 | net.if.out[if,] 142 | net.if.collisions[if] 143 | net.if.discovery 144 | net.if.out[if,] 145 | net.if.total[if,] 146 | 2.与网络连接相关的key 147 | 148 | net.tcp.listen[port] 149 | net.tcp.port[,port] 150 | net.tcp.service[service,,] 151 | net.tcp.service.perf[service,,] 152 | net.udp.listen[port] 153 | net.udp.service[service,,] 154 | net.udp.service.perf[service,,] 155 | net.dns[,name,,,,] 156 | net.dns.record[,name,,,,] 157 | 3.监控进程的key 158 | 159 | kernel.maxfiles 160 | kernel.maxproc 161 | proc.mem[,,,] 162 | proc.num[,,,] 163 | proc.cpu.util[,,,,,] 164 | 4.监控CPU和内存的key 165 | 166 | system.cpu.intr 167 | system.cpu.load[,] 168 | system.cpu.num[] 169 | system.cpu.switches 170 | system.cpu.util[,,] 171 | system.cpu.discovery 172 | vm.memory.size[] 173 | system.swap.in[,] 174 | system.swap.out[,] 175 | system.swap.size[,] 176 | sensor[device,sensor,] 177 | 5.磁盘I/O监控的key 178 | 179 | vfs.dev.read[,,] 180 | vfs.dev.write[,,] 181 | vfs.fs.inode[fs,] 182 | 6.文件监控的key 183 | 184 | vfs.file.cksum[file] 185 | vfs.file.contents[file,] 186 | vfs.file.exists[file] 187 | vfs.file.md5sum[file] 188 | vfs.file.regexp[file,regexp,,,,] 189 | vfs.file.regmatch[file,regexp,,,] 190 | vfs.file.size[file] 191 | vfs.file.time[file,] 192 | Vfs.fs.discovery 193 | vfs.fs.size[fs,] 194 | vfs.dir.count[dir,,,,,,,,,] 195 | 7.与操作系统相关的key 196 | 197 | system.boottime 198 | system.hw.chassis[] 199 | system.hw.cpu[,] 200 | system.hw.devices[] 201 | system.hw.macaddr[,] 202 | system.localtime[] 203 | system.run[command,] 204 | system.stat[resource,] 205 | system.sw.arch 206 | system.sw.os[] 207 | system.sw.packages[,,] 208 | system.uname 209 | system.uptime 210 | system.users.num 211 | 8. 与Web性能相关的key 212 | 213 | web.page.get[host,,] 214 | web.page.perf[host,,] 215 | web.page.regexp[host,,,,,] 216 | 9. 监控硬件信息的key 217 | 218 | sensor[device,sensor,] 219 | 10. 日志监控的key 220 | 需要主动模式的支持。 221 | 222 | log[file,,,,,] 223 | logrt[file_pattern,,,,,] 224 | 关于更多的Zabbix-Agent Key,请读者参考官方文档,地址如下: 225 | https://www.zabbix.com/documentation/4.0/manual/config/items/itemtypes/zabbix_agent 226 | 11.Windows监控的key 227 | 228 | eventlog[name,,,,,,] 229 | net.if.list 230 | perf_counter[counter,] 231 | proc_info[,,] 232 | service.discovery 233 | service.info[service,] 234 | service_state[*] 235 | services[,,] 236 | wmi.get[,] 237 | 关于key的详细用法,读者可以参考如下地址: 238 | https://www.zabbix.com/documentation/4.0/manual/config/items/itemtypes/zabbix_agent/win_keys 239 | ``` 240 | 241 | 242 | 243 | # 139页 244 | 245 | ```shell 246 | C:\> typeperf -qx > performance_counters.txt #查看结果如图5-8所示 247 | 在Windows中安装好Zabbix-Agent后,配置zabbix_agentd.conf,即可采集数据。 248 | 249 | C:\> "C:\Program Files\zabbix_agents_4.0.0.win\in\win64\zabbix_agentd.exe" -c "c:\Program Files\zabbix_agents_4.0.0.win\conf\zabbix_agentd.win.conf" -t perf_counter["\Processor(_Total)\% Idle Time"] 250 | perf_counter[\Processor(_Total)\% Idle Time] [d|92.035326] 251 | ``` 252 | 253 | # 141-143页 254 | 255 | ```shell 256 | 1.Simple check支持的key 257 | 258 | icmpping[,,,,] 259 | icmppingloss[,,,,] 260 | icmppingsec[,,,,,] 261 | net.tcp.service[service,,] 262 | net.tcp.service.perf[service,,] 263 | net.udp.service[service,,] 264 | net.udp.service.perf[service,,] 265 | 下面我们来分别介绍上面的key。 266 | icmpping[,,,,] 267 | 含义:这个key是用来ping目标IP地址是否存活的。 268 | 检测结果:0表示不存活,1表示存活。 269 | 数据类型:整数。 270 | target:可以不用填写,可以为IP地址,也可以为DNS。 271 | packets:表示ping多少个数据包。 272 | interval:表示间隔多久ping一次,单位为毫秒。 273 | size:表示包的大小,单位是字节。 274 | timeout:表示超时时间,单位为毫秒。 275 | 举例:icmpping[,3,10]表示ping 3个包,间隔10毫秒,检测目标IP地址是否存活。 276 | icmppingloss[,,,,] 277 | 含义:这个key是用来ping目标IP地址的丢包率的。参数同icmpping。 278 | 数据类型:浮点数。 279 | 举例:icmppingloss[,3]表示ping 3个包,间隔10毫秒,检测目标IP地址的丢包率。 280 | icmppingsec[,,,,,] 281 | 含义:这个key是用来ping目标IP地址的平均响应时间的。 282 | 数据类型:浮点数。 283 | mode:表示对ping的响应时间的计算,支持avg、max、min。其他参数同icmpping。 284 | 举例:icmppingloss[,3,,,,avg]表示ping 3个包,检测目标IP地址的平均响应时间。 285 | net.tcp.service[service,,] 286 | 含义:检测目标TCP服务的存活。 287 | 数据类型:整数。 288 | 检测结果:0表示不存活,1表示存活。 289 | service:可以为ssh、ldap、smtp、ftp、http、pop、nntp、imap、tcp、https、telnet。 290 | ip:表示连接service的IP地址,默认为Item的接口。 291 | port:表示去连接service的IP地址,默认为service的标准端口。 292 | 举例:net.tcp.service[ftp]表示检测FTP是否存活。 293 | net.tcp.service.perf[service,,] 294 | 含义:检测目标TCP服务的连接响应时间。参数同net.tcp.service。 295 | 数据类型:浮点数。 296 | 检测结果:0.000000表示服务不存活。 297 | 举例:net.tcp.service.perf[ftp]表示检测FTP的连接响应时间。 298 | net.udp.service[service,,] 299 | 含义:检测目标UDP服务的存活。 300 | 数据类型:整数。 301 | 检测结果:0表示不存活,1表示存活。 302 | service:可以为ntp。 303 | ip:表示连接service的IP地址,默认为Item的接口。 304 | port:表示连接service的IP地址,默认为service的标准端口。 305 | 举例:net.udp.service[ntp]表示检测NTP是否存活。 306 | net.udp.service.perf[service,,] 307 | 含义:检测目标UDP服务的连接响应时间。参数同net.udp.service。 308 | 数据类型:浮点数。 309 | 检测结果:0.000000表示服务不存活。 310 | 举例:net.udp.service.perf[ntp]表示检测NTP的连接响应时间。 311 | 关于这些key的详细说明,请参考官方文档,地址为: 312 | https://www.zabbix.com/documentation/4.0/manual/config/items/itemtypes/simple _checks 313 | 2.超时处理 314 | 超过zabbix_server.conf中设置的超时时间(最大超时时间为30秒)后,Zabbix会放弃处理。 315 | 3.ICMP ping 316 | Zabbix 用fping处理ICMP ping请求,所以需要安装fping程序。在zabbix_server.conf中,FpingLocation参数是用于配置fping程序路径的。 317 | 由于fping默认是以root权限工作的,而Zabbix-Server是Zabbix用户运行的,所以需要对fping程序设置setuid(如果在自定义key时需要用到netstat命令,也同样要设置setuid;否则不能获取到数据,而在日志中提示权限拒绝)。 318 | 319 | shell# chown root:zabbix /usr/sbin/fping 320 | shell# chmod 4710 /usr/sbin/fping 321 | ``` 322 | 323 | 324 | 325 | # 145页 326 | 327 | ```python 328 | log[/path/to/file/file_name,,,,,,,] 329 | logrt[/path/to/file/regexp_describing_filename_pattern,,,,,,,] 330 | log.count[/path/to/file/file_name,,,,, ,] 331 | logrt.count[/path/to/file/regexp_describing_filename_pattern,,,,,,] 332 | ``` 333 | 334 | 335 | 336 | # 146页 337 | 338 | ```python 339 | 例如,我们定义了以下的key: 340 | 341 | log[/path/to/the/file,"large result buffer allocation.*Entries: ([0-9]+)",,,,\1] 342 | 当日志中出现以下记录时,则匹配,其中([0-9]+)会匹配到Entries后面的数值,将由“\1”输出,该key输出的数据类型为整数。该key匹配输出的是数值,而非整条日志记录。 343 | 344 | Fr Feb 07 2014 11:07:36.6690 */ Thread Id 1400 (GLEWF) large result buffer allocation - /Length: 437136/Entries: 5948/Client Ver: >=10/RPC ID: 41726453/User: AUser/Form: CFG:ServiceLevelAgreement 345 | ``` 346 | 347 | 348 | 349 | # 147页 350 | 351 | ```shell 352 | [root@zabbix ~]# tail -f /var/log/zabbix/zabbix_agentd.log|grep log 353 | "key":"log[\/var\/log\/secure,session,,50]",22851:20140106:225042.451 In add_check() key:'log[/var/log/secure,session,,50]' refresh:30 lastlogsize:0 mtime:0 354 | 22851:20140106:225042.451 In process_log() filename:'/var/log/secure' lastlogsize:0 355 | 22851:20140106:225042.452 cannot open '/var/log/secure': [13] Permission denied 356 | 22851:20140106:225042.452 active check "log[/var/log/secure,session,,50]" is not supported 357 | 22851:20140106:225042.452 In process_value() key:'Zabbix server:log [/var/log/secure,session,,50]' value:'(null)' 358 | "key":"log[\/var\/log\/secure,session,,50]", 359 | ``` 360 | 361 | 362 | 363 | # 148页 364 | 365 | ```shell 366 | [root@localhost ~]# ls -l /var/log/secure 367 | -rw------- 1 root root 3788 Jul 27 15:04 /var/log/secure 368 | 在这里,为了演示如何解决这个问题而改变文件的权限,使用如下命令: 369 | shell# chown zabbix.root /var/log/secure 370 | 对于不方便设置权限的日志文件,可以使Zabbix-Agent采用root权限运行: 371 | shell# vim /etc/zabbix/zabbix_agentd.conf 372 | ### Option: AllowRoot 373 | # Allow the agent to run as 'root'. If disabled and the agent is started by 'root', the agent 374 | # will try to switch to the user specified by the User configuration option instead. 375 | # Has no effect if started under a regular user. 376 | # 0 - do not allow 377 | # 1 - allow 378 | # 379 | # Mandatory: no 380 | # Default: 381 | # AllowRoot=0 382 | AllowRoot=1 383 | 384 | shell# systemctl restart zabbix-agent 385 | ``` 386 | 387 | # 151页 388 | 389 | ```sql 390 | mysql> select * from history_log; 391 | ``` 392 | 393 | 394 | 395 | ```shell 396 | shell# zabbix_get -s 127.0.0.1 -k log[/var/log/secure,session] 397 | ZBX_NOTSUPPORTED 398 | ``` 399 | 400 | # 153页 401 | 402 | ```shell 403 | 2.计算表达式的例子 404 | (1) 计算剩余磁盘的百分比。 405 | 406 | 100*last("vfs.fs.size[/,free]",0)/last("vfs.fs.size[/,total]",0) 407 | (2)计算10分钟内Zabbix values的可用大小。 408 | 409 | avg("Zabbix server:zabbix[wcache,values]",600) 410 | (3)统计eth0的进出流量总和。 411 | 412 | last("net.if.in[eth0,bytes]",0)+last("net.if.out[eth0,bytes]",0) 413 | (4)统计进流量占网卡总流量的百分比。 414 | 415 | 100*last("net.if.in[eth0,bytes]",0)/(last("net.if.in[eth0,bytes]",0)+last("net.if.out[eth0,bytes]",0)) 416 | (5)对聚合监控方式的监控项(Aggregated[能写成中文吗?] Item)进行计算,注意引号需要转义。 417 | 418 | last("grpsum[\"video\",\"net.if.out[eth0,bytes]\",\"last\",\"0\"]",0) / last("grpsum[\"video\",\"nginx_stat.sh[active]\",\"last\",\"0\"]",0) 419 | ``` 420 | 421 | 422 | 423 | # 154页 424 | 425 | ```shell 426 | 3.示例1:计算磁盘总剩余容量 427 | 例如要计算C、D、E、F磁盘的总剩余容量,分区剩余容量的key为: 428 | 429 | vfs.fs.size[C:,free] 430 | vfs.fs.size[D:,free] 431 | vfs.fs.size[E:,free] 432 | vfs.fs.size[F:,free] 433 | 添加磁盘总剩余容量的计算表达式,如图5-26所示。 434 | 435 | last("vfs.fs.size[C:,free]",0)+last("vfs.fs.size[D:,free]",0)+last("vfs.fs.size[E:,free]",0)+last("vfs.fs.size[F:,free]",0) 436 | ``` 437 | 438 | 439 | 440 | # 155页 441 | 442 | ```shell 443 | 4.示例2:计算网卡的流量 444 | 计算表达式如下: 445 | 446 | last("net.if.in[eth0]",0)+last("net.if.in[eth1]",0)+last("net.if.in[eth2]",0) 447 | ``` 448 | 449 | 450 | 451 | # 160-161页 452 | 453 | ```shell 454 | 3. 聚合型监控方式配置实例 455 | 456 | grpsum["MySQL Servers","vfs.fs.size[/,total]",last] 457 | 含义:对MySQL Servers组监控项vfs.fs.size[/,total],最近一次监控数据求和,即求该组/分区总的容量。 458 | grpavg["MySQL Servers","system.cpu.load[,avg1]",last] 459 | 含义:对MySQL Servers组监控项system.cpu.load[,avg1],最近一次监控数据求平均值,可以得出该组的load平均值。 460 | grpavg["MySQL Servers",mysql.qps,avg,5m] 461 | 含义:对MySQL Servers组监控项mysql.qps,最近5分钟内每个主机所获取到的监控数据的平均值(avg),再次求平均值(grpavg),得出该组mysql.qps 5分钟内的平均值。 462 | grpavg[["Servers A","Servers B","Servers C"],system.cpu.load,last] 463 | 含义:对Servers A、Servers B、Servers C三个主机组监控项system.cpu.load,每个主机的最近一次监控数据求平均值。 464 | grpsum[["WEB-1"," WEB-2","WEB-3"],nginx.404.log ,sum,10m] 465 | 含义:对WEB-1、WEB-2、WEB-3三个主机组监控项nginx.404.log,每个主机近10分钟出现404的次数和,再次求和(grpsum),即求三3个分组404一共出现的次数。 466 | grpsum["Linux",log[/var/log/message,error],count,30m] 467 | 含义:对Linux主机组监控项log[/var/log/message,error],每个主机近30分钟出现的错误日志次数[指什么次数?](即日志的条数),再次求和(grpsum),即求该组一共出现的匹配错误日志的个数。 468 | ``` 469 | 470 | 471 | 472 | # 164页 473 | 474 | ```shell 475 | 2. SSH监控配置 476 | 在默认情况下,Zabbix-Server并不知道我们使用哪个SSH密钥来连接服务器,因此需要指定SSH密钥的位置。由于使用RPM包安装的Zabbix-Server,其用户家目录在/var/lib/zabbix目录下面,因此我们将SSH密钥目录设置为/var/lib/zabbix/.ssh。 477 | 478 | shell# vim /etc/zabbix/zabbix_server.conf 479 | ### Option: SSHKeyLocation 480 | # Location of public and private keys for SSH checks and actions. 481 | # 482 | # Mandatory: no 483 | # Default: 484 | # SSHKeyLocation= 485 | SSHKeyLocation=/var/lib/zabbix/.ssh 486 | 487 | shell# systemctl restart zabbix-server 488 | 3. 生成SSH密钥 489 | 使用如下命令生成SSH密钥: 490 | 491 | shell# mkdir -p /var/lib/zabbix/.ssh 492 | shell# chown zabbix:zabbix -R /var/lib/zabbix/.ssh 493 | shell# sudo -u zabbix ssh-keygen -t rsa -b 2048 494 | Generating public/private rsa key pair. 495 | Enter file in which to save the key (/var/lib/zabbix/.ssh/id_rsa): 496 | Enter passphrase (empty for no passphrase): #直接按回车键 497 | Enter same passphrase again: #可以不用输入任何参数直接按回车键 498 | Your identification has been saved in /var/lib/zabbix/.ssh/id_rsa 499 | Your public key has been saved in /var/lib/zabbix/.ssh/id_rsa.pub. 500 | The key fingerprint is: 501 | SHA256:AvvQqLfE2RsqQtMQKAY7Z9wxP+e/OxglqLY6S9Cde2w zabbix@localhost.localdomain 502 | The key's randomart image is: 503 | +---[RSA 2048]----+ 504 | |+ o | 505 | |o= . + | 506 | |= = o o.. | 507 | | * . *.+. . | 508 | |. + *.o So | 509 | | + +oB ... | 510 | |. +.*.E o. | 511 | |..oo.= o. .. | 512 | | .o=o . oo | 513 | +----[SHA256]-----+ 514 | 515 | shell# ls /var/lib/zabbix/.ssh -l 516 | -rw------- 1 zabbix zabbix 1679 Jul 27 17:09 id_rsa 517 | -rw-r--r-- 1 zabbix zabbix 410 Jul 27 17:09 id_rsa.pub 518 | 4. 分发SSH密钥 519 | 现在我们将SSH密钥分发到目标机器10.0.2.43。假如有更多的目标机器,我们需要批量复制到目标机器。 520 | 521 | [root@localhost ~]# sudo -u zabbix ssh-copy-id root@10.0.2.43 522 | /bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/var/lib/zabbix/ .ssh/id_rsa.pub" 523 | The authenticity of host '10.0.2.43 (10.0.2.43)' can't be established. 524 | RSA key fingerprint is SHA256:r+AAt7xmf8NvZ1pEHXD97K7BiMUhHAZv0FmxmPAnf1A. 525 | RSA key fingerprint is MD5:8f:ef:ae:ec:61:40:c2:30:cb:cf:47:7c:1b:3a:f8:17. 526 | Are you sure you want to continue connecting (yes/no)? yes 527 | /bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed 528 | /bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys 529 | root@10.0.2.43's password: #输入10.0.2.43这台机器的root密码 530 | Number of key(s) added: 1 531 | Now try logging into the machine, with: "ssh 'root@10.0.2.43'" 532 | and check to make sure that only the key(s) you wanted were added. 533 | 测试目标机器能否免密码访问,使用如下命令: 534 | 535 | [root@localhost ~]# sudo -u zabbix ssh root@10.0.2.43 'ifconfig' 536 | eth0 Link encap:Ethernet HWaddr 07:80:56:B7:91:8A 537 | inet addr:10.0.2.43 Bcast:10.0.2.255 Mask:255.255.255.0 538 | ``` 539 | 540 | 541 | 542 | # 168页 543 | 544 | ```shell 545 | shell# yum install telnet-server 546 | shell# vim /etc/xinetd.d/telnet 547 | service telnet 548 | { 549 | flags = REUSE 550 | socket_type = stream 551 | wait = no 552 | user = root 553 | server = /usr/sbin/in.telnetd 554 | log_on_failure += USERID 555 | disable = no 556 | } 557 | shell# /etc/init.d/xinetd start 558 | Starting xinetd: [ OK ] 559 | shell# telnet 127.0.0.1 #输入用户名和密码,进行测试 560 | # 如果希望用root登录,则需要配置 561 | shell# vim /etc/securetty 562 | tty8 563 | tty9 564 | tty10 565 | tty11 566 | pts/0 567 | shell# useradd admin 568 | shell# passwd admin #输入密码mypwd@2018 569 | ``` 570 | 571 | 572 | 573 | # 169-170页 574 | 575 | ```shell 576 | shell# vim /etc/zabbix/zabbix_server.conf 577 | ### Option: ExternalScripts 578 | # Full path to location of external scripts. 579 | # Default depends on compilation options. 580 | # To see the default path run command "zabbix_server --help". 581 | # 582 | # Mandatory: no 583 | # Default: 584 | # ExternalScripts=${datadir}/zabbix/externalscripts 585 | 586 | ExternalScripts=/etc/zabbix/externalscripts 587 | 588 | shell# systemctl restart zabbix-server 589 | shell# vim /etc/zabbix/externalscripts/echo.sh 590 | #!/bin/bash 591 | echo "$1" "$2" 592 | shell# chmod 755 /etc/zabbix/externalscripts/echo.sh 593 | shell# chown zabbix:zabbix /etc/zabbix/externalscripts/echo.sh 594 | ``` 595 | 596 | # 172页 597 | 598 | ```shell 599 | shell# vim /etc/zabbix/zabbix_server.conf 600 | ### Option: StartPreprocessors 601 | # Number of pre-forked instances of preprocessing workers. 602 | # The preprocessing manager process is automatically started when preprocessor worker is started. 603 | # 604 | # Mandatory: no 605 | # Range: 1-1000 606 | # Default: 607 | # StartPreprocessors=3 608 | ``` 609 | 610 | 611 | 612 | # 177页 613 | 614 | https://www.zabbix.com/documentation/4.0/manual/appendix/macros/supported_by_location#additional_support_for_user_macros 615 | 616 | -------------------------------------------------------------------------------- /charter-06/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-06/.DS_Store -------------------------------------------------------------------------------- /charter-06/Zabbix书籍V2-第6章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-06/Zabbix书籍V2-第6章-操作命令.pdf -------------------------------------------------------------------------------- /charter-06/img/image-20190912103506648.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-06/img/image-20190912103506648.png -------------------------------------------------------------------------------- /charter-06/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | # 187页 8 | 9 | ![image-20190912103506648](img/image-20190912103506648.png) 10 | 11 | 12 | 13 | # 194-196页 14 | 15 | ```powershell 16 | 4.Trigger表达式示例 17 | 示例1:对主机www.zabbix.com的CPU负载值进行判断。 18 | 19 | {www.zabbix.com:system.cpu.load[all,avg1].last(0)}>5 20 | {www.zabbix.com:system.cpu.load[all,avg1]给出了监控参数的名称。指定服务器是www.zabbix.com,Item是system.cpu.load[all,avg1],使用函数last()取最近一次获取到的值,>5表示来自www.zabbix.com主机的最后负载值大于5时触发器进入PROBLEM状态。 21 | 示例2:对主机www.zabbix.com的CPU负载值进行多重条件判断[叙述对吗?]。 22 | 23 | {www.zabbix.com:system.cpu.load[all,avg1].last()}>5 or{www.zabbix.com:system.cpu.load[all,avg1].min(10m)}>2 24 | 当负载值大于5或者最近10分钟内的负载值大于2时,就会触发Trigger进入PROBLEM状态。 25 | 示例3:对文件/etc/passwd是否有变化进行监控。 26 | 使用函数diff: 27 | 28 | {www.zabbix.com:vfs.file.cksum[/etc/passwd].diff()}=1 29 | 当文件/etc/passwd之前的checksum值与最近的值不同时,则会触发Trigger进入PROBLEM状态。 30 | 示例4:对网卡流量是否超过一定阈值进行条件判断。 31 | 使用函数min: 32 | 33 | {www.zabbix.com:net.if.in[eth0,bytes].min(5m)}>100K 34 | 当最近5分钟内eth0接收到的字节数大于100KB时,则会触发Trigger进入PROBLEM状态。 35 | 示例5:两台SMTP服务器的集群节点都停止了。 36 | 注意,在一个表达式中使用两个不同的主机,语句如下: 37 | 38 | {smtp1.zabbix.com:net.tcp.service[smtp].last()}=0 and {smtp2.zabbix.com: net.tcp.service[smtp].last()}=0 39 | 当SMTP服务器smtp1.zabbix.com与smtp2.zabbix.com都停止时,表达式为真,则会触发Trigger进入PROBLEM状态。 40 | 这个示例讲的也就是告警关联,对于避免误报具有很好的效果。 41 | 示例6:对Zabbix客户端代理版本是否满足特定版本进行判断。 42 | 使用函数str(): 43 | 44 | {zabbix.zabbix.com:agent.version.str("beta8")}=1 45 | 当Zabbix客户端代理有版本beta8时,该表达式为真。 46 | 示例7:服务器的imcp ping不可达进度判断。 47 | 48 | {zabbix.com:icmpping.count(30m,0)}>5 49 | 主机zabbix.zabbix.com在最近30分钟内超过5次不可达,该表达式为真。 50 | 示例8:服务器最近3分钟内没有响应。 51 | 使用函数nodata(): 52 | 53 | {zabbix.com:tick.nodata(3m)}=1 54 | tick必须使用“Zabbix trapper”类型。为了使这个触发器能工作,tick必须定义。该主机应该使用Zabbix-Sender定期为该参数发送数据。如果180s都没有接收到数据,该触发器的状态就变为PROBLEM。 55 | 示例9:对CPU在特定时间的负载判断。 56 | 使用函数time(): 57 | 58 | {zabbix:system.cpu.load[all,avg1].min(5m)}>2 and {zabbix:system.cpu.load [all,avg1].time(0)}>000000 and {zabbix:system.cpu.load[all,avg1].time()}<060000 59 | 触发器只在晚上(00:00—06:00)可用,当5分钟内的负载值大于2时,该触发器的状态就变为PROBLEM。 60 | 示例10:检查客户端本地时间是否与Zabbix-Server服务器时间同步。 61 | 使用函数fuzzytime(): 62 | 63 | {MySQL_DB:system.localtime.fuzzytime(10)}=0 64 | 当MySQL_DB的本地时间与Zabbix-Server的时间相差超过10s时,触发器变为PROBLEM状态。 65 | 示例11:CPU的负载在最近1小时的平均值,与一天前的值进行同比大于2倍。[请顺一下这句话] 66 | 67 | {server:system.cpu.load.avg(1h)}/{server:system.cpu.load.avg(1h,1d)}>2 68 | 示例12:存储容量小于总容量的10%。 69 | 70 | {Template PfSense:hrStorageFree[{#SNMPVALUE}].last()}<{Template PfSense: hrStorageSize[{#SNMPVALUE}].last()}*0.1 #乘号的优先级比小于号大 71 | 示例13:进程数是总进程数的80%。 72 | 73 | ({Template_Oracle:oracle[procnum].last(0)}*100/{Template_Oracle:oracle[maxprocs].last(0)})>80 74 | 示例14:判断告警故障表达式,满足阈值的个数大于或等于2。即满足告警条件{Zabbix server:system.cpu.load [percpu,avg1].last()}>5后,数值1,一共有3个逻辑表达式,故大于或等于2为满足条件,[不通顺]如图6-8所示。 75 | 76 | ({Zabbix server:system.cpu.load[percpu,avg1].last()}>5) + ({Zabbix server: system.cpu.load[percpu,avg1].last()}>5) + ({Zabbix server:system.cpu.load [percpu,avg1].last()}>5)>=2 77 | ``` 78 | 79 | 80 | 81 | # 197页 82 | 83 | 表6-4 Trigger表达式 84 | 85 | | 表 达 式 | 解  释 | 86 | | ------------------------------------------------------------ | ---------------------------------------------------------- | 87 | | {Template OS Linux:agent.hostname.diff(0)}>0 | 主机名发生了改变 | 88 | | {Template OS Linux:kernel.maxproc.last(0)}<512 | 最后接收到的数据小于512个 | 89 | | {Template OS Linux:proc.num[,,run].avg(5m)}>30 | 5分钟的平均数值大于30 | 90 | | {Template OS Linux:socket.tcp_established.last(0)}>25000 and {Template OS Linux:socket.tcp_established.last(#1,5m)}>25000 | 值大于25000 个并且 5分钟第一次的值大于25000个 | 91 | | {Template OS Linux:system.localtime.fuzzytime(5m)}=0 | 时间相差5分钟 | 92 | | {Template OS Linux:agent.ping.nodata(10m)}=1 and {Template OS Linux:agent.ping.last(#20,10m)}=1 and {Template OS Linux:agent.ping.last(#16,10m)}=1 and {Template OS Linux:agent.ping.last(#12,10m)}=1 | 10分钟内没接收到数据,并发10分钟的第12、16、20次都没有数据 | 93 | | {Template Cisco envmon:sysUpTime.change(0)}<0 | 启动时间最近一次的值-上一次的值之差小于0 | 94 | | {Template SNMP OS ESXi:vmwVMGuestState.[{#SNMPINDEX}]. regexp("not running")}=1 | 匹配字符串“not running” | 95 | | {Template SNMP OS ESXi:hrStorageUsedBlocks[{#SNMPINDEX}]. last(0)} /{Template SNMP OS ESXi:hrStorageSizeBlocks[{#SNMPINDEX}]. last(0)} > 0.9 | 两个值相除大于0.9 | 96 | 97 | 98 | 99 | # 205-208页 100 | 101 | ```powershell 102 | 示例1:在默认的标题{TRIGGER.NAME}中表示Trigger的名称。 103 | 104 | {TRIGGER.NAME}: {TRIGGER.STATUS} 105 | 当接收到消息后,内容将被解析为: 106 | 107 | Processor load is too high on server zabbix.zabbix.com: PROBLEM 108 | 示例2:除使用宏外,我们还可以使用函数表达式来获取具体的数值[不通顺]。例如: 109 | 110 | Processor load is: {zabbix.zabbix.com:system.cpu.load[,avg1].last()} 111 | 当接收到消息后,内容将被解析为: 112 | 113 | Processor load is: 1.45 114 | 示例3:有如下告警消息内容。 115 | 116 | Latest value: {{HOST.HOST}:{ITEM.KEY}.last()} 117 | MAX for 15 minutes: {{HOST.HOST}:{ITEM.KEY}.max(900)} 118 | MIN for 15 minutes: {{HOST.HOST}:{ITEM.KEY}.min(900)} 119 | 当接收到消息后,内容将被解析为: 120 | 121 | Latest value: 1.45 122 | MAX for 15 minutes: 2.33 123 | MIN for 15 minutes: 1.01 124 | 示例4:支持在消息内容中显示触发器的正则表达式。 125 | 126 | Trigger: {TRIGGER.NAME} 127 | Trigger expression: {TRIGGER.EXPRESSION} 128 | 129 | 1. Item value on {HOST.NAME1}: {ITEM.VALUE1} ({ITEM.NAME1}) 130 | 2. Item value on {HOST.NAME2}: {ITEM.VALUE2} ({ITEM.NAME2}) 131 | 当接收到消息后,内容将被解析为: 132 | 133 | Trigger: Processor load is too high on a local host 134 | Trigger expression: {Myhost:system.cpu.load[percpu,avg1].last(0)}>5 | {Myotherhost:system.cpu.load[percpu,avg1].last(0)}>5 135 | 136 | 1. Item value on Myhost: 0.83 (Processor load (1 min average per core)) 137 | 2. Item value on Myotherhost: 5.125 (Processor load (1 min average per core)) 138 | 示例5:告警故障消息。 139 | 140 | Problem: 141 | Event ID: {EVENT.ID} 142 | Event value: {EVENT.VALUE} 143 | Event status: {EVENT.STATUS} 144 | Event time: {EVENT.TIME} 145 | Event date: {EVENT.DATE} 146 | Event age: {EVENT.AGE} 147 | Event acknowledgement: {EVENT.ACK.STATUS} 148 | Event acknowledgement history: {EVENT.ACK.HISTORY} 149 | 当接收到消息后,内容将被解析为: 150 | 151 | Problem: 152 | Event ID: 21874 153 | Event value: 1 154 | Event status: PROBLEM 155 | Event time: 13:04:30 156 | Event date: 2014.01.02 157 | Event age: 5m 158 | Event acknowledgement: Yes 159 | Event acknowledgement history: 2014.01.02 11:11:01 "Smith (Admin)" 160 | 示例6:告警恢复消息。 161 | 162 | Recovery: 163 | Event ID: {EVENT.RECOVERY.ID} 164 | Event value: {EVENT.RECOVERY.VALUE} 165 | Event status: {EVENT.RECOVERY.STATUS} 166 | Event time: {EVENT.RECOVERY.TIME} 167 | Event date: {EVENT.RECOVERY.DATE} 168 | 当接收到消息后,内容将被解析为: 169 | 170 | Recovery: 171 | Event ID: 21896 172 | Event value: 0 173 | Event status: OK 174 | Event time: 13:10:07 175 | Event date: 2014.01.02 176 | 6.3.5 在告警消息中使用宏 177 | 在告警消息中同样可以使用宏。下面我们针对Zabbix 4.0版本列出了一些宏,其中较常用的宏已用粗体字标出。 178 | 179 | {host:key.func(param)} 180 | {TRIGGER.EVENTS.ACK} 181 | {TRIGGER.EVENTS.PROBLEM.ACK} 182 | {TRIGGER.EVENTS.PROBLEM.UNACK} 183 | {TRIGGER.EVENTS.UNACK} 184 | {TRIGGER.HOSTGROUP.NAME} 185 | {TRIGGER.PROBLEM.EVENTS.PROBLEM.ACK} 186 | {TRIGGER.PROBLEM.EVENTS.PROBLEM.UNACK} 187 | {TRIGGER.EXPRESSION} 188 | {TRIGGER.EXPRESSION.RECOVERY} 189 | {TRIGGER.ID} 190 | {TRIGGER.NAME} 191 | {TRIGGER.VALUE} 192 | {TRIGGER.NAME.ORIG} 193 | {TRIGGER.NSEVERITY} 194 | {TRIGGER.SEVERITY} 195 | {TRIGGER.STATE} 196 | {TRIGGER.STATUS} 197 | {TRIGGER.TEMPLATE.NAME} 198 | {TRIGGER.URL} 199 | 200 | {EVENT.ID} 201 | {EVENT.DATE} #事件的日期 202 | {EVENT.TIME} #事件的时间 203 | {EVENT.UPDATE.HISTORY} 204 | {EVENT.ACK.STATUS} 205 | {EVENT.AGE} 206 | {EVENT.VALUE} 207 | {EVENT.TAGS} #tag 208 | {EVENT.UPDATE.ACTION} 209 | {EVENT.UPDATE.DATE} 210 | {EVENT.UPDATE.HISTORY} 211 | {EVENT.UPDATE.MESSAGE} 212 | {EVENT.UPDATE.TIME} 213 | {EVENT.RECOVERY.DATE} 214 | {EVENT.RECOVERY.TIME} 215 | {EVENT.RECOVERY.TAGS} 216 | {EVENT.RECOVERY.VALUE} 217 | {TIME} #发送告警的时间 218 | {DATE} #发送告警的日期 219 | {PROXY.NAME} 220 | {PROXY.DESCRIPTION} 221 | {ITEM.NAME.ORIG} 222 | {ITEM.LOG.TIME} 223 | {ITEM.LOG.SOURCE} 224 | {ITEM.LOG.SEVERITY} 225 | {ITEM.LOG.NSEVERITY} 226 | {ITEM.LOG.EVENTID} 227 | {ITEM.LOG.DATE} 228 | {ITEM.LOG.AGE} 229 | {ITEM.LASTVALUE} 230 | {ITEM.KEY.ORIG} 231 | {ITEM.NAME} #Item的名称 232 | {ITEM.KEY} #Item的key 233 | {ITEM.VALUE} #Item的值 234 | {ITEM.ID} 235 | {ITEM.DESCRIPTION} 236 | {INVENTORY.*} 237 | {HOST.NAME} #主机名 238 | {HOST.PORT} 239 | {ACTION.ID} 240 | {ACTION.NAME} 241 | ``` 242 | 243 | 244 | 245 | # 213页 246 | 247 | ```shell 248 | 2 通过执行远程命令重启Apache 249 | 如果Agent端的Apache无响应,那么在Agent端对Apache进行重启即可。 250 | 251 | sudo /etc/init.d/httpd restart 252 | 步骤如下: 253 | (1)在Agent端配置执行远程命令。 254 | 255 | shell# vim /etc/zabbix/zabbix_agentd.conf 256 | EnableRemoteCommands=1 257 | (2)配置sudo。 258 | 259 | shell# visudo 260 | # 允许 zabbix 用户重启Apache,不需要密码 261 | zabbix ALL=NOPASSWD: /etc/init.d/httpd restart 262 | ``` 263 | 264 | 265 | 266 | # 218页 267 | 268 | ```shell 269 | 6.5.1 自定义脚本告警的原理 270 | 自定义脚本在/etc/zabbix/zabbix_server.conf中,配置语句如下: 271 | 272 | AlertScriptsPath=/etc/zabbix/alertscripts 273 | ``` 274 | 275 | 276 | 277 | # 219页 278 | 279 | ```shell 280 | 例如,/etc/zabbix/alertscripts/scripts.sh脚本内容为: 281 | 282 | #!/bin/bash 283 | 284 | to=$1 285 | subject=$2 286 | body=$3 287 | 288 | cat <" 377 | msg = MIMEText(content) 378 | msg['Subject'] = subject 379 | msg['From'] = me 380 | msg['to'] = mail_to 381 | global sendstatus 382 | global senderr 383 | 384 | try: 385 | smtp = smtplib.SMTP() 386 | smtp.connect(mail_host) 387 | smtp.login(mail_user,mail_pass) 388 | smtp.sendmail(me,mail_to,msg.as_string()) 389 | smtp.close() 390 | print 'send ok' 391 | sendstatus = True 392 | except Exception,e: 393 | senderr=str(e) 394 | print senderr 395 | sendstatus = False 396 | 397 | def logwrite(sendstatus,mail_to,content): 398 | logpath='/var/log/zabbix/alert' 399 | 400 | if not sendstatus: 401 | content = senderr 402 | 403 | if not os.path.isdir(logpath): 404 | os.makedirs(logpath) 405 | 406 | t=datetime.datetime.now() 407 | daytime=t.strftime('%Y-%m-%d') 408 | daylogfile=logpath+'/'+str(daytime)+'.log' 409 | logging.basicConfig(filename=daylogfile,level=logging.DEBUG) 410 | logging.info('*'*130) 411 | logging.debug(str(t)+' mail send to {0},content is :\n {1}'.format (mail_to,content)) 412 | 413 | if __name__ == "__main__": 414 | parser = argparse.ArgumentParser(description='Send mail to user for zabbix alerting') 415 | parser.add_argument('mail_to',action="store", help='The address of the E-mail that send to user ') 416 | parser.add_argument('subject',action="store", help='The subject of the E-mail') 417 | parser.add_argument('content',action="store", help='The content of the E-mail') 418 | args = parser.parse_args() 419 | mail_to=args.mail_to 420 | subject=args.subject 421 | content=args.content 422 | 423 | send_mail(mail_to,subject,content) 424 | logwrite(sendstatus,mail_to,content) 425 | 注意上面这个脚本文件需要Zabbix用户具有执行权限,以确保脚本能正常运行。下面对脚本文件进行权限改变。 426 | 427 | shell# chmod 700 /etc/zabbix/alertscripts/zabbix_sendmail.py 428 | shell# chown zabbix.zabbix /etc/zabbix/alertscripts/zabbix_sendmail.py 429 | 使用脚本测试发送邮件。 430 | 431 | shell# python /etc/zabbix/alertscripts/zabbix_sendmail.py 432 | info@itnihao.com test "test to send mail" 433 | ``` 434 | 435 | 436 | 437 | # 235页 438 | 439 | ```shell 440 | 6.10 如何取消告警发送 441 | 当大量告警无法正常发送时,告警会处于队列堆积状态,因此,我们可以手动关闭告警,使其不再发送。在数据库中,alerts表记录了即将发送的告警消息,其状态为1,表示待发送;状态为0,表示已发送,因此可以使用如下语句批量取消告警发送。 442 | shell# mysql -uzabbix -pzabbix zabbix "update alerts set status='1' where status='0'" 443 | 6.11 如何删除故障信息 444 | 当Zabbix-Web界面中的故障信息,无法通过手动操作关闭故障的时候,我们还可以通过直接操作数据库进行删除。为了方便,可用笔者编写的脚本进行操作,如下所示: 445 | #!/bin/bash 446 | 447 | MYSQL_BIN=mysql #MySQL的程序 448 | MYSQL_USER=zabbix #MySQL的用户名 449 | MYSQL_PWD=zabbix #MySQL的密码 450 | MYSQL_PORT=3306 #MySQL的端口 451 | MYSQL_HOST=127.0.0.1 #MySQL的IP 452 | DB_NAME=zabbix #数据库名称 453 | MYSQL_LOGIN="${MYSQL_BIN} -u${MYSQL_USER} -p${MYSQL_PWD} -h${MYSQL_HOST} -P${MYSQL_PORT} ${DB_NAME}" 454 | triggerids="13614 13684" #此处填写需要被删除的故障的triggerid 455 | for ID in ${triggerids};do 456 | echo "------------------------------------------------------" 457 | echo "update zabbix.triggers set value=0 where triggerid=${ID} and value=1" 458 | ${MYSQL_LOGIN} -e "update zabbix.triggers set value=0 where triggerid=${ID} and value=1" 2>&1 | grep -v "Warning: Using a password" 459 | echo "delete from zabbix.events where objectid=${ID} and object=0" 460 | ${MYSQL_LOGIN} -e "delete from zabbix.events where objectid=${ID} and object=0" 2>&1 | grep -v "Warning: Using a password" 461 | #4.0版本还需要清理problem表的数据记录 462 | ${MYSQL_LOGIN} -e "delete from zabbix.problem where objectid=${ID} and object=0" 2>&1 | grep -v "Warning: Using a password" 463 |   echo "" 464 | done[新增加的内容] 465 | ``` 466 | 467 | 468 | 469 | # 237页 470 | 471 | ```shell 472 | 配置触发器的相关重要参数如下: 473 | 474 | Name:Service {{ITEM.VALUE}.regsub("^.* service ([A-Za-z]+).*$",\1)} stopped 475 | Problem expression:{Zabbix server:log[/tmp/app.log].regexp("stopped")}=1 476 | Recovery expression:{Zabbix server:log[/tmp/app.log].regexp("started")}=1 477 | Tags:Service {{ITEM.VALUE}.regsub("^.* service ([A-Za-z]+).*$",\1)} 478 | 我们创建一个日志文件app.log,[是否是文件?]并写入两条触发告警的日志。 479 | 480 | shell# touch /tmp/app.log 481 | shell# chown zabbix:zabbix /tmp/app.log 482 | shell# echo "service web stopped" >> /tmp/app.log  483 | shell# echo "service db stopped" >> /tmp/app.log  484 | ``` 485 | 486 | # 238页 487 | 488 | ```shell 489 | 继续写入两条触发告警的日志: 490 | shell# echo "service web started" >> /tmp/app.log  491 | shell# echo "service db started" >> /tmp/app.log  492 | ``` 493 | 494 | -------------------------------------------------------------------------------- /charter-08/Zabbix书籍V2-第8章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-08/Zabbix书籍V2-第8章-操作命令.pdf -------------------------------------------------------------------------------- /charter-09/Zabbix书籍V2-第9章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-09/Zabbix书籍V2-第9章-操作命令.pdf -------------------------------------------------------------------------------- /charter-09/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | # 394页 8 | 9 | ```shell 10 | shell# vim /etc/zabbix/zabbix_proxy.conf  11 | ### Option: ProxyLocalBuffer 12 | #       Proxy will keep data locally for N hours, even if the data have already been synced with the server. 13 | #       This parameter may be used if local data will be used by third party applications. 14 | # 15 | # Mandatory: no 16 | # Range: 0-720 17 | # Default: 18 | # ProxyLocalBuffer=0 19 | 20 | ### Option: ProxyOfflineBuffer 21 | #       Proxy will keep data for N hours in case if no connectivity with Zabbix Server. 22 | #       Older data will be lost. 23 | # 24 | # Mandatory: no 25 | # Range: 1-720 26 | # Default: 27 | # ProxyOfflineBuffer=1 28 | ``` 29 | 30 | # 395页 31 | 32 | ```shell 33 | shell# rpm -ivh http://repo.zabbix.com/zabbix/4.0/rhel/7/x86_64/zabbix- release-4.0-1.el7.noarch.rpm 34 | shell# yum install -y zabbix-proxy-mysql mariadb-server 35 | ``` 36 | 37 | ```shell 38 | 注意:如果安装的版本高于4.0,则请下载并安装最新版本的yum源地址,地址格式如下: 39 | http://repo.zabbix.com/zabbix/4.0/rhel/7/x86_64/ #4.0代表当前的版本 40 | 在安装zabbix-release后,将会增加如下的yum源: 41 | 42 | shell# cat /etc/yum.repos.d/zabbix.repo 43 | [zabbix] 44 | name=Zabbix Official Repository - $basearch 45 | baseurl=http://repo.zabbix.com/zabbix/4.0/rhel/7/$basearch/ 46 | enabled=1 47 | gpgcheck=1 48 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX-A14FE591 49 | 50 | [zabbix-non-supported] 51 | name=Zabbix Official Repository non-supported - $basearch  52 | baseurl=http://repo.zabbix.com/non-supported/rhel/7/$basearch/ 53 | enabled=1 54 | gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-ZABBIX 55 | gpgcheck=1 56 | ``` 57 | 58 | # 396页 59 | 60 | ```shell 61 | shell# systemctl start mariadb #启动数据库服务 62 | shell# systemctl enable mariadb #配置开机自启动 63 | shell# mysqladmin -uroot password admin #设置root密码为admin 64 | shell# mysql -uroot -padmin #用root登录MySQL 65 | mysql> create database zabbix_proxy character set utf8; #创建数据库zabbix_proxy,并将其字符集设置为UTF-8 66 | mysql> grant all privileges on zabbix_proxy.* to zabbix_proxy@localhost identified by 'zabbix_proxy'; #将数据库zabbix_proxy授权给用户zabbix_proxy,授权地址为localhost,访问密码为zabbix_proxy 67 | mysql> flush privileges; #刷新权限 68 | #由于默认安装的MySQL是空密码(5.5版本以下),5.6版本以上的数据库密码策略会有所不同,启动服务时会自动生成一个复杂的root密码。可以用mysql_secure_installation命令进行安全配置 69 | shell# mysql_secure_installation 70 | ``` 71 | 72 | ```shell 73 | shell# zcat /usr/share/doc/zabbix-proxy-mysql-4.0.0/schema.sql.gz | mysql -uzabbix_proxy -pzabbix_proxy zabbix_proxy #如果zcat命令执行失败,则可以尝试先解压缩再导入MySQL中,如果导入成功,则以下步骤忽略 74 | shell# cd /usr/share/doc/zabbix-proxy-mysql-4.0.0 75 | shell# gzip –d schema.sql.gz #解压缩后的文件名称为schame.sql 76 | shell# mysql -uzabbix_proxy -pzabbix_proxy zabbix_proxy 77 | mysql> use zabbix_proxy 78 | mysql> source /usr/share/doc/zabbix-proxy-mysql-4.0.0/schema.sql; #导入schema.sql 79 | ``` 80 | 81 | # 397页 82 | 83 | 表9-2 zabbix_proxy.conf的重要参数 84 | 85 | | 参   数 | 参 数 配 置 | 描  述 | 86 | | ------------ | ---------------------------------- | ------------------------------------------------------------ | 87 | | ProxyMode | ProxyMode=0 | 默认参数值为0,即Zabbix-Proxy工作于主动模式下 | 88 | | ProxyMode=1 | 表示Zabbix-Proxy工作于被动模式下 | | 89 | | Server | Server=X.X.X.X | 该参数工作于主动模式(ProxyMode=0)下,从X.X.X.X这个IP地址的Zabbix-Server中获取监控配置信息。在被动模式下此参数无效 | 90 | | ServerPort | ServerPort=10051 | 默认参数值为10051,工作于主动模式下,在被动模式下此参数无效 | 91 | | Hostname | Hostname=Zabbix proxy | Zabbix-Proxy的主机名字。需要注意,这个名字要具有唯一性,不能重复。在配置Proxy时,Web中的配置会用到此参数,即Administration-DM-Create proxy-Proxy name,这个是配置Zabbix-Proxy的重点 | 92 | | HostnameItem | HostnameItem=system.hostname | 该参数在Hostname没有定义时才会生效 | 93 | | ListenPort | ListenPort=10051 | Zabbix-Proxy的默认端口 | 94 | | SourceIP | SourceIP=X.X.X.X | 用于多网卡环境中,指定Zabbix-Proxy连接的外网IP地址 | 95 | | DBHost | DBHost=localhost | Zabbix-Proxy的数据库IP地址 | 96 | | DBName | DBName=zabbix_proxy | Zabbix-Proxy的数据库名称 | 97 | | DBUser | DBUser= zabbix_proxy | Zabbix-Proxy的数据库用户名 | 98 | | DBPassword | DBPassword= zabbix_proxy | Zabbix-Proxy的数据库密码 | 99 | | DBSocket | DBSocket=/var/lib/mysql/mysql.sock | Zabbix-Proxy的mysql.sock文件 | 100 | 101 | ```shell 102 | 启动Zabbix-Proxy服务的命令如下: 103 | shell# systemctl start zabbix-proxy #启动服务 104 | shell# systemctl enable zabbix-proxy #添加到开机启动项 105 | ``` 106 | 107 | 108 | 109 | # 398页 110 | 111 | ```shell 112 | 9.1.5 查看Zabbix-Proxy日志 113 | 如果需要查看启动日志,则执行以下命令: 114 | shell# tail -f /var/log/zabbix/zabbix_proxy.log 115 | ``` 116 | 117 | # 404页 118 | 119 | ```shell 120 | 9.4.2 配置过程 121 | 1.配置Zabbix-Agent 122 | 在配置注册的Zabbix-Agent时,需要关注的配置参数如下: 123 | 124 | shell# vim /etc/zabbix/zabbix_agentd.conf 125 | ServerActive=10.0.0.1 #Zabbix-Server所在的IP地址,可以同时填写多个IP 126 | Hostname=ec2-10-9-0-8 #主机名 127 | HostnameItem=system.hostname #获取主机名的key,当Hostname参数已设置值的时候,此参数失效。 128 | HostMetadata=Linux linux_host #主机元数据的标识,字符串的长度范围为0~255。可以满足于云环境主机的使用,因为在云环境中主机名通常没有规律可循,基本都是是随机生成的字符串,。 129 | HostMetadataItem=system.uname #①当HostMetadata参数已设置值的时候,此参数失效;②用于获取数据的key,此处的system.uname为获取系统内核名称的key;③对于其返回结果的字符串,字符的长度范围限制为0~255;④可以使用Zabbix-Agent原生内置的key,也可以使用用户自定义的key,还可以使用system.run[]这个key(前提是EnableRemoteCommands参数已经打开)。 130 | ``` 131 | 132 | # 407-408页 133 | 134 | ```shell 135 | vfs.fs.discovery ,支持Zabbix-Agent。 136 | 137 | { 138 | "data": [ 139 | { 140 | "{#FSNAME}": "/", 141 | "{#FSTYPE}": "ext4" 142 | }, 143 | { 144 | "{#FSNAME}": "/boot", 145 | "{#FSTYPE}": "ext4" 146 | } 147 | ] 148 | } 149 | net.if.discovery, 支持Zabbix-Agent。 150 | 151 | { 152 | "data": [ 153 | { 154 | "{#IFNAME}": "lo" 155 | }, 156 | { 157 | "{#IFNAME}": "eth0" 158 | } 159 | ] 160 | } 161 | discovery[{#MACRO1},oid1,{#MACRO2},oid2,…,] ,支持SNMP v1/v2 /v3。 162 | 163 | {"data":[ 164 | { 165 | "{#SNMPINDEX}":"", 166 | "{#SNMPVALUE}":"” 167 | }, 168 | { 169 | "{#SNMPINDEX}":"", 170 | "{#SNMPVALUE}":" 171 | }] 172 | } 173 | system.cpu.discovery: 174 | 175 | { 176 | "data": [ 177 | { 178 | "{#CPU.NUMBER}": 0, 179 | "{#CPU.STATUS}": "online" 180 | }, 181 | { 182 | "{#CPU.NUMBER}": 1, 183 | "{#CPU.STATUS}": "online" 184 | }, 185 | { 186 | "{#CPU.NUMBER}": 2, 187 | "{#CPU.STATUS}": "online" 188 | } 189 | ] 190 | } 191 | db.odbc.discovery[,] , 支持ODBC(Server)。 192 | 193 | { 194 | "data": [ 195 | { 196 | "{#CITY}": "BeiJing", 197 | "{#COUNT}": "13" 198 | }, 199 | { 200 | "{#HCITY}": "ShangHai", 201 | "{#COUNT}": "7" 202 | } 203 | ] 204 | } 205 | ``` 206 | 207 | # 409页 208 | 209 | 表9-3 内置的宏功能 210 | 211 | | 宏 | 功 能 描 述 | 212 | | ---------------------- | ------------------------------------------------------------ | 213 | | {#SERVICE.NAME} | 服务的名称 | 214 | | {#SERVICE.DISPLAYNAME} | 服务的显示名称 | 215 | | {#SERVICE.DESCRIPTION} | 服务的描述 | 216 | | {#SERVICE.STATE} | 运行状态值0 Running1 Paused2 Start pending3 Pause pending4 Continue pending | 217 | 218 | | 宏 | 功 能 描 述 | 219 | | ------------------------- | ------------------------------------------------------------ | 220 | | | 5 Stop pending6 Stopped7 Unknown | 221 | | {#SERVICE.STATENAME} | 服务状态(Running, Paused, Start pending, Pause pending, Continue pending, Stop pending, Stopped, Unknown ) | 222 | | {#SERVICE.PATH} | 服务的实际路径 | 223 | | {#SERVICE.USER} | 服务的用户 | 224 | | {#SERVICE.STARTUP} | 服务开机自启动类型0 Automatic1 Automatic delayed2 Manual3 Disabled4 Unknown | 225 | | {#SERVICE.STARTUPNAME} | 服务开机自启动类型(Automatic, Automatic delayed, Manual, Disabled, Unknown) | 226 | | {#SERVICE.STARTUPTRIGGER} | 启动时触发0 no startup triggers1 has startup triggers | 227 | 228 | # 410页 229 | 230 | ```json 231 | 测试net.if.discovery,数据如下: 232 | 233 | shell# zabbix_get -s 127.0.0.1 -k net.if.discovery 234 | { 235 | "data": [ 236 | { 237 | "{#IFNAME}": "lo" 238 | }, 239 | { 240 | "{#IFNAME}": "eth0" 241 | } 242 | ] 243 | } 244 | 测试vfs.fs.discovery,数据如下: 245 | 246 | shell# zabbix_get -s 127.0.0.1 -k vfs.fs.discovery 247 | { 248 | "data": [ 249 | { 250 | "{#FSNAME}": "/", 251 | "{#FSTYPE}": "rootfs" 252 | }, 253 | 省略部分显示 254 | { 255 | "{#FSNAME}": "/", 256 | "{#FSTYPE}": "ext4" 257 | }, 258 | 省略部分显示 259 | { 260 | "{#FSNAME}": "/net", 261 | "{#FSTYPE}": "autofs" 262 | } 263 | ] 264 | } 265 | ``` 266 | 267 | # 412页 268 | 269 | ```shell 270 | 9.5.5 配置Zabbix客户端 271 | 配置Zabbix客户端,命令如下: 272 | 273 | shell# egrep -v "(#|^$)" /etc/zabbix/zabbix_agentd.conf 274 | LogFile=/var/log/zabbix/zabbix_agentd.log 275 | EnableRemoteCommands=0 #是否支持远程命令,0表示不支持 276 | Server=127.0.0.1,192.168.0.240 #Zabbix-Server端的IP地址 277 | StartAgents=8 #Agent开启的进程个数 278 | ServerActive=192.168.0.240:10051 #Zabbix-Server端的IP地址 279 | Timeout=30 #超时时间 280 | Include=/etc/zabbix/zabbix_agentd.conf.d/ #子配置文件路径 281 | UnsafeUserParameters=1 #在自定义key中可以包含特殊字符 282 | ``` 283 | 284 | 285 | 286 | ```shell 287 | shell# cat /etc/zabbix/scripts/web_site_code_status 288 | #!/bin/bash  289 |   290 | # function:monitor web  status from zabbix  291 | # License: GPL  292 | # mail:itnihao@qq.com  293 | # version:1.0 date:2012-12-09  294 | source /etc/bashrc >/dev/null 2>&1  295 | source /etc/profile  >/dev/null 2>&1  296 |   297 | #/usr/bin/curl -o /dev/null -s -w %{http_code} http://$1/  298 | Web_SITE_discovery () {  299 | Web_SITE=($(cat /etc/zabbix/scripts/Web.txt|grep -v "^#"))  300 |    printf '{\n'  301 |    printf '\t"data":[\n'  302 | for((i=0;i<${#Web_SITE[@]};++i))  303 | {  304 |     num=$(echo $((${#Web_SITE[@]}-1)))  305 |       if [ "$i" != ${num} ]; then  306 |         printf "\t\t{ \n"  307 |         printf "\t\t\t\"{#SITENAME}\":\"${Web_SITE[$i]}\"},\n"  308 |       else  309 |       printf  "\t\t{ \n"  310 |          printf  "\t\t\t\"{#SITENAME}\":\"${Web_SITE[$num]}\"}]}\n"  311 |       fi  312 | }  313 | }  314 | web_site_code () {  315 | /usr/bin/curl -o /dev/null -s -w %{http_code} http://$1  316 | }  317 | case "$1" in  318 | web_site_discovery)  319 | Web_SITE_discovery  320 | ;;  321 | web_site_code)  322 | web_site_code $2   323 | ;;  324 | *)  325 | echo "Usage:$0 {web_site_discovery|web_site_code [URL]}"  326 | ;;  327 | esac  328 | ``` 329 | 330 | # 413页 331 | 332 | ```json 333 | shell# sh web_site_code_status web_site_discovery 334 | { 335 | "data":[ 336 | { 337 | "{#SITENAME}":"www.itnihao.com"}, 338 | { 339 | "{#SITENAME}":"www.baidu.com"}, 340 | { 341 | "{#SITENAME}":"www.weibo.com"}]} 342 | ``` 343 | 344 | # 414页 345 | 346 | ```python 347 | 此处如果采用Python来编写,则代码如下: 348 | 349 | #!/bin/env python 350 | # -*- coding: utf-8 -*- 351 | 352 | # Last modified: 2017-08-12 14:47 353 | # Author: itnihao 354 | # Mail: itnihao@qq.com 355 | 356 | import urllib2 357 | import json 358 | import sys 359 | from optparse import OptionParser 360 | import socket 361 | 362 | def discovery(): 363 | '''从Web.txt中发现URL,如果路径不同,请修改为实际路径''' 364 | try: 365 | f=open('Web.txt','r') 366 | url_list=f.read().split() 367 | f.close() 368 | except: 369 | return 370 | urls = [] 371 | 372 | for k in url_list: 373 | urls += [{'{#SITENAME}':k}] 374 | print json.dumps({'data':urls},sort_keys=True,indent=7,separators=(',',':')) 375 | 376 | def get_code(url): 377 | '''获取URL的HTTP code''' 378 | socket.setdefaulttimeout(5) 379 | 380 | try: 381 | response = urllib2.urlopen(url) 382 | code = response.getcode() 383 | response.close() 384 | print code 385 | except: 386 | print 0 387 | 388 | if __name__ == '__main__': 389 | parser = OptionParser( 390 | usage="%prog [-l URL] [-d d]", 391 | version="%prog $Revision$", 392 | prog="url", 393 | description="""Zabbix Web Monitor Discovery""", 394 | ) 395 | 396 | parser.add_option( 397 | "--discovery", 398 | action="store", 399 | type="string", 400 | dest="discovery", 401 | default="false", 402 | help="method is discovery", 403 | ) 404 | 405 | parser.add_option( 406 | "--url", 407 | action="store", 408 | type="string", 409 | dest="url", 410 | default=None, 411 | help="url", 412 | ) 413 | 414 | (opts, args) = parser.parse_args() 415 | m = opts.discovery 416 | url = opts.url 417 | if m == "true": 418 | discovery() 419 | elif url != None: 420 | get_code(url) 421 | ``` 422 | 423 | # 415页 424 | 425 | ```json 426 | 输出格式如下: 427 | 428 | shell# python webmonitor.py --discovery=true 429 | { 430 | "data":[ 431 | { 432 | "{#SITENAME}":"www.itnihao.com" 433 | }, 434 | { 435 | "{#SITENAME}":"www.baidu.com" 436 | }, 437 | { 438 | "{#SITENAME}":"www.weibo.com"} 439 | ] 440 | } 441 | shell# python webmonitor.py --url=http://www.baidu.com 442 | 200 443 | ``` 444 | 445 | ```shell 446 | 9.5.7 自定义key配置文件 447 | shell版本的脚本,自定义UserParameter配置文件如下: 448 | 449 | shell# cat /etc/zabbix/zabbix_agentd.conf.d/web_site_discovery.conf  450 | UserParameter=web.site.discovery,/etc/zabbix/scripts/web_site_code_status web_site_discovery   451 | UserParameter=web.site.code[*],/etc/zabbix/scripts/web_site_code_status web_site_code $1   452 | Python版本的脚本,自定义UserParameter配置文件如下: 453 | 454 | shell# cat /etc/zabbix/zabbix_agentd.conf.d/web_site_discovery.conf  455 | UserParameter=web.site.discovery,/etc/zabbix/scripts/web_site_code_status.py  discovery=true 456 | UserParameter=web.site.code[*],/etc/zabbix/scripts/web_site_code_status web_site_code.py url=“$1“ 457 | ``` 458 | 459 | # 416页 460 | 461 | ```shell 462 | 域名如下: 463 | 464 | shell# cat /etc/zabbix/scripts/Web.txt 465 | http://www.itnihao.com 466 | http://www.baidu.com 467 | http://www.weibo.com 468 | 测试命令如下: 469 | shell# zabbix_get -s 127.0.0.1 -k web.site.discovery  470 | { 471 | "data":[ 472 | { 473 | "{#SITENAME}":"www.itnihao.com"}, 474 | { 475 | "{#SITENAME}":"www.baidu.com"}, 476 | { 477 | "{#SITENAME}":"www.weibo.com"} 478 | ] 479 | } 480 | shell# zabbix_get -s 127.0.0.1 -k web.site.code[www.itnihao.com]  481 | 200 482 | shell# zabbix_get -s 127.0.0.1 -k web.site.code[www.baidu.com]  483 | 200 484 | shell# zabbix_get -s 127.0.0.1 -k web.site.code[www.weibo.com]  485 | 200 486 | 以上自定义UserParameter的清单如下: 487 | 488 | /etc/zabbix/zabbix_agentd.conf #Agent配置文件 489 | /etc/zabbix/scripts/web_site_code_status #权限755 490 | /etc/zabbix/scripts/Web.txt #网站URL存放文件 491 | /etc/zabbix/zabbix_agentd.conf.d/web_site_discovery.conf #子配置文件 492 | ``` 493 | 494 | # 425页 495 | 496 | 对于Zabbix-Server的内部监控,提供了一个用于发现主机接口的key,如下所示。 497 | 498 | `zabbix[host,discovery,interfaces]` 499 | 500 | 添加key后,在Zabbix-Server内部将会生成如下数据: 501 | 502 | `{"data":[{"{#IF.CONN}":"192.168.3.1","{#IF.IP}":"192.168.3.1","{#IF.DNS}":"","{#IF.PORT}":"10050","{#IF.TYPE}":"AGENT","{#IF.DEFAULT}":1}]} ` 503 | 504 | 其内置的一些宏功能如表9-4所示。 505 | 506 | 表9-4 内置的宏功能 507 | 508 | | 宏(Macro) | 功 能 描 述 | 509 | | --------------- | ---------------------------------- | 510 | | {#IF.CONN} | 接口的IP地址或者DNS名称 | 511 | | {#IF.IP} | 接口的IP地址 | 512 | | {#IF.DNS} | 接口的DNS名称 | 513 | | {#IF.PORT} | 接口使用的端口 | 514 | | {#IF.TYPE} | 接口类型(AGENT,SNMP,JMX,IPMI) | 515 | | {#IF.DEFAULT} | 默认的接口状态 | 516 | | 0非 | | 517 | | 1默认接口 | | 518 | | {#IF.SNMP.BULK} | 是否启用SNMP批量处理 | 519 | | 0不启用 | | 520 | | 1启用 | | 521 | 522 | # 428页 523 | 524 | ```shell 525 | 9.6.2 安装salt-master 526 | 安装salt-master,命令如下: 527 | shell# rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel- release-6-8.noarch.rpm 528 | shell# yum install salt-master 529 | ``` 530 | 531 | ```shell 532 | 启动服务,命令如下: 533 | shell# service salt-master start 534 | shell# chkconfig salt-master on 535 | ``` 536 | 537 | # 429页 538 | 539 | ```shell 540 | 安装salt-minion,命令如下: 541 | shell# yum install salt-minion 542 | 配置salt-minion,命令如下: 543 | 544 | shell# vim /etc/salt/minion 545 | master: salt-master.itnihao.com #Master的IP地址或域名 546 | id: zabbix-agent.itnihao.com #Minion的标识 547 | 启动服务,命令如下: 548 | 549 | shell# service salt-minion start 550 | shell# chkconfig salt-minion on 551 | ``` 552 | 553 | # 430-431页 554 | 555 | ```yaml 556 | 在salt-master中配置命令如下: 557 | 558 | shell# mkdir /srv/salt/ #因为StatStack安装好后无/srv/salt目录,所以建立此文件夹 559 | shell# vim /srv/salt/top.sls 560 | base: 561 | '*.itnihao.com': 562 | - zabbix 563 | shell# mkdir /srv/salt/zabbix 564 | shell# vim /srv/salt/zabbix/init.sls 565 | zabbix-agent: 566 | service: 567 | - running 568 | - watch: 569 | - file: zabbix_agentd.conf 570 | - file: zabbix_agentd.conf.d 571 | - pkg: zabbix-agentd 572 | require: 573 | - pkg: zabbix-agent 574 | zabbix-agentd: 575 | pkg.installed: 576 | - name: zabbix-agent 577 | - version: '2.2.2-0.el6.zbx' 578 | - skip_verify: True 579 | - skip_suggestions: True 580 | - fromrepo: zabbix 581 | - refresh: True 582 | 583 | zabbix_agentd.conf: 584 | file.managed: 585 | - name: /etc/zabbix/zabbix_agentd.conf 586 | - source: salt://zabbix/conf/zabbix_agentd.conf 587 | - mode: 644 588 | - user: zabbix 589 | - group: zabbix 590 | - template: jinja 591 | zabbix_agentd.conf.d: 592 | file.recurse: 593 | - name: /etc/zabbix/zabbix_agentd.conf.d 594 | - source: salt://zabbix/conf/zabbix_agentd.conf.d 595 | - include_empty: True 596 | - user: zabbix 597 | - group: zabbix 598 | - dir_mode: 755 599 | - file_mode: 644 600 | scripts: 601 | file.recurse: 602 | - name: /etc/zabbix/scripts 603 | - source: salt://zabbix/scripts 604 | - include_empty: True 605 | - user: zabbix 606 | - group: zabbix 607 | - dir_mode: 755 608 | - file_mode: 700 609 | 整个代码的目录结构如下: 610 | 611 | /srv/salt/ 612 | ├── top.sls 613 | └── zabbix 614 | ├── conf 615 | │ ├── zabbix_agentd.conf #Zabbix-Agent的配置文件 616 | │ └── zabbix_agentd.conf.d #子配置文件 617 | │ ├── haproxy_host_status.conf 618 | │ ├── haproxy_main_status.conf 619 | │ ├── haproxy_status_discovery.conf 620 | ├── init.sls #StatStack[问题同上]的状态配置文件 621 | └── scripts 622 | ├── haproxy_host_status 623 | ├── haproxy_main_status 624 | └── haproxy_status_discovery 625 | 9.6.6 执行状态同步 626 | 执行状态同步,命令如下: 627 | shell# salt '*' state.highstate 628 | ``` 629 | 630 | -------------------------------------------------------------------------------- /charter-10/Zabbix书籍V2-第10章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-10/Zabbix书籍V2-第10章-操作命令.pdf -------------------------------------------------------------------------------- /charter-10/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | # 434页 8 | 9 | ```shell 10 | 各状态代表的意思如下: 11 | 00,ERROR_STATUS。 12 | 01,TCP_ESTABLISHED。 13 | 02,TCP_SYN_SENT。 14 | 03,TCP_SYN_RECV。 15 | 04,TCP_FIN_WAIT1。 16 | 05,TCP_FIN_WAIT2。 17 | 06,TCP_TIME_WAIT。 18 | 07,TCP_CLOSE。 19 | 08,TCP_CLOSE_WAIT。 20 | 09,TCP_LAST_ACK。 21 | 0A,TCP_LISTEN。 22 | 0B,TCP_CLOSING。 23 | 10.1.2 TCP连接状态监控脚本的实现 24 | 下面通过命令来获取TCP连接状态,并自定义key。 25 | shell# vim /etc/zabbix/zabbix_agentd.conf.d/tcp_connect.conf 26 | #LISTEN,SYN-SENT,SYN-RECEIVED,ESTABLISHED,FIN-WAIT-1,FIN-WAIT-2,CLOSE-WAIT,CLOSING,LAST-ACK,TIME-WAIT和 CLOSED 27 | UserParameter=socket.tcp_listen, grep -c "\b 0A \b" /proc/net/tcp 28 | UserParameter=socket.tcp_synsent, grep -c "\b 02 \b" /proc/net/tcp 29 | UserParameter=socket.tcp_synrecv, grep -c "\b 03 \b" /proc/net/tcp 30 | UserParameter=socket.tcp_established,grep -c "\b 01 \b" /proc/net/tcp 31 | UserParameter=socket.tcp_finwait1, grep -c "\b 04 \b" /proc/net/tcp 32 | UserParameter=socket.tcp_finwait2, grep -c "\b 05 \b" /proc/net/tcp 33 | UserParameter=socket.tcp_closewait, grep -c "\b 08 \b" /proc/net/tcp 34 | UserParameter=socket.tcp_closing, grep -c "\b 0B \b" /proc/net/tcp 35 | UserParameter=socket.tcp_lastack, grep –c "\b 09 \b" /proc/net/tcp 36 | UserParameter=socket.tcp_timewait, grep -c "\b 06 \b" /proc/net/tcp 37 | UserParameter=socket.tcp_closed, grep -c "\b 07 \b" /proc/net/tcp 38 | ``` 39 | 40 | # 435页 41 | 42 | ```shell 43 | shell# vim /etc/nginx/conf.d/monitor.conf #/etc/nginx是配置目录 44 | server { 45 | listen 127.0.0.1:80; 46 | server_name 127.0.0.1; 47 | location /nginxstatus { 48 | stub_status on; 49 | access_log off; 50 | allow 127.0.0.1; #这里是允许的IP地址 51 | deny all; 52 | } 53 | } 54 | shell# nginx -t #如果输出错误,请检查配置文件 55 | nginx: the configuration file etc/nginx/nginx.conf syntax is ok 56 | nginx: configuration file/etc/nginx/nginx.conf test is successful 57 | shell# nginx -s reload #测试配置是否正确 58 | ``` 59 | 60 | # 436页 61 | 62 | ```shell 63 | Nginx监控脚本如下: 64 | 65 | shell# vim /etc/zabbix/scripts/nginx_status 66 | #!/bin/bash 67 | 68 | # function:monitor nginx from zabbix 69 | # License: GPL 70 | # mail: itnihao@qq.com 71 | # version 1.0 date:2012-12-09 72 | # version 1.0 date:2013-01-15 73 | # version 1.1 date:2014-09-05 74 | 75 | source /etc/bashrc >/dev/null 2>&1 76 | source /etc/profile >/dev/null 2>&1 77 | nginxstatus=http://127.0.0.1/nginxstatus 78 | 79 | # Functions to return nginx stats 80 | function checkavailable { 81 | code=$(curl -o /dev/null -s -w %{http_code} ${nginxstatus}) 82 | if [ "${code}" == "200" ];then 83 | return 1 84 | else 85 | echo 0 86 | fi 87 | } 88 | function active { 89 | checkavailable|| curl -s "${nginxstatus}" | grep 'Active' | awk '{print $3}' 90 | } 91 | function reading { 92 | checkavailable|| curl -s "${nginxstatus}" | grep 'Reading' | awk '{print $2}' 93 | } 94 | function writing { 95 | checkavailable|| curl -s "${nginxstatus}" | grep 'Writing' | awk '{print $4}' 96 | } 97 | function waiting { 98 | checkavailable|| curl -s "${nginxstatus}" | grep 'Waiting' | awk '{print $6}' 99 | } 100 | function accepts { 101 | checkavailable|| curl -s "${nginxstatus}" | awk NR==3 | awk '{print $1}' 102 | } 103 | function handled { 104 | checkavailable|| curl -s "${nginxstatus}" | awk NR==3 | awk '{print $2}' 105 | } 106 | function requests { 107 | checkavailable|| curl -s "${nginxstatus}" | awk NR==3 | awk '{print $3}' 108 | } 109 | 110 | case "$1" in 111 | active) 112 | active 113 | ;; 114 | reading) 115 | reading 116 | ;; 117 | writing) 118 | writing 119 | ;; 120 | waiting) 121 | waiting 122 | ;; 123 | accepts) 124 | accepts 125 | ;; 126 | handled) 127 | handled 128 | ;; 129 | requests) 130 | requests 131 | ;; 132 | *) 133 | echo "Usage: $0 {active |reading |writing |waiting |accepts |handled |requests }" 134 | esac 135 | ``` 136 | 137 | # 437页 138 | 139 | ```shell 140 | key的配置文件如下: 141 | shell# vim /etc/zabbix/zabbix_agentd.conf.d/monitor_ningx.conf 142 | UserParameter=nginx.accepts,/etc/zabbix/scripts/check_nginx_status.sh accepts 143 | UserParameter=nginx.handled,/etc/zabbix/scripts/check_nginx_status.sh handled 144 | UserParameter=nginx.requests,/etc/zabbix/scripts/check_nginx_status.sh requests 145 | UserParameter=nginx.connections.active,/etc/zabbix/scripts/check_nginx_status.sh active 146 | UserParameter=nginx.connections.reading,/etc/zabbix/scripts/check_nginx_status.sh reading 147 | UserParameter=nginx.connections.writing,/etc/zabbix/scripts/check_nginx_status.sh writing 148 | UserParameter=nginx.connections.waiting,/etc/zabbix/scripts/check_nginx_status.sh waiting 149 | ``` 150 | 151 | # 438页 152 | 153 | ```shell 154 | shell# vim /etc/php-fpm.conf 155 | pm.status_path = /phpfpmstatus 156 | shell# /etc/init.d/php-fpm restart 157 | shell# vim /etc/nginx/conf.d/monitor.conf 158 | server { 159 | listen 127.0.0.1:80; 160 | server_name 127.0.0.1; 161 | location /nginxstatus { 162 | stub_status on; 163 | access_log off; 164 | allow 127.0.0.1; 165 | deny all; 166 | } 167 | location ~ ^/(phpfpmstatus)$ { 168 | include fastcgi_params; 169 | fastcgi_pass unix:/tmp/fpm.sock; 170 | fastcgi_param SCRIPT_FILENAME $fastcgi_script_name; 171 | } 172 | } 173 | ``` 174 | 175 | # 439页 176 | 177 | ```shell 178 | shell# vim /etc/zabbix/scripts/monitor_phpfpm_status 179 | #!/bin/bash 180 | 181 | # function:monitor php-fpm status from zabbix 182 | # License: GPL 183 | # mail:admin@itnihao.com 184 | # date:2016-01-06 185 | 186 | source /etc/bashrc >/dev/null 2>&1 187 | source /etc/profile >/dev/null 2>&1 188 | 189 | PHPFPM_FILE=/var/log/zabbix/phpfpmstatus.tmp 190 | CMD () { 191 | curl http://127.0.0.1/phpfpmstatus >${PHPFPM_FILE} 2>&1 192 | } 193 | 194 | if [ -e ${PHPFPM_FILE} ]; then 195 | TIMEFROM=`stat -c %Y ${TMP_MYSQL_STATUS}` 196 | TIMENOW=`date +%s` 197 | if [ `expr $TIMENOW - $TIMEFROM` -gt 60 ]; then 198 | rm -f ${PHPFPM_FILE} 199 | CMD 200 | fi 201 | else 202 | CMD 203 | fi 204 | 205 | pool(){ 206 | awk '/pool/ {print $NF}' ${PHPFPM_FILE} 207 | } 208 | process_manager() { 209 | awk '/process manager/ {print $NF}' ${PHPFPM_FILE} 210 | } 211 | 212 | start_since(){ 213 | awk '/^start since:/ {print $NF}' ${PHPFPM_FILE} 214 | } 215 | accepted_conn(){ 216 | awk '/^accepted conn:/ {print $NF}' ${PHPFPM_FILE} 217 | } 218 | listen_queue(){ 219 | awk '/^listen queue:/ {print $NF}' ${PHPFPM_FILE} 220 | } 221 | max_listen_queue(){ 222 | awk '/^max listen queue:/ {print $NF}' ${PHPFPM_FILE} 223 | } 224 | listen_queue_len(){ 225 | awk '/^listen queue len:/ {print $NF}' ${PHPFPM_FILE} 226 | } 227 | idle_processes(){ 228 | awk '/^idle processes:/ {print $NF}' ${PHPFPM_FILE} 229 | } 230 | active_processes(){ 231 | awk '/^active processes:/ {print $NF}' ${PHPFPM_FILE} 232 | } 233 | total_processes(){ 234 | awk '/^total processes:/ {print $NF}' ${PHPFPM_FILE} 235 | } 236 | max_active_processes(){ 237 | awk '/^max active processes:/ {print $NF}' ${PHPFPM_FILE} 238 | } 239 | max_children_reached(){ 240 | awk '/^max children reached:/ {print $NF}' ${PHPFPM_FILE} 241 | } 242 | 243 | case "$1" in 244 | pool) 245 | pool 246 | ;; 247 | process_manager) 248 | process_manager 249 | ;; 250 | start_since) 251 | start_since 252 | ;; 253 | accepted_conn) 254 | accepted_conn 255 | ;; 256 | listen_queue) 257 | listen_queue 258 | ;; 259 | max_listen_queue) 260 | max_listen_queue 261 | ;; 262 | listen_queue_len) 263 | listen_queue_len 264 | ;; 265 | idle_processes) 266 | idle_processes 267 | ;; 268 | active_processes) 269 | active_processes 270 | ;; 271 | total_processes) 272 | total_processes 273 | ;; 274 | max_active_processes) 275 | max_active_processes 276 | ;; 277 | max_children_reached) 278 | max_children_reached 279 | ;; 280 | *) 281 | echo "Usage: $0 {pool|process_manager|start_since|accepted_conn| listen_queue|max_listen_queue|listen_queue_len|idle_processes|active_processes|total_processes|max_active_processes|max_children_reached}" 282 | esac 283 | ``` 284 | 285 | # 441页 286 | 287 | ```shell 288 | key的php-fpm.conf子配置文件如下: 289 | 290 | shell# cat /etc/zabbix/zabbix_agentd.conf.d/php-fpm.conf 291 | UserParameter=phpfpm.status.pool,/etc/zabbix/scripts/check_phpfpm.sh pool 292 | UserParameter=phpfpm.status.process.manager,/etc/zabbix/scripts/check_phpfpm.sh process_manager 293 | UserParameter=phpfpm.status.start.since,/etc/zabbix/scripts/check_phpfpm.sh start_since 294 | UserParameter=phpfpm.status.accepted.conn,/etc/zabbix/scripts/check_phpfpm.sh accepted_conn 295 | UserParameter=phpfpm.status.listen.queue,/etc/zabbix/scripts/check_phpfpm.sh listen_queue 296 | UserParameter=phpfpm.status.max.listen.queue,/etc/zabbix/scripts/check_phpfpm.sh max_listen_queue 297 | UserParameter=phpfpm.status.listen.queue.len,/etc/zabbix/scripts/check_phpfpm.sh listen_queue_len 298 | UserParameter=phpfpm.status.idle.processes,/etc/zabbix/scripts/check_phpfpm.sh idle_processes 299 | UserParameter=phpfpm.status.active.processes,/etc/zabbix/scripts/check_phpfpm.sh active_processes 300 | UserParameter=phpfpm.status.total.processes,/etc/zabbix/scripts/check_phpfpm.sh total_processes 301 | UserParameter=phpfpm.status.max.active.processes,/etc/zabbix/scripts/check_phpfpm.sh max_active_processes 302 | UserParameter=phpfpm.status.max.children.reached,/etc/zabbix/scripts/check_phpfpm.sh max_children_reached 303 | ``` 304 | 305 | # 442页 306 | 307 | ```sql 308 | mysql> SHOW GLOBAL STATUS; #查看全局状态 309 | mysql> SHOW GLOBAL VARIABLES; #查看全局变量 310 | mysql> SHOW ENGINE INNODB STATUS; #查看InooDB状态 311 | mysql> SHOW SLAVE STATUS; #查看Slave状态 312 | mysql> SHOW MASTER STATUS; #查看Master状态 313 | mysql> SHOW BINARY LOGS; #查看日志状态 314 | mysql> SHOW PROCESSLIST; #查看进程状态 315 | mysql> SELECT SUM(compress_time) AS compress_time, SUM(uncompress_time) AS uncompress_time FROM information_schema.INNODB_CMP; 316 | mysql> SELECT LOWER(REPLACE(trx_state, " ", "_")) AS state, count(*) AS cnt from information_schema.INNODB_TRX GROUP BY state; 317 | mysql> SELECT SUM(trx_rows_locked) AS rows_locked, SUM(trx_rows_modified) AS rows_modified, SUM(trx_lock_memory_bytes) AS lock_memory FROM information_ schema.INNODB_TRX;#查看锁 318 | mysql> select table_name,(DATA_LENGTH+INDEX_LENGTH)/1024/1024 as total_mb, table_rows from information_schema.tables where table_rows is not NULL; #查看表名和表记录条数 319 | ``` 320 | 321 | ```shell 322 | shell# cp check_mysql /etc/zabbix/scripts/check_mysql 323 | shell# vim /etc/zabbix/zabbix_agentd.conf.d/userparameter_mysql.conf 324 | UserParameter=mysql.variables[*], /etc/zabbix/scripts/check_mysql -collect variables -metric "mysql.variables[$1]" --host="$2" --port="$3" --user="$4" --pass="$5" 325 | UserParameter=mysql.status[*], /etc/zabbix/scripts/check_mysql -collect status -metric "mysql.status[$1]" --host="$2" --port="$3" --user="$4" --pass= "$5" 326 | UserParameter=mysql.processlist.state[*],/etc/zabbix/scripts/check_mysql -collect showProcesslist -metric "mysql.processlist.state[$1]" --host="$2" --port="$3" --user="$4" --pass="$5" 327 | UserParameter=mysql.innodb[*], /etc/zabbix/scripts/check_mysql -collect innodb -metric "mysql.innodb[$1]" --host="$2" --port="$3" --user="$4" --pass= "$5" 328 | UserParameter=mysql.master[*], /etc/zabbix/scripts/check_mysql -collect master -metric "mysql.master[$1]" --host="$2" --port="$3" --user="$4" --pass= "$5" 329 | UserParameter=mysql.slave[*], /etc/zabbix/scripts/check_mysql -collect slave -metric "mysql.slave[$1]" --host="$2" --port="$3" --user="$4" --pass="$5" 330 | UserParameter=mysql.table.discovery[*], /etc/zabbix/scripts/check_mysql -collect discoveryTable -metric "mysql.table.discovery[$1]" --host="$2" --port="$3" --user="$4" --pass="$5" 331 | UserParameter=mysql.table.info.rows[*], /etc/zabbix/scripts/check_mysql -collect tableInfoRows -metric "mysql.table.info.rows[$1]" --host="$2" --port="$3" --user="$4" --pass="$5" 332 | UserParameter=mysql.total.spaces.used[*],/etc/zabbix/scripts/check_mysql -collect tableInfoUsed -metric "mysql.total.spaces.used[$1]" --host="$2" --port="$3" --user="$4" --pass="$5" 333 | UserParameter=mysql.ping[*], /etc/zabbix/scripts/check_mysql -collect ping -metric ping --host="$1" --port="$2" --user="$3" --pass="$4" 334 | ``` 335 | 336 | # 443页 337 | 338 | ```shell 339 | shell# mysql -uroot -p 340 | mysql> GRANT USAGE,SELECT,PROCESS,REPLICATION CLIENT,REPLICATION SLAVE ON *.* TO 'zabbix'@'127.0.0.1' IDENTIFIED BY 'zabbix'; 341 | mysql> flush privileges; 342 | ``` 343 | 344 | # 449页 345 | 346 | ```shell 347 | shell# ipmitool sensor 348 | Intrusion | 0x00 | ok 349 | Fan1 | 4440 RPM | ok 350 | Fan2 | 4440 RPM | ok 351 | Fan3 | 4440 RPM | ok 352 | Fan4 | 4440 RPM | ok 353 | Fan5 | 4440 RPM | ok 354 | Fan6 | 4440 RPM | ok 355 | Inlet Temp | 32 degrees C | ok 356 | CPU Usage | 1 percent | ok 357 | IO Usage | 0 percent | ok 358 | MEM Usage | 0 percent | ok 359 | SYS Usage | 2 percent | ok 360 | Exhaust Temp | 37 degrees C | ok 361 | Temp | 45 degrees C | ok 362 | Temp | 44 degrees C | ok 363 | OS Watchdog | 0x00 | ok 364 | VCORE PG | 0x00 | ok 365 | VCORE PG | 0x00 | ok 366 | 3.3V PG | 0x00 | ok 367 | 5V AUX PG | 0x00 | ok 368 | ``` 369 | 370 | # 452页 371 | 372 | 表10-2 常见的磁盘阵列卡工具 373 | 374 | | 工具名称 | 支持的型号 | 375 | | -------- | -------------------- | 376 | | LSIUtil | LSI1068系列阵列卡 | 377 | | MegaCli | LSI2208 | 378 | | SAS2IRCU | LSI2308 | 379 | | SAS3IRCU | LSI3008 | 380 | | STorCLI | LSI3108 | 381 | | Hpacucli | HP服务器特有的阵列卡 | 382 | | Hpssacli | HP服务器特有的阵列卡 | 383 | 384 | LSI提供的工具名称为MegaRAID,其官方下载地址为: 385 | 386 | https://www.broadcom.com/products/storage/raid-controllers/megaraid-sas-9361-4i#downloads 387 | 388 | # 453页 389 | 390 | ```shell 391 | 与磁盘监控相关的命令和文件如下: 392 | 393 | /etc/zabbix/scripts/check_lsimegaraid.sh #检测脚本 394 | /etc/zabbix/scripts/check_MegaCli64 #检测脚本 395 | /etc/zabbix/zabbix_agentd.conf.d/userparameter_lsimegaraid.conf #配置文件 396 | 配置sudo,允许check_MegaCli64命令访问。 397 | 398 | /etc/sudoers.d/zabbix_sudo 399 | zabbix ALL=(ALL) NOPASSWD: /etc/zabbix/scripts/check_MegaCli64 400 | 配置UserParameter,定义磁盘监控的key。 401 | 402 | UserParameter=lsimegaraid.discovery[*],/etc/zabbix/scripts/check_lsimegaraid.sh "discovery" $1 $2 403 | UserParameter=lsimegaraid.trapper[*],/etc/zabbix/scripts/check_lsimegaraid.sh "trapper" $1 $2 404 | 添加脚本与配置文件[指哪个目录?]后,需要执行重启Zabbix-Agent的操作。 405 | 406 | shell# chmod 755 /etc/zabbix/scripts/check_lsimegaraid.sh 407 | shell# chmod 755 /etc/zabbix/scripts/check_MegaCli64 408 | shell# chown zabbix /etc/zabbix/scripts/check_lsimegaraid.sh 409 | shell# chown zabbix /etc/zabbix/scripts/check_MegaCli64 410 | shell# systemctl restart zabbix-agent 411 | ``` 412 | 413 | # 455页 414 | 415 | ```shell 416 | Router#configure terminal 417 | Router(config)#ip access-list standard snmp-filter #创建方位列表 418 | Router(config-std-nacl)#permit 192.168.0.240 #允许192.168.0.240访问 419 | Router(config-std-nacl)#deny any log #拒绝其他用户访问,但记录日志 420 | Router(config-std-nacl)#end 421 | Router#configure terminal 422 | Router(config)#snmp-server community public RO snmp-filter #设置团组(community)名为public 423 | ``` 424 | 425 | Cisco的SNMP配置文档请参考如下地址: 426 | 427 | http://www.cisco.com/c/en/us/td/docs/ios/12_2/configfun/configuration/guide/ffun_c/fcf014.html 428 | 429 | ```shell 430 | shell# yum install net-snmp-utils -y 431 | shell# snmpwalk -v 2c -c public 172.30.31.10 1.3.6.1.4.1.9.2.1.57.0 432 | SNMPv2-SMI::enterprises.9.2.1.57.0 = INTEGER: 8 433 | ``` 434 | 435 | # 458页 436 | 437 | ```shell 438 | shell# systemctl restart zabbix-server 439 | Shutting down zabbix_server: [ OK ] 440 | Starting zabbix_server: zabbix_server [19571]: ERROR: cannot start vmware collector because Zabbix server is built without VMware support 441 | [FAILED] 442 | ``` 443 | 444 | ```shell 445 | shell# vim /etc/zabbix/zabbix_server.conf 446 | ### Option: StartVMwareCollectors 447 | # Number of pre-forked vmware collector instances. 448 | # 449 | # Mandatory: no 450 | # Range: 0-250 451 | # Default: 452 | # StartVMwareCollectors=0 453 | StartVMwareCollectors=1 454 | ``` 455 | 456 | # 462页 457 | 458 | ```shell 459 | /etc/zabbix/scripts/check_rabbitmq #检测脚本 460 | /etc/zabbix/zabbix_agentd.conf.d/userparameter_rabbitmq.conf #配置文件 461 | 添加脚本与配置文件[指哪个目录?]后,需要执行重启Zabbix-Agent的操作。 462 | shell# chmod 755 /etc/zabbix/scripts/check_rabbitmq 463 | shell# chown zabbix:zabbix /etc/zabbix/scripts/check_rabbitmq 464 | shell# systemctl restart zabbix-agent 465 | ``` 466 | 467 | # 463页 468 | 469 | ```shell 470 | # 查看当前所有用户 471 | Shell# rabbitmqctl list_users 472 | # 添加新用户,用户名为admin,密码为pwd 473 | shell# rabbitmqctl add_user admin pwd 474 | # 设置用户tag 475 | shell# rabbitmqctl set_user_tags admin administrator 476 | # 赋予默认用户admin的全部操作权限[这条注释对吗?] 477 | shell# rabbitmqctl set_permissions -p / admin ".*" ".*" ".*" 478 | # 查看用户的权限 479 | shell# rabbitmqctl list_user_permissions admin 480 | 测试获取RabbitMQ数据,命令如下: 481 | 482 | shell# zabbix_get -s 127.0.0.1 -k rabbitmq.discovery.node 483 | {"data":[{"{#NODENAME}":"rabbit@localhost","{#NODETYPE}":"disc"}]} 484 | ``` 485 | 486 | # 465页 487 | 488 | ```shell 489 | shell# curl "http://localhost:9200/_cluster/health") 490 | shell# curl "http://localhost:9200/_nodes/_local/stats?all=true" 491 | 获取数据之后,我们编写一些代码将数据输出为Zabbix需要的格式。 492 | 关于Elasticsearch的监控指标,官方文档地址如下: 493 | ``` 494 | 495 | https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-stats.html 496 | 497 | # 466页 498 | 499 | ```shell 500 | Kafka监控的JMX配置命令如下: 501 | shell# cd /data/app/kafka_2.12-1.1.0/ #进入Kafka所在目录 502 | shell# bin/kafka-server-stop.sh 503 | shell# JMX_PORT=10053 bin/kafka-server-start.sh -daemon config/server.properties #开启JMX端口 504 | ``` 505 | 506 | ```bash 507 | Kafka服务器指标:CPU 负载、磁盘IO、内存使用情况。[中文意思?] 508 | JVM监控:主要监控Java的垃圾回收时间,Java的垃圾回收机制对性能的影响比较明显。 509 | Kafka Broker监控:Kafka集群中Broker列表,Broker运行状况,包括Node下线、活跃数量、Broker是否提供服务、数据流量、流入速度、流出速度。 510 | Kafka Controller监控:Controller存活数目。 511 | Kafka Producer监控:Producer数量、排队情况、请求响应时间。 512 | Kafka Consumer监控:Consumer队列中排队请求数、请求响应时间、最近1分钟平均每秒请求数。 513 | Kafka Topic监控:数据量大小、Offset数据流量、流入速度、流出速度。 514 | ``` 515 | 516 | 更多的监控指标和详细的解释,请参考《Kafka权威指南》的第10章。官方文档见http://kafka.apache.org/documentation/#monitoring。 517 | 518 | # 468页 519 | 520 | ```shell 521 | Redis监控的配置命令如下: 522 | shell# vim /etc/zabbix/zabbix_agentd.conf.d/userparameter_redis.conf 523 | UserParameter=redis_info[*],(echo info; sleep 0.01) | telnet 127.0.0.1 $1 2>&1|grep "\b$2\b"|cut -d : -f2 524 | UserParameter=redis.port.discovery,sudo /etc/zabbix/scripts/process_ discovery redis 525 | ``` 526 | 527 | # 470页 528 | 529 | ```shell 530 | 安装Oracle客户端软件包,执行如下命令: 531 | shell# rpm -ivh oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm 532 | shell# rpm -ivh oracle-instantclient11.2-devel-11.2.0.3.0-1.x86_64.rpm 533 | shell# rpm -ivh oracle-instantclient11.2-sqlplus-11.2.0.3.0-1.x86_64.rpm 534 | shell# rpm -ivh cx_Oracle-5.1.2-11g-py26-1.x86_64.rpm #可以使用pip安装 535 | shell# rpm -ivh python-argparse-1.2.1-2.el6.noarch.rpm 536 | Oracle客户端软件包的下载地址如下,读者需要根据不同的Oracle版本进行下载,如图10-50所示。 537 | ``` 538 | 539 | http://www.oracle.com/technetwork/database/database-technologies/instant-client/downloads/ index.html 540 | 541 | # 471页 542 | 543 | ```bash 544 | 安装成功后,配置环境变量如下: 545 | 546 | shell# cat > /etc/profile.d/oracle.sh << EOF 547 | #!/bin/bash 548 | LD_LIBRARY_PATH="/usr/lib/oracle/11.2/client64/lib:${LD_LIBRARY_PATH}" 549 | export LD_LIBRARY_PATH 550 | ORACLE_HOME="/usr/lib/oracle/11.2/client64/lib" 551 | export ORACLE_HOME 552 | EOF 553 | 将代码和配置文件放到相应的目录下: 554 | 555 | #代码见https://github.com/zabbix-book/Pyora/blob/master/pyora.py 556 | shell# /etc/zabbix/scripts/pyora.py 557 | shell# vim /etc/zabbix/zabbix_agentd.conf.d/oracle.conf 558 | UserParameter=pyora[*],/etc/zabbix/scripts/pyora.py $1 $2 $3 $4 $5 $6 $7 $8 559 | 配置Oracle的监控账户,账户名称是zabbix,密码为zabbix。 560 | 561 | shell# su - oracle 562 | shell# sqlplus / as sysdba 563 | SQL> CREATE USER zabbix IDENTIFIED BY zabbix DEFAULT TABLESPACE SYSTEM TEMPORARY TABLESPACE TEMP PROFILE DEFAULT ACCOUNT UNLOCK; #创建用户zabbix,密码为zabbix 564 | SQL> GRANT CONNECT TO zabbix; 565 | SQL> GRANT RESOURCE TO zabbix; 566 | SQL> ALTER USER zabbix DEFAULT ROLE ALL; 567 | SQL> GRANT SELECT ANY TABLE TO zabbix; 568 | SQL> GRANT CREATE SESSION TO zabbix; 569 | SQL> GRANT SELECT ANY DICTIONARY TO zabbix; 570 | SQL> GRANT UNLIMITED TABLESPACE TO zabbix; 571 | SQL> GRANT SELECT ANY DICTIONARY TO zabbix; 572 | SQL> GRANT SELECT ON V_$SESSION TO zabbix; 573 | SQL> GRANT SELECT ON V_$SYSTEM_EVENT TO zabbix; 574 | SQL> GRANT SELECT ON V_$EVENT_NAME TO zabbix; 575 | SQL> GRANT SELECT ON V_$RECOVERY_FILE_DEST TO zabbix; 576 | 接下来,我们使用zabbix_get来测试获取数据。 577 | 578 | shell# zabbix_get -s 127.0.0.1 -k pyora[uptime] 579 | 21623423 580 | ``` 581 | 582 | # 472页 583 | 584 | https://github.com/zabbix-book/Pyora/blob/master/zabbix-template/Pyora.xml 585 | 586 | # 474页 587 | 588 | ```bash 589 | 开启JMX参数,配置如下: 590 | 591 | shell# cd /opt/weblogic/user_projects/domains/webapp/ 592 | shell# vim bin/setDomainEnv.sh 593 | export JAVA_OPTIONS="${JAVA_OPTIONS} -Djava.rmi.server.hostname=本机的IP地址" 594 | export JAVA_OPTIONS="${JAVA_OPTIONS} -Dcom.sun.management.jmxremote" 595 | export JAVA_OPTIONS="${JAVA_OPTIONS} -Dcom.sun.management.jmxremote.port= 10053" 596 | export JAVA_OPTIONS="${JAVA_OPTIONS} -Dcom.sun.management.jmxremote.authenticate= false" 597 | export JAVA_OPTIONS="${JAVA_OPTIONS} -Dcom.sun.management.jmxremote.ssl= false" 598 | ``` 599 | 600 | # 475页 601 | 602 | ```shell 603 | C:\> typeperf -qx 604 | 省略输出...... 605 | \MSRS 2008 R2 Windows Service(sqlexpress)\Report Requests 606 | \MSRS 2008 R2 Windows Service(sqlexpress)\Total Reports Executed 607 | \MSRS 2008 R2 Windows Service(sqlexpress)\Reports Executed/Sec 608 | \MSRS 2008 R2 Windows Service(sqlexpress)\Total Processing Failures 609 | \MSRS 2008 R2 Windows Service(sqlexpress)\Total Rejected Threads 610 | \MSRS 2008 R2 Windows Service(sqlexpress)\Active Sessions 611 | \MSRS 2008 R2 Windows Service(sqlexpress)\First Session Requests/Sec 612 | \MSRS 2008 R2 Windows Service(sqlexpress)\Next Session Requests/Sec 613 | \MSRS 2008 R2 Windows Service(sqlexpress)\Total Cache Hits 614 | \MSRS 2008 R2 Windows Service(sqlexpress)\Cache Hits/Sec 615 | \MSRS 2008 R2 Windows Service(sqlexpress)\Total Cache Misses 616 | 省略输出......[这段数据缺少说明文字] 617 | ``` 618 | 619 | # 478 620 | 621 | 可以从https://github.com/zabbix-book/check-ssl-certificates获取所需的文件。 622 | 623 | ```python 624 | 脚本内容如下: 625 | shell# cat /etc/zabbix/scripts/check_ssl_certificates.py 626 | #!/usr/bin/python 627 | import socket 628 | import ssl 629 | import datetime 630 | import argparse 631 | 632 | def ssl_expiry_datetime(hostname): 633 | ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z' 634 | 635 | context = ssl.create_default_context() 636 | conn = context.wrap_socket(socket.socket(socket.AF_INET),server_ hostname=hostname,) 637 | # 3 second timeout because Lambda has runtime limitations 638 | conn.settimeout(3.0) 639 | 640 | conn.connect((hostname, 443)) 641 | ssl_info = conn.getpeercert() 642 | # parse the string from the certificate into a Python datetime object 643 | return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt) 644 | 645 | def ssl_valid_time_remaining(hostname): 646 | """Get the number of days left in a cert's lifetime.""" 647 | expires = ssl_expiry_datetime(hostname) 648 | return expires - datetime.datetime.utcnow() 649 | 650 | parser = argparse.ArgumentParser(description='returns the time before expiration of certificate') 651 | parser.add_argument("-c","--hostname", help="hostname of the certificate you want to check") 652 | args = parser.parse_args() 653 | 654 | expire = ssl_valid_time_remaining(args.hostname) 655 | print int(round(datetime.timedelta.total_seconds(expire), 0)) 656 | ``` 657 | 658 | ```json 659 | 在本例中,我们只监控证书过期时间,对其他信息不再监控,比如还可以获取到如下相关信息。 660 | 661 | {'OCSP': ('http://ocsp.digicert.com',), 662 |  'caIssuers': (u'http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',), 663 |  'crlDistributionPoints': (u'http://crl3.digicert.com/sha2-ev-server-g2.crl', u'http://crl4.digicert.com/sha2-ev-server-g2.crl'), 664 |  'issuer': ((('countryName', u'US'),), 665 |   (('organizationName', u'DigiCert Inc'),), 666 |   (('organizationalUnitName', u'www.digicert.com'),), 667 |   (('commonName', u'DigiCert SHA2 Extended Validation Server CA'),)), 668 |  'notAfter': 'Jun  3 12:00:00 2020 GMT', 669 |  'notBefore': u'May  8 00:00:00 2018 GMT', 670 |  'serialNumber': u'0A0630427F5BBCED6957396593B6451F', 671 |  'subject': ((('businessCategory', u'Private Organization'),), 672 |   (('1.3.6.1.4.1.311.60.2.1.3', u'US'),), 673 |   (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),), 674 |   (('serialNumber', u'5157550'),), 675 |   (('countryName', u'US'),), 676 |   (('stateOrProvinceName', u'California'),), 677 |   (('localityName', u'San Francisco'),), 678 |   (('organizationName', u'GitHub, Inc.'),), 679 |   (('commonName', u'github.com'),)), 680 |  'subjectAltName': (('DNS', 'github.com'), ('DNS', 'www.github.com')), 681 |  'version': 3L} 682 | ``` 683 | 684 | # 480页 685 | 686 | ```shell 687 | {Template App SSL Certificate:ssl.certificates["www.github.com"].last()} <2592000 688 | ``` 689 | 690 | # 481页 691 | 692 | 网络上有很多现成的监控模板,读者可以拿来直接使用,或者参考其实现思路,多去动手实践,举一反三。关于监控模板可参考如下地址: 693 | 694 | https://github.com/zabbix-book/ 695 | 696 | https://www.zabbix.org/wiki/Zabbix_Templates 697 | 698 | https://www.zabbix.com/integrations/ 699 | 700 | http://share.zabbix.com 701 | 702 | https://github.com/monitoringartist/zabbix-community-repos -------------------------------------------------------------------------------- /charter-11/Zabbix书籍V2-第11章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/Zabbix书籍V2-第11章-操作命令.pdf -------------------------------------------------------------------------------- /charter-11/img/image-20190912140906308.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912140906308.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141013345.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141013345.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141055263.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141055263.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141125266.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141125266.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141145900.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141145900.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141255101.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141255101.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141327627.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141327627.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141344256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141344256.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141438566.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141438566.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141500653.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141500653.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141528027.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141528027.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141549043.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141549043.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141625547.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141625547.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141658896.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141658896.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141720320.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141720320.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141745765.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141745765.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141801977.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141801977.png -------------------------------------------------------------------------------- /charter-11/img/image-20190912141829144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-11/img/image-20190912141829144.png -------------------------------------------------------------------------------- /charter-11/readme.md: -------------------------------------------------------------------------------- 1 | #482页 2 | 3 | ![image-20190912140906308](img/image-20190912140906308.png) 4 | 5 | # 483页 6 | 7 | ![image-20190912141013345](img/image-20190912141013345.png) 8 | 9 | ![image-20190912141055263](img/image-20190912141055263.png) 10 | 11 | # 484页 12 | 13 | ![image-20190912141125266](img/image-20190912141125266.png) 14 | 15 | 16 | 17 | ![image-20190912141145900](img/image-20190912141145900.png) 18 | 19 | # 485页 20 | 21 | https://grafana.com/grafana/download 22 | 23 | ```shell 24 | 这里以安装Grafana 5.2.2-1版本为例进行讲解。 25 | 使用如下命令进行安装。 26 | 27 | shell# wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/ grafana-5.2.2-1.x86_64.rpm  28 | shell# yum localinstall grafana-5.2.2-1.x86_64.rpm  29 | #CentOS 7启动命令 30 | shell# systemctl daemon-reload 31 | shell# systemctl start grafana-server 32 | shell# systemctl status grafana-server 33 | shell# systemctl enable grafana-server.service 34 | #CentOS 6启动命令 35 | shell# service grafana-server start 36 | shell# /sbin/chkconfig grafana-server on 37 | ``` 38 | 39 | ```shell 40 | shell# grafana-cli plugins install alexanderzobnin-zabbix-app 41 | shell# service grafana-server restart 42 | ``` 43 | 44 | ![image-20190912141255101](img/image-20190912141255101.png) 45 | 46 | # 486页 47 | 48 | ![image-20190912141327627](img/image-20190912141327627.png) 49 | 50 | ![image-20190912141344256](img/image-20190912141344256.png) 51 | 52 | # 487页 53 | 54 | ![image-20190912141438566](img/image-20190912141438566.png) 55 | 56 | 57 | 58 | ![image-20190912141500653](img/image-20190912141500653.png) 59 | 60 | # 488页 61 | 62 | ![image-20190912141528027](img/image-20190912141528027.png) 63 | 64 | ![image-20190912141549043](img/image-20190912141549043.png) 65 | 66 | # 489页 67 | 68 | 表11-1 各配置字段说明 69 | 70 | | 字  段 | 说  明 | 71 | | -------- | ----------------------------------------- | 72 | | Name | 名称,可以自定义 | 73 | | Type | 类型,选择“Zabbix” | 74 | | URL | http://10.211.55.9/zabbix/api_jsonrpc.php | 75 | | Access | 选择“Brower” | 76 | | Username | 用户名为Admin | 77 | | Paasword | 密码为zabbix | 78 | 79 | ![image-20190912141625547](img/image-20190912141625547.png) 80 | 81 | # 490页 82 | 83 | ![image-20190912141658896](img/image-20190912141658896.png) 84 | 85 | ![image-20190912141720320](img/image-20190912141720320.png) 86 | 87 | # 491页 88 | 89 | ![image-20190912141745765](img/image-20190912141745765.png) 90 | 91 | ![image-20190912141801977](img/image-20190912141801977.png) 92 | 93 | # 492页 94 | 95 | ![image-20190912141829144](img/image-20190912141829144.png) 96 | 97 | # 493页 98 | 99 | ```shell 100 | 安装命令如下: 101 | shell# cd /usr/share/zabbix 102 | shell# wget https://raw.githubusercontent.com/OneOaaS/graphtrees/master/ graphtree3.0.4.patch 103 | shell# yum install -y patch 104 | shell# patch -Np0 enable 165 | Password: 166 | S2#configure terminal 167 | Enter configuration commands, one per line. End with CNTL/Z. 168 | S2(config)#lldp run 169 | S2(config)#end 170 | S2#write 171 | Building configuration... 172 | [OK] 173 | S2# 174 | 在其他交换机上依次配置开启LLDP。在SW2交换机上查看配置文件,命令如下: 175 | 176 | S2# show configuration 177 | 省略部分配置文件 178 | lldp run 179 | interface Ethernet0/0 180 | ip address 192.168.1.42 255.255.255.0 181 | no mop enabled 182 | ! 183 | interface Ethernet0/1 184 | ip address 10.211.55.42 255.255.255.0 185 | ! 186 | interface Ethernet0/2 187 | ip address 192.168.2.42 255.255.255.0 188 | ! 189 | interface Ethernet0/3 190 | ip address 192.168.3.42 255.255.255.0 191 | ! 192 | interface Ethernet1/0 193 | ip address 192.168.4.42 255.255.255.0 194 | ! 195 | interface Ethernet1/1 196 | ip address 192.168.5.42 255.255.255.0 197 | no mop enabled 198 | 省略部分配置文件 199 | ``` 200 | 201 | 202 | 203 | # 505页 204 | 205 | ```shell 206 | S2# show lldp neighbors 207 | Capability codes: 208 | (R) Router, (B) Bridge, (T) Telephone, (C) DOCSIS Cable Device 209 | (W) WLAN Access Point, (P) Repeater, (S) Station, (O) Other 210 | Device ID Local Intf Hold-time Capability Port ID 211 | R3 Et1/0 120 R Et0/0 212 | S4 Et1/1 120 R Et0/0 213 | S3 Et0/3 120 R Et0/0 214 | S1 Et0/0 120 R Et0/0 215 | S5 Et0/2 120 R Et0/0 216 | 217 | Total entries displayed: 5 218 | ``` 219 | 220 | ```shell 221 | shell# snmpwalk -v 2c -c public 10.211.55.42 1.0.8802.1.1.2.1.3.7.1.3 222 | iso.0.8802.1.1.2.1.3.7.1.3.1 = STRING: "Et0/0" #邻接S1[正确的,11.7.3节 223 | S1 Et0/0 120 R Et0/0 224 | ][在图中没发现S1]的Et0/0 225 | iso.0.8802.1.1.2.1.3.7.1.3.2 = STRING: "Et0/1" 226 | iso.0.8802.1.1.2.1.3.7.1.3.3 = STRING: "Et0/2" #邻接S5的Et0/0 227 | iso.0.8802.1.1.2.1.3.7.1.3.4 = STRING: "Et0/3" #邻接S3的Et0/0 228 | iso.0.8802.1.1.2.1.3.7.1.3.5 = STRING: "Et1/0" #邻接R3的Et0/0 229 | iso.0.8802.1.1.2.1.3.7.1.3.6 = STRING: "Et1/1" #邻接S4的Et0/0 230 | iso.0.8802.1.1.2.1.3.7.1.3.7 = STRING: "Et1/2" #无邻居 231 | iso.0.8802.1.1.2.1.3.7.1.3.8 = STRING: "Et1/3" #无邻居 232 | ``` 233 | 234 | ```shell 235 | shell# snmpwalk -v 2c -c public 10.211.55.42 1.0.8802.1.1.2.1.4.1.1.7 236 | iso.0.8802.1.1.2.1.4.1.1.7.0.1.4 = STRING: "Et0/0" 237 | iso.0.8802.1.1.2.1.4.1.1.7.0.3.2 = STRING: "Et0/0" 238 | iso.0.8802.1.1.2.1.4.1.1.7.0.4.1 = STRING: "Et0/0" 239 | iso.0.8802.1.1.2.1.4.1.1.7.0.5.3 = STRING: "Et0/0" 240 | iso.0.8802.1.1.2.1.4.1.1.7.0.6.5 = STRING: "Et0/0" 241 | ``` 242 | 243 | ```shell 244 | shell# snmpwalk -v 2c -c public 10.211.55.42 1.0.8802.1.1.2.1.4.1.1.9 245 | iso.0.8802.1.1.2.1.4.1.1.9.0.1.4 = STRING: "S1" 246 | iso.0.8802.1.1.2.1.4.1.1.9.0.3.2 = STRING: "S5" 247 | iso.0.8802.1.1.2.1.4.1.1.9.0.4.1 = STRING: "S3" 248 | iso.0.8802.1.1.2.1.4.1.1.9.0.5.3 = STRING: "R3" 249 | iso.0.8802.1.1.2.1.4.1.1.9.0.6.5 = STRING: "S4" 250 | ``` 251 | 252 | # 506页 253 | 254 | 表11-3 SNMP LLDP OID 255 | 256 | | OID | 节 点 名 称 | 数 据 类 型 | 含  义 | 257 | | ------------------------- | ----------------------- | ------------------------- | ---------------------- | 258 | | 1.0.8802.1.1.2.1.4.1.1.4 | lldpRemChassisIdSubtype | LldpChassisIdSubtype | 远端设备ID子类型 | 259 | | 1.0.8802.1.1.2.1.4.1.1.5 | lldpRemChassisId | LldpChassisId | 远端设备ID | 260 | | 1.0.8802.1.1.2.1.4.1.1.6 | lldpRemPortIdSubtype | LldpPortIdSubtype | 远端设备的端口ID子类型 | 261 | | 1.0.8802.1.1.2.1.4.1.1.7 | lldpRemPortId | LldpPortId | 远端设备的端口索引ID | 262 | | 1.0.8802.1.1.2.1.4.1.1.8 | lldpRemPortDesc | SnmpAdminString | 远端设备的端口描述 | 263 | | 1.0.8802.1.1.2.1.4.1.1.9 | lldpRemSysName | SnmpAdminString | 远端设备名称 | 264 | | 1.0.8802.1.1.2.1.4.1.1.10 | lldpRemSysDesc | SnmpAdminString | 远端设备类型描述 | 265 | | 1.0.8802.1.1.2.1.4.1.1.11 | lldpRemSysCapSupported | LldpSystemCapabilitiesMap | 远端设备是否支持LLDP | 266 | | 1.0.8802.1.1.2.1.4.1.1.12 | lldpRemSysCapEnabled | LldpSystemCapabilitiesMap | 远端设备是否开启LLDP | 267 | 268 | # 507页 269 | 270 | https://share.zabbix.com/network_devices/l2-discovery-module-for-lldp 271 | 272 | 为方便读者获取,笔者将模板放到GitHub上,地址如下: 273 | 274 | https://github.com/zabbix-book/snmp_lldp 275 | 276 | 为Zabbix-Server增加支持SNMP LLDP的功能,配置如下: 277 | 278 | ````shell 279 | shell# mkdir -p /etc/zabbix/modules 280 | shell# wget https://raw.githubusercontent.com/zabbix-book/snmp_lldp/ master/modules/zabbix4.0/lldp_get.so 281 | shell# vim /etc/zabbix/zabbix_server.conf 282 | ####### LOADABLE MODULES ####### 283 | LoadModulePath=/etc/zabbix/modules 284 | LoadModule=lldp_get.so 285 | shell# systemctl restart zabbix-server 286 | ```` 287 | 288 | 从Zabbix-Web管理界面导入模板,地址如下: 289 | 290 | https://github.com/zabbix-book/snmp_lldp/blob/master/data/zabbix3.0/templates/zbx_export_templates.xml -------------------------------------------------------------------------------- /charter-12/Zabbix书籍V2-第12章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-12/Zabbix书籍V2-第12章-操作命令.pdf -------------------------------------------------------------------------------- /charter-12/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | # 514页 8 | 9 | ```php 10 | //代码位于src/frontends/php/include/func.inc.php中 11 | //performance [指性能数据吗?] //从Zabbix-Server中获取NVPS的数据 12 | if (array_key_exists('required performance', $server_status)) { 13 | $status['vps_total'] = 0; 14 | foreach ($server_status['required performance'] as $stats) { 15 | if ($stats['attributes']['proxyid'] == 0) { 16 | $status['vps_total'] += $stats['count']; 17 | } 18 | } 19 | } 20 | ``` 21 | 22 | ```c 23 | //代码位于src/libs/zbxdbcache/dbconfig.c的9675~9688行 24 | Double DCget_required_performance(void) 25 | { 26 | double nvps; 27 | WRLOCK_CACHE; 28 | dc_status_update(); 29 | nvps = config->status->required_performance; 30 | UNLOCK_CACHE; 31 | return nvps; 32 | } 33 | //以及位于src/libs/zbxdbcache/dbconfig.c的9481~9486行 34 | { 35 | config->status->required_performance += 1.0 / delay; 36 | if (NULL != dc_proxy) 37 | dc_proxy->required_performance += 1.0 / delay; 38 | } 39 | ``` 40 | 41 | ```sql 42 | mysql> SELECT SUM(1.0/i.delay) AS qps FROM items i,hosts h WHERE i.status= 'ITEM_STATUS_ACTIVE' AND i.hostid=h.hostid AND h.status='HOST_STATUS_MONITORED'; 43 | +----------+ 44 | | qps | 45 | +----------+ 46 | | 53.24389 | 47 | ``` 48 | 49 | # 515页 50 | 51 | ```shell 52 | StartPollers=160 53 | StartPollersUnreacheable=80 54 | StartTrappers=20 55 | StartPingers=100 56 | StartDiscoverers=120 57 | CacheSize=1024M 58 | StartDBSyncers=16 59 | HistoryCacheSize=1024M 60 | TrendCacheSize=1024M 61 | HistoryTextCacheSize=512M 62 | ``` 63 | 64 | ```shell 65 | ### Option: StartPreprocessors 66 | #       Number of pre-forked instances of preprocessing workers. 67 | #       The preprocessing manager process is automatically started when preprocessor worker is started. 68 | # 69 | # Mandatory: no 70 | # Range: 1-1000 71 | # Default: 72 | # StartPreprocessors=3 73 | ``` 74 | 75 | ```shell 76 | shell# systemctl restart zabbix-server 77 | ``` 78 | 79 | https://www.zabbix.org/wiki/How_to/configure_shared_memory 80 | 81 | # 518页 82 | 83 | ```shell 84 | shell# mkdir -p /etc/zabbix/modules 85 | shell# mkdir -p /usr/src/zabbix 86 | shell# cd /usr/src/zabbix 87 | shell# wget https://sourceforge.net/projects/zabbix/files/ZABBIX%20Latest% 20Stable/4.0.0/zabbix-4.0.0.tar.gz 88 | shell# tar xvf zabbix-4.0.0.tar.gz 89 | shell# cd zabbix-4.0.0 90 | shell# ./configure --enable-agent 91 | shell# mkdir src/modules/zabbix_module_stress 92 | shell# cd src/modules/zabbix_module_stress 93 | shell# wget https://raw.githubusercontent.com/monitoringartist/zabbix-server-stress-test/master/src/modules/zabbix_module_stress/zabbix_module_ stress.c 94 | shell# wget https://raw.githubusercontent.com/monitoringartist/zabbix-server-stress-test/master/src/modules/zabbix_module_stress/Makefile 95 | shell# make 96 | shell# ls -l 97 | -rw-r--r-- 1 root root 132 10月 9 14:07 Makefile 98 | -rw-r--r-- 1 root root 9107 10月 9 14:06 zabbix_module_stress.c 99 | -rwxr-xr-x 1 root root 12960 10月 9 14:07 zabbix_module_stress.so 100 | shell# cp zabbix_module_stress.so /etc/zabbix/modules 101 | ``` 102 | 103 | ```shell 104 | shell# vim /etc/zabbix/zabbix_agentd.conf 105 | ### Option: LoadModulePath 106 | # Full path to location of agent modules. 107 | # Default depends on compilation options. 108 | # 109 | # Mandatory: no 110 | # Default: 111 | # LoadModulePath=${libdir}/modules 112 | LoadModulePath=/etc/zabbix/modules #配置模块加载的路径 113 | 114 | ### Option: LoadModule 115 | # Module to load at agent startup. Modules are used to extend functionality of the agent. 116 | # Format: LoadModule= 117 | # The modules must be located in directory specified by LoadModulePath. 118 | # It is allowed to include multiple LoadModule parameters. 119 | # 120 | # Mandatory: no 121 | # Default: 122 | # LoadModule= 123 | LoadModule=zabbix_module_stress.so #加载压力测试模块 124 | ``` 125 | 126 | ```shell 127 | shell# systemctl restart zabbix-agent 128 | shell# zabbix_get -s 127.0.0.1 -k stress.ping[1] 129 | 1 130 | ``` 131 | 132 | # 526页 133 | 134 | ```shell 135 | shell# cat /etc/zabbix/zabbix_server.conf 136 | ############ GENERAL PARAMETERS ################# 137 | ListenPort=10051 #监控端口,默认值为10051,范围是1024~32767.源码文件src/zabbix_server/server.c中硬编码实现,可修改代码调整。 138 | SourceIP= #当Zabbix-Server有两个IP地址时,需要定义选择IP地址作为出口,如果使用了VIP,则需要配置SourceIP为VIP的地址 139 | LogFile=/var/log/zabbix/zabbix_server.log #日志文件的保存路径 140 | LogFileSize=0 #每个日志文件最大的容量。当设置为0时,即关闭日志轮转自动切割的功能。单位是MB 141 | # DebugLevel=3 #默认值为3,共有6个级别,从0到5 142 | # 0 — 基本信息,Zabbix进程的启停信息 143 | # 1 — 严重致命的软件运行错误信息 144 | # 2 — 错误信息 145 | # 3 — 警告信息 146 | # 4 — 调试信息,输出大量的日志 147 | # 5 — 开发调试,输出大量的详细日志 148 | PidFile=/var/run/zabbix/zabbix_server.pid #Pid文件路径 149 | SocketDir=/var/run/zabbix #IPC Socket的文件夹路径 150 | DBHost=localhost #DB的主机名,或者IP地址 151 | DBName=zabbix #DB的名称 152 | # DBSchema= #仅在数据库IBM DB2和PostgreSQL中使用 153 | DBUser=zabbix #DB的用户名 154 | DBPassword=zabbix #DB的密码 155 | DBSocket= #DB的Socket路径,一般不需要设置,如DBHost为localhost,则需要配置 156 | DBPort= #DB的端口 157 | # HistoryStorageURL= #当使用Elasticsearch时配置 158 | # HistoryStorageTypes=uint,dbl,str,log,text #将哪些数据类型存储到Elasticsearch上 159 | # HistoryStorageDateIndex=0 #是否开启按日期索引功能,0表示关闭,1表示开启 160 | # ExportDir= #将实时监控数据输出到JSON文件,此处填写文件夹的路径 161 | # ExportFileSize=1G #导出的JSON文件单个最大值 162 | ############ ADVANCED PARAMETERS ################ 163 | # StartPollers=5 #被动模式进程开启的个数,通常一个进程可以获取10~20台主机的监控数据,最大值为1000,最小值为0,默认值为5,可以在硬件配置足够好的情况下,一次将此值调整为1000 164 | # StartIPMIPollers=0 #IPMI进程开启的个数,默认值为0,表示关闭IPMI,取值范围为0~1000 165 | # StartPreprocessors=3 #预处理进程的个数,默认值为3,需要根据实际情况调整,建议设置为100左右,取值范围为0~1000 166 | # StartPollersUnreachable=1 #当主机不可达时,会再次请求,使用此进程,建议设置为主机数量的3%,即100台主机设置为3。取值范围为0~1000 167 | # StartTrappers=5 #Trapper进程的数量,使用zabbix_sender命令发送的数据,将由此进程进行处理。默认值为5,如果采用Trapper进程的数量较多,则应增大此值,取值范围为0~1000 168 | # StartPingers=1 #ICMP ping的进程个数,默认值为1,取值范围为0~1000 169 | # StartDiscoverers=1 #自动发现的进程个数,取值范围为0~250 170 | # StartHTTPPollers=1 #HTTP监控进程的个数,默认值为1,取值范围为0~1000 171 | # StartTimers=1 #与时间有关的触发器函数和维护时间的进程,取值范围为1~1000 172 | # StartEscalators=1 #告警升级的进程个数,取值范围为0~100 173 | # StartAlerters=3 #告警的进程个数,取值范围为0~100 174 | # JavaGateway=127.0.0.1 #JavaGateway的IP地址,仅支持一个参数 175 | # JavaGatewayPort=10052 #JavaGateway的端口 176 | # StartJavaPollers=1 #JavaGateway的处理进程个数,取值范围为0~1000 177 | # StartVMwareCollectors=0 #VMware监控的进程个数,取值范围为0~200 178 | # VMwareFrequency=60 #Zabbix-Server每隔多久从VMware获取一次数据,取值范围为10~86400 179 | # VMwarePerfFrequency=60 #Zabbix-Server每隔多久从VMware获取一次性能数据,取值范围为10~86400 180 | # VMwareCacheSize=8M #存储VMware监控数据的内存大小,取值范围为256KB~2GB 181 | # VMwareTimeout=10 #连接到VMware服务的超时时间,取值范围为1~300 182 | SNMPTrapperFile=/var/log/snmptrap/snmptrap.log #SNMP Trapper的日志文件路径 183 | # StartSNMPTrapper=0 #是否开启SNMP Trapper,1表示开启,0表示关闭 184 | # ListenIP=127.0.0.1 #监听的IP地址,如果为空,则所有网卡都被允许接收用户端的数据[不通顺] 185 | # HousekeepingFrequency=1 #删除数据的频率,单位为小时,取值范围为0~24 186 | # MaxHousekeeperDelete=5000 #每次最大删除数据条数,0表示删除全部,取值范围 187 | 为0~1 000 000 188 | # CacheSize=8M #配置缓存的大小,用于存储Host、Item和Trigger等的数据,这里一般不用设置得太大,一般环境下200MB足够,取值范围为128KB~8GB 189 | # CacheUpdateFrequency=60 #缓存更新的频率,单位为秒,取值范围为1~3600 190 | # StartDBSyncers=4 #数据库同步进程,也叫历史数据同步进程,取值范围为1~100。功能是将数据从缓存同步到数据库,负责触发器的计算,处理趋势数据,更新Item状态,存储告警事件结果。1个DBSyncer可以支持1000个NVPS,4个DBSyncer可以支持4000的NVPS,[请顺一下这句话]前提是数据库能够及时同步。注意,这个值不能设置得太大,太大会造成数据库压力过大,而导致整体处理速度下降 191 | # HistoryCacheSize=16M #历史数据的缓存大小,取值范围为128KB~2GB,可以一次设置到最大值2G 192 | # HistoryIndexCacheSize=4M #历史数据缓存的索引大小,取值范围为128KB~2GB。一个Item需要分配100B的空间,2000万个的Item需要分配大约2GB的内存空间,计算方式为:(100.00B/ 1024KB/ 1024MB)*2000 0000=1907MB。如果读者的Item为100万个,则(100.00/1024/1024)*100 0000[对吗?]=[正确] 95MB。因此这个值可以不用计算,直接将其设置为256MB,基本可以满足200~300万个Item数据的存储需求。默认值为4MB,只能支撑4万个Item。如果此值过小,则会导致zabbix_server进程退出运行 193 | # TrendCacheSize=4M #趋势数据的缓存大小,取值范围为128KB~2GB,和历史数据的缓存大小一样,可以一次设置到最大值2GB 194 | # ValueCacheSize=8M #Item的历史数据,取值范围为128KB~64GB,0表示关闭。这个值可以根据实际情况而定,但建议将其设置得大些,在2GB以上。一般可以设置存取监控指标一天的数据容量,比如数据库一天更新量有5GB,则可以将此值设置为5GB。此值设置得越大,Zabbix的性能越好。如按照时间范围查询监控指标数据,将优先从内存取值,如果内存中无此时间范围的数据,再从数据库查询获取,这样可以有效减少数据库的访问 195 | # 当缓存利用率较高时,会采取删除策略进行删除释放——删除最后一天无访问的数据、删除命中率低的数据,不再添加新的数据到缓存中 196 | # 当内存容量小于设置的数值时,将每5分钟写入一次警告信息到日志 197 | # Timeout=3 #超时时间,对Agent、SNMP设置和扩展检测有效,取值范围为1~30s 198 | # TrapperTimeout=300 #处理Trapper数据的超时时间[不通顺],取值范围为1~300s 199 | # UnreachablePeriod=45 #多久检测一次不可达主机,取值范围为1~3600s 200 | # UnavailableDelay=60 #当主机状态不可用时,检测可达的频率,取值范围为1~3600s 201 | # UnreachableDelay=15 #当主机不可达时,检测可达的频率,取值范围为1~3600s 202 | AlertScriptsPath=/usr/lib/zabbix/alertscripts #告警脚本路径 203 | ExternalScripts=/usr/lib/zabbix/externalscripts #扩展脚本路径 204 | # FpingLocation=/usr/sbin/fping #fping二进制文件的路径 205 | # Fping6Location=/usr/sbin/fping6 #fping6二进制文件的路径 206 | # SSHKeyLocation= #SSH密钥的路径 207 | LogSlowQueries=3000 #慢查询的时间,取值范围为1~3 600 000ns 208 | # TmpDir=/tmp #临时文件的路径 209 | # StartProxyPollers=1 #Proxy进程的个数,用于被动模式下,取值范围为0~250 210 | # ProxyConfigFrequency=3600 #将Zabbix-Server端的配置数据同步到Proxy端的周期[不通顺],取值范围为1~3600*24*7 211 | # ProxyDataFrequency=1 #多久从Zabbix-Proxy获取一次监控的历史数据,取值范围为1~3600s 212 | # AllowRoot=0 #是否使用root启动,0表示不允许,1表示使用root启动进程 213 | # User=zabbix #Zabbix进程运行的用户 214 | # 子配置文件路径 215 | # Include=/usr/local/etc/zabbix_server.general.conf 216 | # Include=/usr/local/etc/zabbix_server.conf.d/ 217 | # Include=/usr/local/etc/zabbix_server.conf.d/*.conf 218 | # SSLCertLocation=${datadir}/zabbix/ssl/certs #SSL证书路径 219 | # SSLKeyLocation=${datadir}/zabbix/ssl/keys #SSL证书key路径 220 | # SSLCALocation= #SSL证书CA路径 221 | 222 | ####### LOADABLE MODULES ####### 223 | # LoadModulePath=${libdir}/modules #动态模块路径 224 | # LoadModule= #需要加载的动态模块 module.so,如果有多个,则写多行 225 | ......后续的证书认证配置省略...... 226 | #需要注意,以上配置中,凡是增大进程数量的配置,都会增加数据库的连接数,如数据库的默认连接数过小,则会造成Zabbix-Server启动的问题。 227 | ``` 228 | 229 | -------------------------------------------------------------------------------- /charter-13/Zabbix书籍V2-第13章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-13/Zabbix书籍V2-第13章-操作命令.pdf -------------------------------------------------------------------------------- /charter-13/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | # 531页 8 | 9 | ```json 10 | {"method": "getid", "params": ["arg"], "id": 1} 11 | ``` 12 | 13 | ```json 14 | { 15 | "result": "id is 000", 16 | "error": null, 17 | "id": 1 18 | } 19 | ``` 20 | 21 | 表13-1 Zabbix API支持的数据类型 22 | 23 | | 类  型 | 说  明 | 24 | | --------- | ------------------------------------------------------------ | 25 | | bool | 布尔值为true或者false | 26 | | flag | 当该值不等于空或者false时,被认为是true | 27 | | integer | 整数 | 28 | | float | 浮点数 | 29 | | string | 文本字符串 | 30 | | timestamp | UNIX 时间戳 | 31 | | array | 数组 | 32 | | object | 关联数组 | 33 | | query | 可以是一个数值,也可以是部分参数· extend:返回所有的对象值· count:返回值的数量 | 34 | 35 | #532页 36 | 37 | 表13-2 查询操作(get方法)支持的参数 38 | 39 | | 参  数 | 类  型 | 描  述 | 40 | | ---------------------- | ------------ | ------------------------------------------------------------ | 41 | | countOutput | flag | 返回结果的个数,而非实际的数据 | 42 | | editable | boolean | 如果设置为true,用户可对返回的对象进行写操作。默认值为false | 43 | | excludeSearch | flag | 返回不匹配给定参数的结果 | 44 | | filter | object | 返回过滤后的结果,参数的值可以为一个数组或者单个值,text字段不能使用此参数 | 45 | | limit | integer | 限制返回结果的数量 | 46 | | nodeids | string/array | 返回给定节点的对象信息 | 47 | | output | query | 返回对象的属性。默认值为extend | 48 | | preservekeys | flag | 返回以ID为键的数组 | 49 | | search | object | 搜索匹配的字符串,仅用于字符和文本字段 | 50 | | searchByAny | boolean | 如果设置为true,则返回 filter 或search字段中所有的值。默认值为false | 51 | | searchWildcardsEnabled | boolean | 如果设置为true,允许使用“*”作为搜索参数的通配符。默认值为false | 52 | | sortfield | string/array | 对给定的参数属性进行排序 | 53 | | sortorder | string/array | 排序。ASC为升序排列;DESC为降序排列 | 54 | | startSearch | flag | 搜索以某个参数开始的结果 | 55 | 56 | # 533页 57 | 58 | https://www.zabbix.com/documentation/4.0/manual/api/reference/host/get 59 | 60 | ```json 61 | { 62 | "jsonrpc": "2.0", 63 | "method": "host.get", 64 | "params": { 65 | "filter": { 66 | "host": [ 67 | "Zabbix server", 68 | "Linux server" 69 | ] 70 | } 71 | }, 72 | "auth": "038e1d7b1735c6a5436ee9eae095879e", 73 | "id": 1 74 | } 75 | ``` 76 | 77 | # 534页 78 | 79 | ```shell 80 | shell# curl -X POST \ 81 | -H 'Content-Type:application/json' \ 82 | -d '{"jsonrpc": "2.0", 83 | "method":"user.login", 84 | "params":{"user":"Admin", 85 | "password":"zabbix"}, 86 | "auth": null, 87 | "id":0 88 | }' \ 89 | http://127.0.0.1/zabbix/api_jsonrpc.php 90 | ``` 91 | 92 | ```json 93 | 得到的结果如下: 94 | { 95 | "jsonrpc":"2.0", 96 | "result":"b545519b2e2f7b08e1a63b360f24b533", 97 | "id":0 98 | } 99 | ``` 100 | 101 | ```sql 102 | mysql> select * from sessions where sessionid="b545519b2e2f7b08e1a63b360f24b533"; 103 | +----------------------------------+--------+------------+--------+ 104 | | sessionid | userid | lastaccess | status | 105 | +----------------------------------+--------+------------+--------+ 106 | | b545519b2e2f7b08e1a63b360f24b533 | 1 | 1539053137 | 0 | 107 | +----------------------------------+--------+------------+--------+ 108 | ``` 109 | 110 | ```shell 111 | shell# curl -X POST \ 112 | -H 'Content-Type: application/json' \ 113 | -d '{"jsonrpc":"2.0", 114 | "method":"host.get", 115 | "params":{ 116 | "output":"extend", 117 | "filter":{"host":""} 118 | }, 119 | "auth":"b545519b2e2f7b08e1a63b360f24b533", 120 | "id":1 121 | }' \ 122 | http://127.0.0.1/zabbix/api_jsonrpc.php 123 | ``` 124 | 125 | # 535页 126 | 127 | ```python 128 | { 129 | "jsonrpc":"2.0", 130 | "result":[ 131 | { 132 | "maintenances":[], 133 | "hostid":"10084", 134 | "proxy_hostid":"0", 135 | "host":"Zabbix server", 136 | "status":"0", 137 | "disable_until":"0", 138 | "error":"", 139 | "available":"1", 140 | "errors_from":"0", 141 | "lastaccess":"0", 142 | "ipmi_authtype":"-1", 143 | "ipmi_privilege":"2", 144 | "ipmi_username":"", 145 | "ipmi_password":"", 146 | "ipmi_disable_until":"0", 147 | "ipmi_available":"0", 148 | "snmp_disable_until":"0", 149 | "snmp_available":"0", 150 | "maintenanceid":"0", 151 | "maintenance_status":"0", 152 | "maintenance_type":"0", 153 | "maintenance_from":"0", 154 | "ipmi_errors_from":"0", 155 | "snmp_errors_from":"0", 156 | "ipmi_error":"", 157 | "snmp_error":"", 158 | "jmx_disable_until":"0", 159 | "jmx_available":"0", 160 | "jmx_errors_from":"0", 161 | "jmx_error":"", 162 | "name":"Zabbix server" 163 | }, 164 | ......省略部分输出...... 165 | ], 166 | "id":1 167 | } 168 | ``` 169 | 170 | # 536页 171 | 172 | ```shell 173 | shell# curl -i -X POST -d ' 174 | {"jsonrpc": "2.0", 175 | "method":"user.login", 176 | "params":{ 177 | "user":"Admin", 178 | "password":"zabbix" 179 | }, 180 | "auth": null, 181 | "id":0 182 | }' http://127.0.0.1/zabbix/api_jsonrpc.php 183 | #可以看到HTTP返回了412错误 184 | HTTP/1.0 412 Precondition Failed 185 | Date: Tue, 09 Oct 2018 03:07:17 GMT 186 | Server: Apache/2.4.6 (CentOS) PHP/5.4.16 187 | X-Powered-By: PHP/5.4.16 188 | Access-Control-Allow-Origin: * 189 | Access-Control-Allow-Headers: Content-Type 190 | Access-Control-Allow-Methods: POST 191 | Access-Control-Max-Age: 1000 192 | Content-Length: 0 193 | Connection: close 194 | Content-Type: text/html; charset=UTF-8 195 | ``` 196 | 197 | ```json 198 | 认证成功的提示内容如下: 199 | 200 | { 201 | "jsonrpc":"2.0", 202 | "result":"b545519b2e2f7b08e1a63b360f24b533", 203 | "id":0 204 | } 205 | ``` 206 | 207 | ```json 208 | 认证失败的提示内容如下: 209 | 210 | { 211 | "jsonrpc":"2.0", 212 | "error": 213 | { 214 | "code":-32602, 215 | "message":"Invalid params.", 216 | "data":"Login name or password is incorrect." 217 | }, 218 | "id":0 219 | } 220 | ``` 221 | 222 | # 537页 223 | 224 | https://github.com/zabbix-book/zabbix_api_example/blob/master/zabbix_api_host_get.py 225 | 226 | ```python 227 | #!/usr/bin/env python 228 | 2. #coding=utf-8 229 | 3. 230 | 4. #导入模块,urllib2是一个模拟浏览器HTTP方法的模块 231 | 5. import json 232 | 6. import urllib2 233 | 7. import sys 234 | 8. from urllib2 import Request, urlopen, URLError, HTTPError 235 | 9. 236 | 10. #url和url头部信息 [要写成中文注释吗?下同] 237 | 11. #Zabbix的API 地址、用户名、密码,这里修改为实际的参数 238 | 12. zabbix_url="http://127.0.0.1/zabbix/api_jsonrpc.php" 239 | 13. zabbix_header = {"Content-Type":"application/json"} 240 | 14. zabbix_user = "Admin" 241 | 15. zabbix_pass = "zabbix" 242 | 16. auth_code = "" 243 | 17. 244 | 18. #用户和密码 245 | 19. #用户认证信息,最终目的是得到一个sessionid 246 | 20. #下面生成一个JSON格式的数据,用户名和密码 247 | 21. auth_data = json.dumps( 248 | 22. { 249 | 23. "jsonrpc":"2.0", 250 | 24. "method":"user.login", 251 | 25. "params": 252 | 26. { 253 | 27. "user":zabbix_user, 254 | 28. "password":zabbix_pass 255 | 29. }, 256 | 30. "id":0 257 | 31. }) 258 | 32. 259 | 33. #构造请求数据 260 | 34. request = urllib2.Request(zabbix_url,auth_data) 261 | 35. for key in zabbix_header: 262 | 36. request.add_header(key,zabbix_header[key]) 263 | 37. 264 | 265 | 38. #认证和获取sessionid 266 | 39. try: 267 | 40. result = urllib2.urlopen(request) 268 | 41. #对认证出错的处理 269 | 42. except HTTPError, e: 270 | 43. print 'The server couldn\'t fulfill the request, Error code: ', e.code 271 | 44. except URLError, e: 272 | 45. print 'We failed to reach a server.Reason: ', e.reason 273 | 46. else: 274 | 47. response=json.loads(result.read()) 275 | 48. result.close() 276 | 49. ''' 277 | 50. #如果访问成功或者失败,则会显示如下数据 278 | 51. sucess result: 279 | 52. {"jsonrpc":"2.0", 280 | 53. "result":"0d225d8d2a058625f814f3a0749cd218", 281 | 54. #result后面的值是sessionid,每次访问都会发生变化 282 | 55. "id":0} 283 | 56. error result: 284 | 57. {'code': -32602, 285 | 58. 'data': 'Login name or password is incorrect.', 286 | 59. 'message': 'Invalid params.'} 287 | 60. ''' 288 | 61. #判断sessionid是否在返回的数据中 289 | 62. if 'result' in response: 290 | 63. auth_code=response['result'] 291 | 64. else: 292 | 65. print response['error']['data'] 293 | 66. 294 | 67. #请求数据 295 | 68. json_data={ 296 | 69. "method":"host.get", 297 | 70. "params":{ 298 | 71. "output": "extend", 299 | 72. } 300 | 73. } 301 | 74. json_base={ 302 | 75. "jsonrpc":"2.0", 303 | 76. "auth":auth_code, 304 | 77. "id":1 305 | 78. } 306 | 79. json_data.update(json_base) 307 | 80. #用得到的sessionid来验证,获取主机信息(用http.get方法) 308 | 81. if len(auth_code) == 0: 309 | 82. sys.exit(1) 310 | 83. else: 311 | 84. get_host_data = json.dumps(json_data) 312 | 85. #发送请求数据 313 | 86. request = urllib2.Request(zabbix_url,get_host_data) 314 | 87. for key in zabbix_header: 315 | 88. request.add_header(key,zabbix_header[key]) 316 | 89. 317 | 90. #获取主机列表数据 318 | 91. try: 319 | 92. result = urllib2.urlopen(request) 320 | 93. except URLError as e: 321 | 94. if hasattr(e, 'reason'): 322 | 95. print 'We failed to reach a server.' 323 | 96. print 'Reason: ', e.reason 324 | 97. elif hasattr(e, 'code'): 325 | 98. print 'The server could not fulfill the request.' 326 | 99. print 'Error code: ', e.code 327 | 100. else: 328 | 101. response = json.loads(result.read()) 329 | 102. result.close() 330 | 103. 331 | 104. #将所有的主机信息显示出来 332 | 105. print response 333 | 106. #显示主机的个数 334 | 107. print "Number Of Hosts: ", len(response['result']) 335 | ``` 336 | 337 | 338 | 339 | # 540页 340 | 341 | ```json 342 | shell# python zabbix_api_host_get.py 343 | { 344 | "available":"1", 345 | "maintenance_type":"0", 346 | "snmp_errors_from":"0", 347 | "hostid":"10084", 348 | "description":"", 349 | "ipmi_errors_from":"0", 350 | "jmx_errors_from":"0", 351 | "error":"", 352 | "tls_accept":"1", 353 | ......省略部分输出...... 354 | "jmx_error":"", 355 | "jmx_available":"0", 356 | "maintenanceid":"0", 357 | "proxy_address":"", 358 | "snmp_available":"0", 359 | "flags":"0", 360 | "maintenance_from":"0", 361 | "ipmi_error":"", 362 | "errors_from":"0", 363 | "tls_subject":"" 364 | } 365 | ``` 366 | 367 | https://www.zabbix.com/documentation/4.0/manual/api/reference/host/create 368 | 369 | ```json 370 | 官方文档中列出了host.create的用法,如下所示。 371 | 372 | {' 373 | auth': '038e1d7b1735c6a5436ee9eae095879e', 374 | 'id': 1, 375 | 'jsonrpc': '2.0', 376 | 'method': 'host.create', 377 | 'params': {'groups': [{'groupid': '50'}], 378 | 'host': 'Linux server[是否是:servers]'[此处需要复数], 379 | 'interfaces': [{'dns': '', 380 | 'ip': '192.168.3.1', 381 | 'main': 1, 382 | 'port': '10050', 383 | 'type': 1, 384 | 'useip': 1}], 385 | 'inventory': {'macaddress_a': '01234', 'macaddress_b': '56768'}, 386 | 'templates': [{'templateid': '20045'}]} 387 | } 388 | ``` 389 | 390 | # 541页 391 | 392 | ```shell 393 | mysql> select * from hosts where host="Template OS Linux"\G; 394 | *************************** 1. row *************************** 395 | hostid: 10001 396 | proxy_hostid: NULL 397 | host: Template OS Linux 398 | status: 3 399 | disable_until: 0 400 | ......省略部分输出...... 401 | tls_psk: 402 | proxy_address: 403 | auto_compress: 1 404 | 继续查询主机组,查询到Linux servers的groupid为2。 405 | 406 | mysql> select * from hstgrp; 407 | +---------+-----------------------------+----------+-------+ 408 | | groupid | name | internal | flags | 409 | +---------+-----------------------------+----------+-------+ 410 | | 1 | Templates | 0 | 0 | 411 | | 2 | Linux servers | 0 | 0 | 412 | | 4 | Zabbix servers | 0 | 0 | 413 | ......省略部分输出...... 414 | | 24 | log | 0 | 0 | 415 | +---------+-----------------------------+----------+-------+ 416 | ``` 417 | 418 | https://github.com/zabbix-book/zabbix_api_example/blob/master/zabbix_api_host_create.py 419 | 420 | # 542页 421 | 422 | ```json 423 | 修改代码中的参数值,替换为实际参数值,如下所示。 424 | 425 | shell# vim zabbix_api_host_create.py 426 | { 427 | 'method': 'host.create', 428 | 'params': {'groups': [{'groupid': '2'}], 429 | 'host': 'Web Linux server', 430 | 'interfaces': [{'dns': '', 431 | 'ip': '192.168.8.1', 432 | 'main': 1, 433 | 'port': '10050', 434 | 'type': 1, 435 | 'useip': 1}], 436 | 'inventory': {'macaddress_a': '01234', 'macaddress_b': '56768'}, 437 | 'templates': [{'templateid': '10001'}]} 438 | } 439 | 运行代码,结果显示主机创建成功,hostid为10284(后续会用到)。 440 | 441 | shell# python zabbix_api_host_create.py 442 | { 443 | 'jsonrpc': '2.0', 444 | 'result': {'hostids[是否多了一个s][正确]': ['10284']}, 445 | 'id': 1 446 | } 447 | ``` 448 | 449 | # 543页 450 | 451 | https://www.zabbix.com/documentation/4.0/manual/api/reference/host/delete 452 | 453 | ```json 454 | { 455 | 'jsonrpc': '2.0', 456 | 'method': 'host.delete', 457 | 'params': [ 458 | '13', 459 | '32' 460 | ], 461 | 'auth': '038e1d7b1735c6a5436ee9eae095879e', 462 | 'id': 1 463 | } 464 | ``` 465 | 466 | https://github.com/zabbix-book/zabbix_api_example/blob/master/zabbix_api_host_delete.py 467 | 468 | ```json 469 | shell# vim zabbix_api_host_delete.py 470 | json_data={ 471 | "method":"host.delete", 472 | "params":['10284'] 473 | } 474 | 运行脚本,如下所示。 475 | 476 | shell# python zabbix_api_host_delete.py 477 | { 478 | u"jsonrpc": "2.0", 479 | u"result": { 480 | u"hostids": [ 481 | u"10284" 482 | ] 483 | }, 484 | u"id": 1 485 | } 486 | ``` 487 | 488 | # 544页 489 | 490 | https://www.zabbix.com/documentation/4.0/manual/api 491 | 492 | https://zabbix.org/wiki/Docs/api/libraries 493 | 494 | ```shell 495 | shell# pip install pyzabbix #如图13-3所示 496 | ``` 497 | 498 | # 545页 499 | 500 | ```python 501 | import logging 502 | import requests 503 | import json 504 | 505 | class _NullHandler(logging.Handler): 506 | def emit(self, record): 507 | pass 508 | 509 | logger = logging.getLogger(__name__) 510 | logger.addHandler(_NullHandler()) 511 | 512 | class ZabbixAPIException(Exception): 513 | pass 514 | 515 | class ZabbixAPI(object): 516 | def __init__(self,server='http://localhost/zabbix',session=None,use_ authenticate=False,timeout=None): #构造URL 517 | if session: 518 | self.session = session 519 | else: 520 | self.session = requests.Session() 521 | 522 | self.session.headers.update({'Content-Type': 'application/json-rpc','User-Agent': 'python/pyzabbix','Cache-Control': 'no-cache'}) 523 | 524 | self.use_authenticate = use_authenticate 525 | self.auth = '' 526 | self.id = 0 527 | self.timeout = timeout 528 | self.url = server + '/api_jsonrpc.php' 529 | logger.info("JSON-RPC Server Endpoint: %s", self.url) 530 | 531 | def login(self, user='', password=''): #输入用户名和密码 532 | self.auth = '' 533 | if self.use_authenticate: 534 | self.auth = self.user.authenticate(user=user, password=password) 535 | else: 536 | self.auth = self.user.login(user=user, password=password) 537 | 538 | def confimport(self, confformat='', source='', rules=''): 539 | return self.do_request(method="configuration.import",params= {"format": confformat, "source": source, "rules": rules})['result'] 540 | 541 | def api_version(self): 542 | return self.apiinfo.version() 543 | 544 | def do_request(self, method, params=None): #使用API方法 545 | request_json = {'jsonrpc': '2.0','method': method,'params': params or {},'id': self.id,} 546 | 547 | if self.auth and method != 'apiinfo.version': 548 | request_json['auth'] = self.auth 549 | 550 | logger.debug("Sending: %s", json.dumps(request_json,indent=4, separators=(',', ': '))) 551 | response = self.session.post(self.url,data=json.dumps(request_json), timeout=self.timeout) 552 | logger.debug("Response Code: %s", str(response.status_code)) 553 | 554 | response.raise_for_status() 555 | 556 | if not len(response.text): 557 | raise ZabbixAPIException("Received empty response") 558 | 559 | try: 560 | response_json = json.loads(response.text) 561 | except ValueError: 562 | raise ZabbixAPIException( "Unable to parse json: %s" % response.text) 563 | logger.debug("Response Body: %s", json.dumps(response_json, indent=4,separators=(',', ': '))) 564 | 565 | self.id += 1 566 | 567 | if 'error' in response_json: # some exception 568 | if 'data' not in response_json['error']: 569 | response_json['error']['data'] = "No data" 570 | msg = u"Error {code}: {message}, {data}".format( 571 | code=response_json['error']['code'], 572 | message=response_json['error']['message'], 573 | data=response_json['error']['data'] 574 | ) 575 | raise ZabbixAPIException(msg,response_json['error']['code']) 576 | return response_json 577 | 578 | def __getattr__(self, attr): 579 | """Dynamically create an object class (ie: host)""" 580 | return ZabbixAPIObjectClass(attr, self) 581 | 582 | class ZabbixAPIObjectClass(object): 583 | def __init__(self, name, parent): 584 | self.name = name 585 | self.parent = parent 586 | 587 | def __getattr__(self, attr): 588 | """Dynamically create a method (ie: get)""" 589 | def fn(*args, **kwargs): 590 | if args and kwargs: 591 | raise TypeError("Found both args and kwargs") 592 | #将zapi.host.get(params)解析为do_request函数中的{'jsonrpc': '2.0','method': 'host.get','params': params or {},'id': self.id,} 593 | return self.parent.do_request( 594 | '{0}.{1}'.format(self.name, attr), 595 | args or kwargs 596 | )['result'] 597 | return fn 598 | 更多的例子,参见https://github.com/lukecyca/pyzabbix/tree/master/example。 599 | ``` 600 | 601 | # 547页 602 | 603 | https://github.com/zabbix-book/zbx_tool 604 | 605 | ```shell 606 | shell# zbx_tool 607 | usage: zbx_tool [options] 608 | 609 | Zabbix Automation Tools 610 | 611 | optional arguments: 612 | -h, --help show this help message 613 | [代码输出的文字,无需翻译] 显示帮助信息 614 | -H [LISTHOST], --host [LISTHOST] 615 | 查询主机 616 | -G [LISTGROUP], --group [LISTGROUP] 617 | 查询主机组 618 | -T [LISTTEMP], --template [LISTTEMP] 619 | 查询模板信息 620 | -A ADDGROUP, --add-group ADDGROUP 621 | 添加主机组 622 | -C 10.10.10.1 HostName group01,group02 Template01,Template02 ["agent", "SNMP", "IPMI", "JMX"] "MACROS1_NAME,MACROS1_VALUE;MACROS2_NAME,MACROS2_VALUE", --add-host 10.10.10.1 HostName group01,group02 Template01,Template02 ["agent", "SNMP", "IPMI", "JMX"] "MACROS1_NAME,MACROS1_VALUE;MACROS2_NAME,MACROS2_VALUE" 623 | 添加主机,多个主机或模板之间使用分号分隔 624 | -d 10.10.10.1, --disable 10.10.10.1 625 | 禁用主机 626 | -D HostName [HostName ...], --delete HostName [HostName ...][是否删除?下同] 627 | 删除主机,多个主机之间用分号分隔 628 | -SH hostname screename hsize, --add-host-all hostname screename hsize 629 | 将一个主机的所有图形添加到screen 630 | -SG groupname graphname screenname hsize, --add-group-graph groupname graphname screenname hsize 631 | 将一个组的指定图形添加到screen 632 | -SN graphname screenname hsize, --add-graph-search graphname screenname hsize 633 | 将指定的图形添加到screen 634 | -v, --version show program's version number[中文意思?] 635 | 显示查询版本 636 | ``` 637 | 638 | 639 | 640 | -------------------------------------------------------------------------------- /charter-14/Zabbix书籍V2-第14章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-14/Zabbix书籍V2-第14章-操作命令.pdf -------------------------------------------------------------------------------- /charter-14/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | #549页 8 | 9 | ```shell 10 | shell# yum -y install gcc gcc-c++ autoconf httpd php mariadb-server php-mysql httpd-manual mod_ssl mod_perl mod_auth_mysql php-gd php-xml php-mbstring php-ldap php-pear php-xmlrpc php-bcmath mysql-connector-odbc mysql-devel libdbi-dbd-mysql net-snmp-devel curl-devel unixODBC-devel OpenIPMI-devel java-devel pcre-devel libxml2-devel openldap-devel libevent-devel openssl-devel libssh2-devel 11 | ``` 12 | 13 | ```shell 14 | shell# wget https://sourceforge.net/projects/zabbix/files/ZABBIX%20Latest%20Stable/ 4.0.0/zabbix-4.0.0.tar.gz #读者可以下载最新版本,写作本书时最新版本为Zabbix 4.0.0 15 | ``` 16 | 17 | ```shell 18 | shell# groupadd zabbix -g 201 #添加zabbix用户组 19 | shell# useradd -g zabbix -u 201 -m zabbix #增加zabbix用户 20 | shell# tar xvf zabbix-4.0.0.tar.gz #解压缩包 21 | shell# cd zabbix-4.0.0 #进入源码目录 22 | shell# ./configure --prefix=/usr --exec-prefix=/usr --bindir=/usr/bin --sbindir=/usr/sbin --sysconfdir=/etc --datadir=/usr/share --includedir=/usr/ include --libdir=/usr/lib64 --libexecdir=/usr/libexec --localstatedir=/var --sharedstatedir=/var/lib --mandir=/usr/share/man --infodir=/usr/share/info --sysconfdir=/etc/zabbix --libdir=/usr/lib64/zabbix --enable-server --enable- agent --enable-proxy --enable-ipv6 --enable-java --with-net-snmp --with-ldap --with-libcurl --with-openipmi --with-unixodbc --with-ssh2 --with-libxml2 --with-libevent --with-libpcre --with-openssl --with-mysql=/usr/bin/mysql_config 23 | #如果读者只需安装Zabbix-Server端,则开启--enable-server参数即可,其他参数可不用选。 24 | #这里是为了后面的各项功能都可以使用,所以开启了非常多的参数 25 | #如果缺少相应的软件包,在配置过程中会给出提示,使用yum安装所缺少的软件包即可顺利通过安装 26 | shell# make 27 | shell# make install 28 | ``` 29 | 30 | # 550页 31 | 32 | ```shell 33 | 将数据库添加到开机启动项中并启动服务,命令如下: 34 | 35 | shell# systemctl enable mariadb #添加到开机启动项中 36 | shell# systemctl start mariadb #启动服务 37 | 设置MySQL用户名和密码,命令如下: 38 | 39 | shell# mysqladmin -uroot password 'mysql_pass'; #设置MySQL的root密码为mysql_pass 40 | shell# mysql -uroot -p #登录数据库,输入刚才设置的密码 41 | mysql> create database zabbix character set utf8; #将zabbix库默认的字符集设置为UTF-8 42 | mysql> grant all privileges on zabbix.* to zabbix@localhost identified by 'zabbix'; #设置zabbix库允许localhost这个IP地址访问,用户名设置为zabbix,密码设置为zabbix 43 | mysql> flush privileges; #刷新权限 44 | 确保以上操作都正确,测试数据库连接是否正常,命令如下: 45 | 46 | shell# mysql -uzabbix -pzabbix zabbix 47 | 导入MySQL库文件,命令如下: 48 | 49 | shell# cd zabbix-4.0.0 #进入Zabbix源码路径 50 | shell# mysql -uzabbix -pzabbix zabbix < database/mysql/schema.sql 51 | ``` 52 | 53 | #551页 54 | ```shell 55 | 如果安装Zabbix-Proxy,则只导入schema.sql即可,无须导入下面的SQL文件;否则,Zabbix-Proxy无法正常工作。 56 | 57 | shell# mysql -uzabbix -pzabbix zabbix < database/mysql/images.sql 58 | shell# mysql -uzabbix -pzabbix zabbix < database/mysql/data.sql 59 | 创建日志保存目录,并修改权限,目录如下: 60 | 61 | shell# mkdir /var/log/zabbix 62 | shell# chown zabbix.zabbix /var/log/zabbix[这是什么命令,缺少文字说明] 63 | ``` 64 | 65 | ```shell 66 | shell# cp misc/init.d/fedora/core/zabbix_* /etc/init.d/ 67 | shell# chmod 755 /etc/init.d/zabbix_* 68 | shell# sed -i "s#BASEDIR=/usr/local#BASEDIR=/usr/#g" /etc/init.d/zabbix_server 69 | shell# sed -i "s#BASEDIR=/usr/local#BASEDIR=/usr/#g" /etc/init.d/zabbix_agentd 70 | ``` 71 | 72 | ```shell 73 | shell# cp -r ./zabbix-X.X.X/frontends/php/ /var/www/html/zabbix 74 | shell# chown -R apache.apache /var/www/html/zabbix 75 | ``` 76 | 77 | ```shell 78 | shell# chkconfig zabbix_server on 79 | shell# service zabbix_server start 80 | shell# systemctl enable httpd 81 | shell# systemctl start httpd #如果启动失败,请检查配置文件是否正确 82 | ``` 83 | 84 | ```shell 85 | shell# vim /etc/php.ini 86 | max_execution_time=300 87 | memory_limit=128M 88 | post_max_size=16M 89 | upload_max_filesize=2M 90 | max_input_time=300 91 | date.timezone=Asia/Shanghai 92 | ``` 93 | 94 | # 552页 95 | 96 | ```shell 97 | hell# wget https://sourceforge.net/projects/zabbix/files/ZABBIX%20Latest% 20Stable/4.0.0/zabbix-4.0.0.tar.gz 98 | shell# groupadd zabbix -g 201 99 | shell# useradd -g zabbix -u 201 -m zabbix 100 | shell# tar xvf zabbix-4.0.0.tar.gz 101 | shell# cd zabbix-4.0.0 102 | shell# ./configure --prefix=/usr --sysconfdir=/etc//zabbix --enable-agent 103 | shell# make 104 | shell# make install 105 | shell# mkdir /var/log/zabbix 106 | shell# chown zabbix.zabbix /var/log/zabbix 107 | shell# cp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/ 108 | shell# chmod 755 /etc/init.d/zabbix_agentd 109 | shell# sed -i "s#BASEDIR=/usr/local#BASEDIR=/usr/#g" /etc/init.d/zabbix_agentd 110 | shell# sed -i "s#tmp/zabbix_agentd.log#var/log/zabbix/zabbix_agentd.log#g" /etc/zabbix/zabbix_agentd.conf 111 | shell# sed -i "#UnsafeUserParameters=0#aUnsafeUserParameters=1\n" /etc/zabbix/zabbix_agentd.conf 112 | #/etc/zabbix/zabbix_agentd.conf配置可参看3.2.3节,这里的X.X.X.X为 113 | #Zabbix-Server的IP地址 114 | 启动Zabbix-Agent服务的命令如下: 115 | 116 | shell# chkconfig zabbix_agentd on 117 | shell# service zabbix_agentd start 118 | ``` 119 | 120 | # 553页 121 | 122 | https://github.com/zabbix-book/zabbix-rpmbuild 123 | 124 | ```shell 125 | shell# yum install rpm-build 126 | ``` 127 | 128 | ```shell 129 | shell# yum install -y gcc make mysql-devel openldap-devel libssh2-devel net-snmp-devel curl-devel unixODBC-devel OpenIPMI-devel java-devel postgresql- devel net-snmp-devel openldap-devel gnutls-devel sqlite-devel curl-devel OpenIPMI-devel libssh2-devel java-devel libxml2-devel libevent-devel openssl-devel 130 | shell# rpm -ivh http://repo.zabbix.com/non-supported/rhel/7/x86_64/fping-3.10-1.el7.x86_64.rpm 131 | ``` 132 | 133 | 134 | 135 | # 554页 136 | 137 | ```shell 138 | shell# useradd admin 139 | ``` 140 | 141 | ```shell 142 | shell# su - admin 143 | shell# mkdir -pv rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS} 144 | shell# echo "% _topdir /home/admin/rpmbuild" >~/.rpmmacros 145 | ``` 146 | 147 | ```shell 148 | shell# cd /home/admin 149 | shell# wget https://raw.githubusercontent.com/zabbix-book/zabbix-rpmbuild/ master/src/zabbix-4.0.0-2.el7.src.rpm 150 | shell# rpm -ivh /home/admin/zabbix-4.0.0-2.el7.src.rpm 151 | ``` 152 | 153 | ```shell 154 | shell# cd /home/admin/rpmbuild/SPECS 155 | shell# rpmbuild -ba zabbix.spec #此处会提示需要依赖包,依次安装 156 | Executing(%prep): /bin/sh -e /var/tmp/rpm-tmp.FK5o3t 157 | + umask 022 158 | + cd /home/admin/rpmbuild/BUILD 159 | + cd /home/admin/rpmbuild/BUILD 160 | + rm -rf zabbix-4.0.0 161 | + /usr/bin/gzip -dc /home/admin/rpmbuild/SOURCES/zabbix-4.0.0.tar.gz 162 | + /usr/bin/tar -xf - 163 | + STATUS=0 164 | + '[' 0 -ne 0 ']' 165 | + cd zabbix-4.0.0 166 | ......省略输出内容...... 167 | #打包生成如下RPM文件 168 | Wrote: /home/admin/rpmbuild/SRPMS/zabbix-4.0.0-2.el7.centos.src.rpm 169 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-agent-4.0.0- 2.el7.centos.x86_64.rpm 170 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-get-4.0.0- 2.el7.centos.x86_64.rpm 171 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-sender-4.0.0- 2.el7.centos.x86_64.rpm 172 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-proxy-mysql-4.0.0- 2.el7.centos.x86_64.rpm 173 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-proxy-pgsql-4.0.0- 2.el7.centos.x86_64.rpm 174 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-proxy-sqlite3-4.0.0- 2.el7.centos.x86_64.rpm 175 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-java-gateway-4.0.0- 2.el7.centos.x86_64.rpm 176 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-server-mysql-4.0.0- 2.el7.centos.x86_64.rpm 177 | Wrote: /home/admin/rpmbuild/RPMS/x86_64/zabbix-server-pgsql-4.0.0- 2.el7.centos.x86_64.rpm 178 | Wrote: /home/admin/rpmbuild/RPMS/noarch/zabbix-web-4.0.0- 2.el7.centos.noarch.rpm 179 | Wrote: /home/admin/rpmbuild/RPMS/noarch/zabbix-web-mysql-4.0.0- 2.el7.centos.noarch.rpm 180 | Wrote: /home/admin/rpmbuild/RPMS/noarch/zabbix-web-pgsql-4.0.0- 2.el7.centos.noarch.rpm 181 | Wrote: /home/admin/rpmbuild/RPMS/noarch/zabbix-web-japanese-4.0.0- 2.el7.centos.noarch.rpm 182 | Executing(%clean): /bin/sh -e /var/tmp/rpm-tmp.pDqbD3 183 | + umask 022 184 | + cd /home/admin/rpmbuild/BUILD 185 | + cd zabbix-4.0.0 186 | + rm -rf /home/admin/rpmbuild/BUILDROOT/zabbix-4.0.0-2.el7.centos.x86_64 187 | + exit 0 188 | ``` 189 | 190 | # 555页 191 | 192 | ```shell 193 | shell# rpm2cpio zabbix-4.0.0-2.el7.src.rpm |cpio -div 194 | warning: rpm2cpio: NOKEY, key ID a14fe591 195 | config.patch 196 | fonts-config.patch 197 | fping3-sourceip-option.patch 198 | zabbix-4.0.0.tar.gz 199 | zabbix-agent.init 200 | zabbix-agent.service 201 | zabbix-java-gateway.init 202 | zabbix-java-gateway.service 203 | zabbix-logrotate.in 204 | zabbix-proxy.init 205 | zabbix-proxy.service 206 | zabbix-server.init 207 | zabbix-server.service 208 | zabbix-tmpfiles.conf 209 | zabbix-web22.conf 210 | zabbix-web24.conf 211 | zabbix.spec 212 | zabbix_java_gateway-sysd 213 | ``` 214 | 215 | # 556页 216 | 217 | ```shell 218 | sed -i \ 219 | -e 's|# PidFile=.*|PidFile=%{_localstatedir}/run/%{name}/ zabbix_agentd.pid|g' \ 220 | -e 's|^LogFile=.*|LogFile=%{_localstatedir}/log/%{name}/ zabbix_agentd.log|g' \ 221 | -e '/# UnsafeUserParameters=0/aUnsafeUserParameters=1\n' \ 222 | -e '/# Include.*zabbix_agentd.conf.d\//aInclude=\/etc\/zabbix\/ zabbix_agentd.conf.d\/\n' \ 223 | -e '/StartAgents=3/aStartAgents=5\n' \ 224 | -e 's|# LogFileSize=.*|LogFileSize=0|g' \ 225 | -e 's|Server=127.0.0.1$|Server=127.0.0.1,10.10.10.1|g' \ 226 | -e 's|ServerActive=127.0.0.1$|ServerActive=127.0.0.1:10051,10.10.10.1: 10051|g' \ 227 | -e 's|# EnableRemoteCommands=0|EnableRemoteCommands=1|g' \ 228 | -e 's|# LogRemoteCommands=0|LogRemoteCommands=1|g' \ 229 | -e 's|LogFileSize=0|LogFileSize=10|g' \ 230 | -e 's|/usr/local|/usr|g' \ 231 | $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/zabbix_agentd.conf 232 | 233 | sed -i \ 234 | -e 's|/usr/local|/usr|g' \ 235 | -e '/# UnsafeUserParameters=0/aUnsafeUserParameters=1\n' \ 236 | -e 's@# Include=/usr/etc/zabbix_agentd.conf.d@Include=/etc/zabbix/ zabbix_agentd.conf.d@g' \ 237 | $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/zabbix_agent.conf 238 | ``` 239 | 240 | ```shell 241 | %post agent 242 | if [ $1 -eq 1 ]; then 243 | sed -i "s@Hostname=Zabbix server@Hostname=$HOSTNAME@g" /etc/zabbix/ zabbix_agentd.conf 244 | getent group zabbix >/dev/null || groupadd -r zabbix 245 | getent passwd zabbix >/dev/null || useradd -r -g zabbix -d %{_sharedstatedir}/ zabbix -s /sbin/nologin -c "zabbix user" zabbix 246 | /sbin/chkconfig zabbix-agent on 247 | /sbin/service zabbix-agent start 248 | chown root:zabbix /bin/netstat 249 | chmod 4755 /bin/netstat 250 | fi 251 | ``` 252 | 253 | # 557页 254 | 255 | `"cURL library support >= 7.28.0 is required for Elasticsearch history backend"` 256 | 257 | https://www.elastic.co/downloads/elasticsearch 258 | 259 | ```shell 260 | shell# rpm -ivh https://artifacts.elastic.co/downloads/elasticsearch/ elasticsearch-6.1.2.rpm 261 | shell# yum install java-1.8.0 -y 262 | ``` 263 | 264 | ```shell 265 | shell# systemctl daemon-reload #重新加载systemd进程 266 | shell# systemctl enable elasticsearch #开机自启动 267 | shell# systemctl start elasticsearch #启动服务 268 | ``` 269 | 270 | ```shell 271 | shell# tail -f /var/log/elasticsearch/elasticsearch.log  272 | [2018-10-20T17:35:55,407][INFO ][o.e.x.m.j.p.l.CppLogMessageHandler] [controller/3091] [Main.cc@109] controller (64 bit): Version 6.4.2 (Build 660eefe6f2ea55) Copyright (c) 2018 Elasticsearch BV 273 | [2018-10-20T17:35:56,116][DEBUG][o.e.a.ActionModule ] Using REST wrapper from plugin org.elasticsearch.xpack.security.Security 274 | [2018-10-20T17:35:56,556][INFO ][o.e.d.DiscoveryModule ] [PYjVnDh] using discovery type [zen] 275 | [2018-10-20T17:35:57,924][INFO ][o.e.n.Node ] [PYjVnDh] initialized 276 | [2018-10-20T17:35:57,925][INFO ][o.e.n.Node ] [PYjVnDh] starting ... 277 | [2018-10-20T17:35:58,180][INFO ][o.e.t.TransportService ] [PYjVnDh] publish_address {127.0.0.1:9300}, bound_addresses {127.0.0.1:9300} 278 | ``` 279 | 280 | # 558页 281 | 282 | ```shell 283 | shell# netstat -nlput|grep 9200 284 | tcp6       0      0 127.0.0.1:9200   :::*    LISTEN      3042/java  285 | ``` 286 | 287 | ```shell 288 | shell# vim /etc/elasticsearch/jvm.options 289 | -Xms1g 290 | -Xmx1g 291 | ``` 292 | 293 | ######第1~5部分 294 | 295 | https://github.com/zabbix-book/es-mapping-create/blob/master/step-1-create_elastic_mapping.sh 296 | 297 | ###### 第7部分 298 | 299 | https://github.com/zabbix-book/es-mapping-create/blob/master/step-2-create_elastic_template.sh 300 | 301 | ###### 第8部分 302 | 303 | https://github.com/zabbix-book/es-mapping-create/blob/master/step-3-create_elastic_pipeline.sh 304 | 305 | ```shell 306 | shell# curl -X PUT \ 307 | http://127.0.0.1:9200/uint \ 308 | -H 'content-type:application/json' \ 309 | -d '{ 310 | "settings" : { 311 | "index" : { 312 | "number_of_replicas" : 1, 313 | "number_of_shards" : 5 314 | } 315 | }, 316 | "mappings" : { 317 | "values" : { 318 | "properties" : { 319 | "itemid" : { 320 | "type" : "long" 321 | }, 322 | "clock" : { 323 | "format" : "epoch_second", 324 | "type" : "date" 325 | }, 326 | "value" : { 327 | "type" : "long" 328 | } 329 | } 330 | } 331 | } 332 | }' 333 | #创建成功,提示如下 334 | {"acknowledged":true,"shards_acknowledged":true,"index":"uint"} 335 | ``` 336 | 337 | # 559页 338 | 339 | ```shell 340 | shell# curl -X PUT \ 341 | http://127.0.0.1:9200/dbl \ 342 | -H 'content-type:application/json' \ 343 | -d '{ 344 | "settings" : { 345 | "index" : { 346 | "number_of_replicas" : 1, 347 | "number_of_shards" : 5 348 | } 349 | }, 350 | "mappings" : { 351 | "values" : { 352 | "properties" : { 353 | "itemid" : { 354 | "type" : "long" 355 | }, 356 | "clock" : { 357 | "format" : "epoch_second", 358 | "type" : "date" 359 | }, 360 | "value" : { 361 | "type" : "double" 362 | } 363 | } 364 | } 365 | } 366 | }' 367 | #创建成功,提示如下 368 | {"acknowledged":true,"shards_acknowledged":true,"index":"dbl"} 369 | ``` 370 | 371 | # 560页 372 | 373 | ```shell 374 | shell# curl -X PUT \ 375 | http://127.0.0.1:9200/str \ 376 | -H 'content-type:application/json' \ 377 | -d '{ 378 | "settings" : { 379 | "index" : { 380 | "number_of_replicas" : 1, 381 | "number_of_shards" : 5 382 | } 383 | }, 384 | "mappings" : { 385 | "values" : { 386 | "properties" : { 387 | "itemid" : { 388 | "type" : "long" 389 | }, 390 | "clock" : { 391 | "format" : "epoch_second", 392 | "type" : "date" 393 | }, 394 | "value" : { 395 | "fields" : { 396 | "analyzed" : { 397 | "index" : true, 398 | "type" : "text", 399 | "analyzer" : "standard" 400 | } 401 | }, 402 | "index" : false, 403 | "type" : "text" 404 | } 405 | } 406 | } 407 | } 408 | }' 409 | #创建成功,提示如下 410 | {"acknowledged":true,"shards_acknowledged":true,"index":"str"} 411 | ``` 412 | 413 | # 561页 414 | 415 | ```shell 416 | shell# curl -X PUT \ 417 | http://127.0.0.1:9200/text \ 418 | -H 'content-type:application/json' \ 419 | -d '{ 420 | "settings" : { 421 | "index" : { 422 | "number_of_replicas" : 1, 423 | "number_of_shards" : 5 424 | } 425 | }, 426 | "mappings" : { 427 | "values" : { 428 | "properties" : { 429 | "itemid" : { 430 | "type" : "long" 431 | }, 432 | "clock" : { 433 | "format" : "epoch_second", 434 | "type" : "date" 435 | }, 436 | "value" : { 437 | "fields" : { 438 | "analyzed" : { 439 | "index" : true, 440 | "type" : "text", 441 | "analyzer" : "standard" 442 | } 443 | }, 444 | "index" : false, 445 | "type" : "text" 446 | } 447 | } 448 | } 449 | } 450 | }' 451 | #创建成功,提示如下 452 | {"acknowledged":true,"shards_acknowledged":true,"index":"text"} 453 | ``` 454 | 455 | # 562页 456 | 457 | ```shell 458 | shell# curl -X PUT \ 459 | http://127.0.0.1:9200/log \ 460 | -H 'content-type:application/json' \ 461 | -d '{ 462 | "settings" : { 463 | "index" : { 464 | "number_of_replicas" : 1, 465 | "number_of_shards" : 5 466 | } 467 | }, 468 | "mappings" : { 469 | "values" : { 470 | "properties" : { 471 | "itemid" : { 472 | "type" : "long" 473 | }, 474 | "clock" : { 475 | "format" : "epoch_second", 476 | "type" : "date" 477 | }, 478 | "value" : { 479 | "fields" : { 480 | "analyzed" : { 481 | "index" : true, 482 | "type" : "text", 483 | "analyzer" : "standard" 484 | } 485 | }, 486 | "index" : false, 487 | "type" : "text" 488 | } 489 | } 490 | } 491 | } 492 | }' 493 | #创建成功,提示如下 494 | {"acknowledged":true,"shards_acknowledged":true,"index":"log"} 495 | ``` 496 | 497 | # 563页 498 | 499 | ```shell 500 | ### Option: HistoryStorageDateIndex 501 | #       Enable preprocessing of history values in history storage to store values in different indices based on date. 502 | #       0 - disable 503 | #       1 - enable 504 | # 505 | # Mandatory: no 506 | # Default: 507 | HistoryStorageDateIndex=1 #开启按天索引的功能 508 | ``` 509 | 510 | ```c 511 | #src/libs/zbxhistory/history_elastic.c 512 | static int  elastic_add_values(zbx_history_iface_t *hist, const zbx_vector_ptr_t *history) 513 | { 514 |     ......省略部分代码...... 515 |     zbx_json_init(&json_idx, ZBX_IDX_JSON_ALLOCATE); 516 | 517 |     zbx_json_addobject(&json_idx, "index"); 518 |     zbx_json_addstring(&json_idx, "_index", value_type_str[hist->value_type], ZBX_JSON_TYPE_STRING); 519 |     zbx_json_addstring(&json_idx, "_type", "values", ZBX_JSON_TYPE_STRING); 520 |     if (1 == CONFIG_HISTORY_STORAGE_PIPELINES)//pipeline的开关 521 |     { 522 |         zbx_snprintf(pipeline, sizeof(pipeline), "%s-pipeline", value_type_str [hist->value_type]); 523 |         zbx_json_addstring(&json_idx, "pipeline", pipeline, ZBX_JSON_TYPE_STRING); 524 |     } 525 |     ......省略部分代码...... 526 | } 527 | ``` 528 | 529 | # 564页 530 | 531 | ```shell 532 | shell# curl -X PUT \ 533 | http://127.0.0.1:9200/_template/text_template \ 534 | -H 'content-type:application/json' \ 535 | -d '{ 536 | "template": "text*", #匹配的数据类型为text*,其他数据类型类似 537 | "index_patterns": ["text*"], #匹配的数据类型为text*,其他数据类型类似 538 | "settings" : { 539 | "index" : { 540 | "number_of_replicas" : 1, 541 | "number_of_shards" : 5 542 | } 543 | }, 544 | "mappings" : { 545 | "values" : { 546 | "properties" : { 547 | "itemid" : { 548 | "type" : "long" 549 | }, 550 | "clock" : { 551 | "format" : "epoch_second", 552 | "type" : "date" 553 | }, 554 | "value" : { 555 | "fields" : { 556 | "analyzed" : { 557 | "index" : true, 558 | "type" : "text", 559 | "analyzer" : "standard" 560 | } 561 | }, 562 | "index" : false, 563 | "type" : "text" 564 | } 565 | } 566 | } 567 | } 568 | }' 569 | #创建成功,提示如下 570 | {"acknowledged":true} 571 | ``` 572 | 573 | # 565页 574 | 575 | ```shell 576 | shell# curl -X PUT \ 577 | http://127.0.0.1:9200/_ingest/pipeline/uint-pipeline \ 578 | -H 'content-type:application/json' \ 579 | -d '{ 580 | "description": "daily uint index naming", 581 | "processors": [ 582 | { 583 | "date_index_name": { #按日期对字段索引 584 | "field": "clock", #匹配哪个字段 585 | "date_formats": ["UNIX"], #日期格式,可用字段有ISO8601、UNIX、UNIX_MS和TAI64N 586 | "index_name_prefix": "uint-", #索引名称前缀 587 | "date_rounding": "d" #可用字段有y(年)、M(月)、w(星期)、d(日)、h(小时)、m(分钟)和s(秒) 588 | } 589 | } 590 | ] 591 | }' 592 | #创建成功,提示如下 593 | {"acknowledged":true} 594 | ``` 595 | 596 | https://www.elastic.co/guide/en/elasticsearch/reference/6.3/date-index-name-processor.html 597 | 598 | ```shell 599 | 配置Zabbix-Server,命令如下: 600 | shell# vim /etc/zabbix/zabbix_server.conf 601 | ### Option: HistoryStorageURL 602 | # History storage HTTP[S] URL. 603 | # 604 | # Mandatory: no 605 | # Default: 606 | HistoryStorageURL=http://192.168.0.15:9200 607 | 608 | ### Option: HistoryStorageTypes 609 | # Comma separated list of value types to be sent to the history storage. 610 | # 611 | # Mandatory: no 612 | # Default: 613 | HistoryStorageTypes=uint,dbl,str,log,text 614 | HistoryStorageDateIndex=1 615 | 重启Zabbix-Server服务,命令如下: 616 | 617 | shell# systemctl restart zabbix-server 618 | ``` 619 | 620 | # 566页 621 | 622 | ```shell 623 | shell# vim /etc/zabbix/web/zabbix.conf.php  624 | global $DB, $HISTORY; //一定要加上$HISTORY,否则无法生效 625 | //$HISTORY['url']   = [ 626 | // 'uint' => 'http://localhost:9200', 627 | // 'text' => 'http://localhost:9200' 628 | //]; 629 | // Value types stored in Elasticsearch. 630 | //$HISTORY['types'] = ['uint', 'text']; 631 | $HISTORY['url'] = 'http://192.168.0.15:9200'; 632 | $HISTORY['types'] = ['uint','dbl','str','log','text']; 633 | ``` 634 | 635 | -------------------------------------------------------------------------------- /charter-15/Zabbix书籍V2-第15章-操作命令.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/charter-15/Zabbix书籍V2-第15章-操作命令.pdf -------------------------------------------------------------------------------- /charter-15/readme.md: -------------------------------------------------------------------------------- 1 | > 《Zabbix企业级分布式监控系统第2版》随书代码 2 | > 3 | > 代码仓库地址 https://github.com/zabbix-book/zabbix_v2 4 | > 5 | > 书籍购买地址 https://item.jd.com/12653708.html 6 | 7 | #573页 8 | 9 | 表15-1 硬件配置 10 | 11 | | 应 用 名 称 | 操 作 系 统 | CPU | 内  存 | 硬  盘 | 12 | | ------------- | ------------ | ------ | --------- | ------------------ | 13 | | Zabbix-Server | RHEL 6.5 x64 | 8核心 | DDR3 16GB | SATA 500GB´2 RAID1 | 14 | | Zabbix-DB | RHEL 6.5 x64 | 24核心 | DDR3 64GB | SAS 300GB´4 RAD1+0 | 15 | | Zabbix-GUI | RHEL 6.5 x64 | 4核心 | DDR3 4GB | SATA 500GB | 16 | | Zabbix-Proxy | RHEL 6.5 x64 | 8核心 | DDR3 16GB | SAS 300GB´2 RAID1 | 17 | 18 | 表15-2 各服务器的IP地址规划 19 | 20 | | 应 用 名 称 | 角  色 | IP地址 | | | 21 | | ------------- | --------------- | ------------- | ----------- | ---------- | 22 | | 物理IP地址 | 虚拟IP地址 | 公网IP地址 | | | 23 | | Zabbix-Server | 主服务器 | 192.168.0.3 | 192.168.0.5 | 58.75.2.89 | 24 | | Zabbix-Server | 从服务器 | 192.168.0.4 | | | 25 | | Zabbix-DB | MySQL数据库主库 | 192.168.0.240 | 无 | 无 | 26 | | Zabbix-DB | MySQL数据库从库 | 192.168.0.241 | | | 27 | | Zabbix-GUI | 前端管理界面 | 192.168.0.2 | 无 | 无 | 28 | | Zabbix-Proxy | 代理节点 | 10.10.10.2 | 无 | 61.61.52.9 | 29 | | Zabbix-Agent | 被监控端 | 10.10.10.10 | 无 | 无 | 30 | 31 | # 574页 32 | 33 | 表15-3 Zabbix的数据库规划 34 | 35 | | 角  色 | IP地址 | 域  名 | 运行的服务 | 36 | | ------------ | ------------- | ------------------------------- | ---------- | 37 | | MySQL-Master | 192.168.0.240 | zabbix-mysql-master.itnihao.com | MySQL服务 | 38 | | MySQL-Slave | 192.168.0.241 | zabbix-mysql-slave.itnihao.com | MySQL服务 | 39 | 40 | ```shell 41 | shell# rpm -ivh http://repo.mysql.com/yum/mysql-8.0-community/el/7/x86_64/ mysql80-community-release-el7-1.noarch.rpm 42 | Shell# yum install mysql-community-server 43 | ``` 44 | 45 | ``` 46 | shell# vim /etc/my.cnf 47 | [mysqld] 48 | datadir=/var/lib/mysql 49 | socket=/var/lib/mysql/mysql.sock 50 | user=mysql 51 | 52 | symbolic-links=0 53 | character-set-server=utf8 #设置字符集为UTF-8 54 | innodb_file_per_table=1 #让InnoDB的每个表文件单独存储 55 | innodb_data_file_path=ibdata1:10M:autoextend 56 | server_id=1 #从库设置为非1 57 | 58 | [mysqld_safe] 59 | log-error=/var/log/mysqld.log 60 | pid-file=/var/run/mysqld/mysqld.pid 61 | 62 | ``` 63 | 64 | 更多配置可参考https://github.com/zabbix-book/MySQL_conf 65 | 66 | # 575页 67 | 68 | ```shell 69 | shell# systemctl start mysqld 70 | ``` 71 | 72 | ```shell 73 | shell# MysqlPassword=admin@2018ABCD 74 | shell# mysqladmin -u root password ${MysqlPassword} 75 | mysql> create database zabbix character set utf8; 76 | mysql> grant all privileges on zabbix.* to zabbix@'192.168.0.2' identified by 'zabbix'; 77 | mysql> grant all privileges on zabbix.* to zabbix@'192.168.0.3' identified by 'zabbix'; 78 | mysql> grant all privileges on zabbix.* to zabbix@'192.168.0.4' identified by 'zabbix'; 79 | mysql> grant all privileges on zabbix.* to zabbix@'192.168.0.5' identified by 'zabbix'; 80 | mysql> grant all privileges on zabbix.* to zabbix@'127.0.0.1' identified by 'zabbix'; 81 | mysql> flush privileges; 82 | ``` 83 | 84 | ```shell 85 | shell# cd /usr/share/doc/zabbix-server-mysql-4.0.0 #进入对应版本的目录 86 | shell# gunzip create.sql.gz #将SQL文件解压缩 87 | shell# mysql -uzabbix -pzabbix -h127.0.0.1 #以zabbix用户登录 88 | mysql> use zabbix #切换到zabbix库 89 | mysql> source /usr/share/doc/zabbix-server-mysql-4.0.0/create.sql; 90 | ``` 91 | 92 | ```shell 93 | shell# systemctl stop mysqld 94 | ``` 95 | 96 | # 576页 97 | 98 | ```shell 99 | shell# rsync -av -e "ssh -p 22" /var/lib/mysql/ root@192.168.0.241:/var/ lib/mysql #192.168.0.241为MySQL数据库从库服务器的IP地址 100 | ``` 101 | 102 | ```shell 103 | shell# systemctl start mysqld 104 | ``` 105 | 106 | ```bash 107 | shell# mysql -uroot -p 108 | mysql> GRANT REPLICATION CLIENT,REPLICATION SLAVE ON *.* TO repl@'192.168.0.241.%' IDENTIFIED BY 'zabbix_repl'; 109 | mysql> FLUSH PRIVILEGES; 110 | ``` 111 | 112 | ```python 113 | mysql> show master status\G; 114 | *************************** 1. row *************************** 115 | File: mysql-bin.000003 116 | Position: 107 117 | Binlog_Do_DB: 118 | Binlog_Ignore_DB: 119 | Executed_Gtid_Set: 120 | 1 row in set (0.00 sec) 121 | ``` 122 | 123 | ```shell 124 | shell# systemctl start mysqld #启动Master节点 125 | ``` 126 | 127 | ```shell 128 | mysql> change master to master_host='192.168.0.240', MASTER_USER='repl', MASTER_PASSWORD='zabbix_repl', MASTER_PORT=3306, MASTER_LOG_FILE='mysql-bin.000003', MASTER_LOG_POS=107, MASTER_CONNECT_RETRY=10; #107要和mater的Position数值一致 129 | ``` 130 | 131 | # 577页 132 | 133 | ```shell 134 | mysql> start slave; 135 | ``` 136 | 137 | ```python 138 | mysql> show slave status\G; 139 | *************************** 1. row *************************** 140 | Slave_IO_State: Waiting for master to send event 141 | Master_Host: 192.168.0.240 142 | Master_User: repl 143 | Master_Port: 3306 144 | Connect_Retry: 10 145 | Master_Log_File: mysql-bin.000003 146 | Read_Master_Log_Pos: 888190 147 | Relay_Log_File: mysql-relay-bin.000002 148 | Relay_Log_Pos: 107 149 | Relay_Master_Log_File: mysql-bin.000003 150 | 查看如下显示是否均为YES状态 151 | Slave_IO_Running: Yes 152 | Slave_SQL_Running: YES 153 | ``` 154 | 155 | ```shell 156 | shell# egrep -v "^$|^#" /etc/zabbix/zabbix_server.conf 157 | LogFile=/var/log/zabbix/zabbix_server.log 158 | LogFileSize=0 159 | PidFile=/var/run/zabbix/zabbix_server.pid 160 | DBHost = zabbix-mysql-master.itnihao.com 161 | DBName=zabbix 162 | DBUser=zabbix 163 | DBPassword=zabbix 164 | DBSocket=/var/lib/mysql/mysql.sock 165 | SNMPTrapperFile=/var/log/snmptt/snmptt.log 166 | AlertScriptsPath=/etc/zabbix/alertscripts 167 | ExternalScripts=/etc/zabbix/externalscripts 168 | SourceIP=192.168.0.5 #VIP地址 169 | ``` 170 | 171 | # 578页 172 | 173 | ```shell 174 | shell# yum install keepalived -y 175 | ``` 176 | 177 | **/etc/keepalived/keepalived.conf** 配置参考 178 | 179 | https://github.com/zabbix-book/zabbix-HA/blob/master/keepalived.conf-master 180 | 181 | ```shell 182 | # cat keepalived.conf 183 | # https://github.com/zabbix-book/zabbix-HA 184 | ! Configuration File for keepalived 185 | 186 | global_defs { 187 | notification_email { 188 | admin@localhost.com 189 | } 190 | notification_email_from zabbix_ha_node1@itnihao.com 191 | smtp_server 127.0.0.1 192 | smtp_connect_timeout 30 193 | router_id ZABBIX_NODE1 194 | } 195 | 196 | vrrp_script zabbix_ha { 197 | script "/etc/keepalived/ha_switch.sh 1 2 STATUS" 198 | interval 5 199 | } 200 | 201 | vrrp_instance VI_1 { 202 | state MASTER 203 | nopreempt 204 | interface eth0 205 | virtual_router_id 109 206 | priority 190 207 | advert_int 5 208 | smtp_alert 209 | 210 | authentication { 211 | auth_type PASS 212 | auth_pass ZABBIX_HA_ZBX_BOOK 213 | } 214 | 215 | virtual_ipaddress { 216 | 192.168.0.5 217 | } 218 | 219 | track_script { 220 | zabbix_ha 221 | } 222 | 223 | notify_master /etc/keepalived/ha_switch.sh MASTER 224 | notify_backup /etc/keepalived/ha_switch.sh BACKUP 225 | notify_fault /etc/keepalived/ha_switch.sh FAULT 226 | notify /etc/keepalived/ha_switch.sh 227 | } 228 | ``` 229 | 230 | https://github.com/zabbix-book/zabbix-HA/blob/master/keepalived.conf-backup 231 | 232 | ```shell 233 | 234 | # cat keepalived.conf 235 | # https://github.com/zabbix-book/zabbix-HA 236 | ! Configuration File for keepalived 237 | 238 | global_defs { 239 | notification_email { 240 | admin@localhost.com 241 | } 242 | notification_email_from zabbix_ha_node2@itnihao.com 243 | smtp_server 127.0.0.1 244 | smtp_connect_timeout 30 245 | router_id ZABBIX_NODE2 246 | } 247 | 248 | vrrp_script zabbix_ha { 249 | script "/etc/keepalived/ha_switch.sh 1 2 STATUS" 250 | interval 5 251 | } 252 | 253 | vrrp_instance VI_1 { 254 | state BACKUP 255 | nopreempt 256 | interface eth0 257 | virtual_router_id 109 258 | priority 100 259 | advert_int 5 260 | smtp_alert 261 | 262 | authentication { 263 | auth_type PASS 264 | auth_pass ZABBIX_HA_ZBX_BOOK 265 | } 266 | 267 | virtual_ipaddress { 268 | 192.168.0.5 269 | } 270 | 271 | track_script { 272 | zabbix_ha 273 | } 274 | 275 | notify_master /etc/keepalived/ha_switch.sh MASTER 276 | notify_backup /etc/keepalived/ha_switch.sh BACKUP 277 | notify_fault /etc/keepalived/ha_switch.sh FAULT 278 | notify /etc/keepalived/ha_switch.sh 279 | } 280 | ``` 281 | 282 | # 579页 283 | 284 | 书中的脚本处理并不是最佳实践,可使用此处更新后的脚本 285 | 286 | ```shell 287 | # cat ha_switch.sh 288 | #!/bin/bash 289 | #https://github.com/zabbix-book/zabbix-HA 290 | #author: itnihao 291 | 292 | STATE="$3" 293 | 294 | ulimit -n 40960 295 | VIP="192.168.0.5" 296 | ZBX_SERVER="zabbix_server" 297 | ZBX_SERVER_PID="/var/run/zabbix/zabbix_server.pid" 298 | #SERVER_PORCESS_NUM=$(pidstat -C "zabbix_server"|grep -c "$ZBX_SERVER") 299 | 300 | if [ -f "${ZBX_SERVER_PID}" ];then 301 | SERVER_PID=$(cat "${ZBX_SERVER_PID}") 302 | else 303 | SERVER_PID=$(pidof "${ZBX_SERVER}") 304 | fi 305 | 306 | if [ "${SERVER_PID}" == "" ];then 307 | SERVER_PID=$(pidof "${ZBX_SERVER}") 308 | fi 309 | 310 | case $STATE in 311 | "MASTER") 312 | if [ "${SERVER_PID}" == "" ];then 313 | systemctl start zabbix-server 314 | fi 315 | echo "MASTER" >/etc/zabbix/.ha_role 316 | exit 0 317 | ;; 318 | "BACKUP") 319 | systemctl stop zabbix-server 320 | killall -9 zabbix_server 321 | echo "BACKUP" >/etc/zabbix/.ha_role 322 | arping "${VIP}" -c 2 323 | exit 0 324 | ;; 325 | "FAULT") 326 | systemctl stop zabbix-server 327 | killall -9 zabbix_server 328 | exit 0 329 | ;; 330 | "STATUS") 331 | #echo "$(date) status">>/tmp/date.log 332 | ROLE=$(cat /etc/zabbix/.ha_role) 333 | if [ "${SERVER_PID}" == "" ];then 334 | if [ "$ROLE" == "MASTER" ];then 335 | killall -9 "${ZBX_SERVER}" && rm -f "${ZBX_SERVER_PID}" 336 | systemctl start zabbix-server 337 | exit 0 338 | elif [ "$ROLE" == "BACKUP" ];then 339 | ps -ef |grep "/usr/sbin/zabbix_server"|grep -v "grep"|awk '{print $2}'|xargs kill -9 && rm -f "${ZBX_SERVER_PID}" 340 | systemctl stop zabbix-server 341 | ps -ef |grep "/usr/sbin/zabbix_server"|grep -v "grep"|awk '{print $2}'|xargs kill -9 342 | if [ -f "${ZBX_SERVER_PID}" ];then 343 | rm -f "${ZBX_SERVER_PID}" 344 | fi 345 | exit 0 346 | else 347 | exit 0 348 | fi 349 | fi 350 | ;; 351 | *) 352 | echo "unknown state" 353 | exit 1 354 | ;; 355 | esac 356 | ``` 357 | 358 | # 582页 359 | 360 | ```shell 361 | {Template OS Linux:proc.num[].avg(5m)}>300 #进程数量 362 | {Template OS Linux:agent.ping.nodata(5m)}=1 #由于网络抖动而引起的误报 363 | {Template OS Linux:kernel.maxfiles.last(0)}<1024 #文件描述符,实际大于此参数值 364 | {Template OS Linux:kernel.maxproc.last(0)}<256 #进程数,实际大于此参数值 365 | ``` 366 | 367 | -------------------------------------------------------------------------------- /勘误/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zabbix-book/zabbix_v2/f6621ee1aa36ec9d50e530cd39d73545edee9bcf/勘误/.DS_Store -------------------------------------------------------------------------------- /勘误/第一次印刷/readme.md: -------------------------------------------------------------------------------- 1 | # 81页 拼写错误 2 | `Micros`修改为`Macros` 3 | 4 | # 118页 5 | 单击`Configuration`->Authentication 修改为`Administration`->Authentication 6 | 7 | # 127页 增加说明 8 | 9 | · Numeric (unsigned):64位无符号整数 10 | 11 | · Numeric (float):浮点数,值范围为-999999999999.9999~999999999999.9999 12 | 13 | · Character:字符(字符串)类型,数据限制为255B 14 | 15 | · Log:日志`数据,数据库表中的TEXT数据类型,参考图3-30表结构` 16 | 17 | Text:文本`数据,数据库表中的TEXT数据类型,参考图3-30表结构` 18 | 19 | # 221页 调整格式 20 | 21 | shell# **cp wechat-alert-master/wechat_linux_amd64** `增加一个空格` /etc/zabbix/alertscripts/wehchat 22 | 23 | # 222页 调整格式 24 | 25 | shell#`mkdir -p /etc/zabbix/alertscripts/` 字体加粗 26 | 27 | shell#`cat /etc/zabbix/alertscripts/zabbix_sendmail.py ` 字体加粗 28 | 29 | # 224页 调整格式 30 | 31 | shell# **chmod 700 /etc/zabbix/alertscripts/zabbix_sendmail.py** 32 | 33 | shell# `多一个空格`**chown zabbix.zabbix /etc/zabbix/alertscripts/zabbix_sendmail.py** 34 | 35 | # 345页 调整格式 36 | 37 | shell# **vi** `加粗`/etc/logrotate.d/zabbix_traps 38 | 39 | # 385、387、388 拼写错误 40 | 41 | 将”OBDC”修改为”ODBC” 42 | 43 | # 436页 路径错误 44 | `vim /etc/zabbix/scripts/nginx_status` 修改为 `vim /etc/zabbix/scripts/check_nginx_status.sh` 45 | # 439页 路径错误 46 | `vim /etc/zabbix/scripts/monitor_phpfpm_status` 修改为 `vim /etc/zabbix/scripts/check_phpfpm.sh` 47 | 48 | # 471页 示例错误 49 | 50 | 修改后的内容如下 51 | 52 | ------ 53 | 54 | 将代码和配置文件放到相应的目录下: 55 | 56 | \#代码和配置见https://github.com/zabbix-book/Pyora/ 57 | 58 | shell# **cp** **pyora.py** **/etc/zabbix/scripts/pyora.py** 59 | 60 | shell# **cp py_oracle.conf /etc/zabbix/zabbix_agentd.conf.d/oracle.conf** 61 | 62 | 63 | 64 | # 538页 调整格式 65 | 66 | ```python 67 | 38. #认证和获取sessionid 68 | 39. try: 69 | 40. result = urllib2.urlopen(request) #此处增加4个空格 70 | 41. #对认证出错的处理 71 | 42. except HTTPError, e: 72 | 43. print 'The server couldn\'t fulfill the request, Error code: ', e.code 73 | 44. except URLError, e: 74 | 45. print 'We failed to reach a server.Reason: ', e.reason 75 | 46. else: 76 | ``` 77 | 78 | 79 | 80 | # 579页 增加链接 81 | 82 | 增加链接`完整脚本请参考https://github.com/zabbix-book/zabbix-HA` 83 | 84 | ``` 85 | shell# cat /etc/keepalived/chk_zabbix_server.sh 86 | #!/bin/bash 87 | # 完整脚本请参考https://github.com/zabbix-book/zabbix-HA 88 | # 89 | status1=$(ps aux|grep "/usr/sbin/zabbix_server" | grep -v grep | grep -v bash | wc -l) 90 | 91 | if [ "${status1}" = "0" ]; then 92 | 93 | /etc/init.d/zabbix-server start 94 | sleep 3 95 | 96 | status2=$(ps aux|grep zabbix_server | grep -v grep | grep -v bash |wc -l) 97 | if [ "${status2}" = "0" ]; then 98 | /etc/init.d/keepalived stop 99 | fi 100 | fi 101 | ``` 102 | 103 | 104 | 105 | 106 | --------------------------------------------------------------------------------