Инструменты пользователя

Инструменты сайта


сервис_zabbix

Сервис Zabbix

Установка и запуск сервера

Документация

Установка необходимых компонентов

Debian/Ubuntu

# apt install zabbix-server-mysql   #2m
# cat zabbix.sql
#drop database zabbix;
create database zabbix character set utf8 collate utf8_bin;
grant all privileges on zabbix.* to zabbix@localhost identified by 'zabbix';
# mysql < zabbix.sql
# zcat /usr/share/zabbix-server-mysql/schema.sql.gz | mysql -uzabbix -pzabbix zabbix  #1m

# zcat /usr/share/zabbix-server-mysql/images.sql.gz | mysql -uzabbix -pzabbix zabbix

# zcat /usr/share/zabbix-server-mysql/data.sql.gz | mysql -uzabbix -pzabbix zabbix

# cat /etc/zabbix/zabbix_server.conf
...
DBHost=localhost
DBName=zabbix
DBUser=zabbix
DBPassword=zabbix
# systemctl enable zabbix-server

# service zabbix-server start

FreeBSD

# pkg install zabbix3-server

# mysql

mysql> create database zabbix character set utf8;
mysql> grant all privileges on zabbix.* to zabbix@localhost identified by 'zabbix';
mysql> quit;

# cat /usr/local/share/zabbix3/server/database/mysql/schema.sql | mysql -uzabbix -p zabbix
# cat /usr/local/share/zabbix3/server/database/mysql/images.sql | mysql -uzabbix -p zabbix
# cat /usr/local/share/zabbix3/server/database/mysql/data.sql | mysql -uzabbix -p zabbix

# cat /usr/local/etc/zabbix3/zabbix_server.conf
LogFile=/tmp/zabbix_server.log
Timeout=30  # for external scripts
DBHost=localhost
DBName=zabbix
DBUser=zabbix
DBPassword=zabbix
# sysrc zabbix_server_enable=yes

# service zabbix_server start

Установка и запуск web интерфейса

Все следующие компоненты поставятся, как зависимости:

Debian 9

# apt install zabbix-frontend-php php-mysql  #1m

# cat /etc/apache2/conf-available/zabbix-frontend-php.conf
...
php_value date.timezone Europe/Moscow
...
php_value date.timezone Europe/Moscow
...
# a2enconf zabbix-frontend-php

# service apache2 reload

# touch /etc/zabbix/zabbix.conf.php

# chown www-data /etc/zabbix/zabbix.conf.php

http://server.corpX.un/zabbix/setup.php

# less /etc/zabbix/zabbix.conf.php
<?php
// Zabbix GUI configuration file.
global $DB;

$DB['TYPE']     = 'MYSQL';
$DB['SERVER']   = 'localhost';
$DB['PORT']     = '0';
$DB['DATABASE'] = 'zabbix';
$DB['USER']     = 'zabbix';
$DB['PASSWORD'] = 'zabbix';

// Schema name. Used for IBM DB2 and PostgreSQL.
$DB['SCHEMA'] = '';

$ZBX_SERVER      = 'localhost';
$ZBX_SERVER_PORT = '10051';
$ZBX_SERVER_NAME = '';

$IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG;

FreeBSD

# pkg install zabbix3-frontend

# cp /usr/local/www/zabbix3/conf/zabbix.conf.php.example /usr/local/www/zabbix3/conf/zabbix.conf.php

# cat /usr/local/www/zabbix3/conf/zabbix.conf.php
...
$DB['PASSWORD']                 = 'zabbix';
...
# cat /usr/local/etc/apache24/httpd.conf
...
DocumentRoot "/usr/local/www/apache24/data"

Alias /zabbix /usr/local/www/zabbix3

<Directory "/usr/local/www/zabbix3">
  Options Indexes FollowSymLinks

  php_value post_max_size 16M
  php_value max_execution_time 300
  php_value max_input_time 300
  php_value always_populate_raw_post_data -1
  php_value date.timezone Europe/Moscow

  AllowOverride All
  Require all granted
  Allow from all
</Directory>
...

Установка и запуск proxy

gate# apt install zabbix-proxy-mysql

gate# cat zabbix_proxy.sql
#drop database zabbix_proxy;
create database zabbix_proxy character set utf8 collate utf8_bin;
grant all privileges on zabbix_proxy.* to zabbix@localhost identified by 'zabbix';
gate# mysql < zabbix_proxy.sql

gate# zcat /usr/share/zabbix-proxy-mysql/schema.sql.gz | mysql -uzabbix -pzabbix zabbix_proxy

gate# cat /etc/zabbix/zabbix_proxy.conf
...
Hostname=gate
ConfigFrequency=60
Server=server
DBHost=localhost
DBName=zabbix_proxy
DBUser=zabbix
DBPassword=zabbix
gate# systemctl enable zabbix-proxy

gate# service zabbix-proxy start

Добавление proxy в zabbix server

Administration->Proxies

Настройка мониторинга

Настройка уведомлений о событиях

Administration->Media types->Email

Administration->Users->Admin или userX->Media

Configuration->Actions->Event source: Triggers
  Report problems to Zabbix administrators->Enable

    Actions

...
1. {ITEM.NAME1} ({HOST.NAME1}:{ITEM.KEY1}): 

Current:

{ITEM.VALUE1}

Previous:

{{HOSTNAME}:{TRIGGER.KEY}.last(#2)}
...


    Operations:
      Default message
        ...
        Trigger Description: 

        {TRIGGER.DESCRIPTION}
        ...
    
    Recovery operations
Reports -> Action log

Простые проверки

Host: ya.ru                         или val.bmstu.ru
  ЛЮБОЙ ИНТЕРФЕЙС: ya.ru            или val.bmstu.ru
  New group: External Hosts
  Items 
    Name: check perf http
    Type: Simple check
    Key: net.tcp.service.perf[https]
    Type of information: Numeric (float)
Host: server
...
  Items
    Name: check ping gate.isp.un
    Type: Simple check
    Key: icmpping[gate.isp.un]
    Applications: Network check

Host: server 
...
  Items
    Name: check rdp client1
    Type: Simple check
    Key: net.tcp.service[tcp,192.168.6.101,3389]
    Applications: Service check

Внешние проверки

server# less /etc/zabbix/zabbix_server.conf
...
ExternalScripts=...
...
Timeout=...
...
server# ES=/etc/zabbix/externalscripts
или
server# ES=/usr/lib/zabbix/externalscripts

server# mkdir $ES

server# cd $ES

Пример простого скрипта

server# cat ping_avg.sh
#!/bin/sh
ping -c"$1" "$2" | tail -n1 | cut -d'/' -f5
Cofiguration->Hosts->gate
  Items
    Name: Ping AVG
    Type: External Check
    Key: ping_avg.sh[3,"{HOST.CONN}"]
    Type of information: Numeric (float)

Пример скрипта, требующего повышения привилегий

!!! Для некоторых хостов (например, val.bmstu.ru) не хватит Timeout

server# cat /etc/sudoers.d/zabbix
zabbix ALL = (ALL) NOPASSWD: /usr/bin/nmap -O *
server# cat detect_host_nmap.sh
#!/bin/sh
sudo /usr/bin/nmap -O $1 | grep -v 'Starting Nmap\|Host is up\|Nmap done'
Cofiguration->Hosts->gate
  Items
    Name: Detect host operating system by nmap
    Type: External Check
    Key: detect_host_nmap.sh["{HOST.CONN}"]
    Type of information: Text

Пример запуска скрипта на удаленной системе

server# service zabbix-server stop
server# service zabbix-agent stop
server# service zabbix-server start
server# service zabbix-agent start

server# sudo -u zabbix bash

$ ssh-keygen

$ ssh-copy-id root@gate

$ ssh root@gate hostname
$ ssh root@gate /usr/local/bin/dhcp_stat.sh CUR

$ ssh root@gate /usr/local/bin/dhcp_stat.sh MAX

# cat /etc/zabbix/externalscripts/dhcp_stat_ext.sh
#!/bin/sh
ssh root@$1 /usr/local/bin/dhcp_stat.sh $2
/etc/zabbix/externalscripts/dhcp_stat_ext.sh gate CUR
gate->Items
  Name: DHCP stat CUR
  Type: External check
  Key: dhcp_stat_ext.sh["{HOST.CONN}",CUR]

Элементы типа trapper

Пример целочисленного элемента

Name: my item
Type: Zabbix trapper
Key:  my.item
Allowed hosts: 127.0.0.1
$ zabbix_sender -z 127.0.0.1 -p 10051 -s server -k my.item -o 1

Пример текстового элемента

Name: my nmap
Type: Zabbix trapper
Key:  my.nmap
Type of information: Text
Allowed hosts: 127.0.0.1
# zabbix_sender -z 127.0.0.1 -p 10051 -s val.bmstu.ru -k my.nmap -o "$(/etc/zabbix/externalscripts/detect_host_nmap.sh val.bmstu.ru)"

  или

# zabbix_sender -z 127.0.0.1 -p 10051 -s val.bmstu.ru -k my.nmap -o "$(/usr/lib/zabbix/externalscripts/detect_host_nmap.sh val.bmstu.ru)"

Вычисляемые элементы

ya.ru->Items
  Name: avg perf http
    Type: Calculated
    Key:  avg.perf.http
    Formula: avg(net.tcp.service.perf[https],5m)
    Type of information: Numeric (float)


gate->Items
  Name: dhcp stat cur
    Type: Zabbix agent
    Key: dhcp.stat[CUR]

  Name: dhcp stat max
    Type: Zabbix agent
    Key: dhcp.stat[MAX]
    
  Name: DHCP stat CUR MAX percent
    Type: Calculated
    Key:  DHCP.stat.CUR.MAX.percent
    Formula: last(dhcp.stat[CUR])/last(dhcp.stat[MAX])*100

Web сценарии

Configuratin->Hosts->server
  Web scenarios
    Scenario
      Name: call
    Steps
      Name: call 1
      URL: http://server.corpX.un/asterisk/call.php?phone=301
      Required status codes: 200

Настройка триггеров

Примеры простых целочисленных триггеров

Host: server
    Name: gate.isp.un is unreachable
    Expression: {server:icmpping[gate.isp.un].last()}=0
    Severity: High

    Name: RDP service on client1 is not available
    Expression: {server:net.tcp.service[tcp,192.168.X.101,3389].last()}=0
    Severity: Warning

Host: ya.ru                                                      или val.bmstu.ru
    Name: HTTPS service on {HOST.NAME} is not available
    Expression: {ya.ru:net.tcp.service.perf[https].last()}=0     или val.bmstu.ru

    Dependencies: Zabbix server: gate.isp.un is unreachable   
        !!!Можно добавить после эксперимента с недоступностью gate.isp.un и двумя, сработавшими триггерами

    Severity: Average

Пример триггера основанного на значении элемента в течении периода

Host: ya.ru                                                       или val.bmstu.ru
    Name: HTTP service on {HOST.NAME} is slow
    Expression: {ya.ru:net.tcp.service.perf[https].avg(5m)}>0.6    или val.bmstu.ru !!!Значение подобрать на основе графика
    Severity: Warning

Пример с макросами и Recovery expression

    Name: On {HOST.NAME} dhcp subnet is full
    Problem expression: {Template App DHCP Service:dhcp.stat[CUR].last()}/{Template App DHCP Service:dhcp.stat[MAX].last()}*100>{$DHCP.POOLS.MAX.PERCENT}
    Recovery expression: {Template App DHCP Service:dhcp.stat[CUR].last()}/{Template App DHCP Service:dhcp.stat[MAX].last()}*100<{$DHCP.POOLS.OK.PERCENT}
    Description:
      В заканчиваются адреса.
      Израсходовано более {$DHCP.POOLS.MAX.PERCENT} процентов.

Пример с текстовым элементом

Name: Host {HOST.NAME} nmap change
Severity: Warning
Expression: {gate:detect_host_nmap.sh["{HOST.CONN}"].diff()}=1

Пользовательские графики

Configuration->Hosts->ya.ru->Graphs->Create graph             или val.bmstu.ru
  Name: perf http
  Y axis MIN value: Fixed 0
  Items
    ya.ru: avg perf http                                      или val.bmstu.ru
    ya.ru: check perf http                                    или val.bmstu.ru
  Draw style: Bold Line

Мониторинг с использованием Zabbix agents

Установка агента в Debian/Ubuntu

# apt install zabbix-agent

Пассивный режим

Проверка связи с агентом:

$ zabbix_get -s IP/DNSNAME -p 10050 -k agent.version

Список элементов данных агента:

# zabbix_agentd -p

Минимальная конфигурация агента, включая PSK

gate# grep -v '^#\|^$' /etc/zabbix/zabbix_agentd.conf
PidFile=/var/run/zabbix/zabbix_agentd.pid
LogFile=/var/log/zabbix-agent/zabbix_agentd.log
LogFileSize=0
Server=server
ListenPort=10050

# Hostname=Zabbix server
# must match hostname as configured on the server
# Иначе в журнале будут сообщения: cannot send list of active checks


#TLSConnect=psk
#TLSAccept=psk
##TLSAccept=unencrypted,psk
#TLSPSKFile=/etc/zabbix/zabbix_agentd.psk
#TLSPSKIdentity=gate
gate# openssl rand -hex 32 > /etc/zabbix/zabbix_agentd.psk

gate# scp /etc/zabbix/zabbix_agentd.psk server:gate.psk

gate# service zabbix-agent restart

server# zabbix_get -s gate -k agent.version --tls-connect=psk --tls-psk-identity="gate" --tls-psk-file=gate.psk

Установка агента в Freebsd

gate# pkg install zabbix3-agent

gate# cat /usr/local/etc/zabbix3/zabbix_agentd.conf
LogFile=/tmp/zabbix_agentd.log
Server=server
#UserParameter=dhcp.stat,rsh router show ip dhcp binding | grep 192.168 | wc -l

Активный режим

Установка агента в Windows

Template App Zabbix Agent Active - Linked to - Template OS Windows Active

Items
  Zabbix agent (active)

Discovery rules
  Mounted filesystem discovery - Type - Zabbix agent (active)
    	Item prototypes - Free disk space on... - Zabbix agent (active)
        
  Network interface discovery - Type - Zabbix agent (active)
    ...

Configuration - Create Actions - Auto registration 
  Name: Add windows clients
  Conditions: Host name like CLIENT
  Action operations: Add to host groups: windows clients
  Link to templates: Template OS Windows Active
adminshell> nodepad++ C:\zabbix\zabbix_agentd.conf
LogFile=C:\zabbix\zabbix_agentd.log

#Server=server

#ListenIP=0.0.0.0
#StartAgents=0
#ServerActive=server
adminshell> C:\zabbix\bin\win32\zabbix_agentd.exe -h

adminshell> C:\zabbix\bin\win32\zabbix_agentd.exe -c C:\zabbix\zabbix_agentd.conf -f

adminshell> C:\zabbix\bin\win32\zabbix_agentd.exe -c C:\zabbix\zabbix_agentd.conf -i

Использование UserParameter

# cat zabbix_agentd.conf
...
UserParameter=dhcp.stat[*],/usr/local/bin/dhcp_stat.sh $1
...
TLSAccept=unencrypted,psk    #for convenience
...
server# zabbix_get -s gate -k dhcp.stat[CUR]
server# zabbix_get -s gate -k dhcp.stat[MAX]
  • Windows examples
C:\> notepad PATH_TO\zabbix_agentd.conf
...
UnsafeUserParameters=1
UserParameter=dir[*],dir $1
UserParameter=runcommand[*],$1
UserParameter=lmstat[*],C:\Progra~1\PTC\flexnet\bin\lmutil lmstat -a -c $1

Мониторинг по протоколу SNMP

# service zabbix-server restart

Автоматическое добавление

Configuration->Discovery
Discovery rules
  Name: Local network
  IP range: 172.16.1.190-199, 192.168.X.11-20
  Checks: 
    Check type: SNMPv2 agent 
    SNMP community: public
    SNMP OID .1.3.6.1.2.1.1.5.0
      или
             SNMPv2-MIB::sysName.0
    Add
  Device uniqueness criteria: IP address
  Enabled: yes

Configuration->Actions
  Event source: Discovery
    Name: Action add snmp device to zabbix
    Conditions: 
      Received value: like switch
      Received value: like router
      Add
    Operations: 
      Add to host groups: Discovered hosts
      Link to templates: 
             3.XX Template SNMP Device
             4.XX Template Module Generic SNMPv2
             4.XX Template Module Interfaces Simple SNMPv2
    Add

Проверки через SSH

Обработка SNMPTRAP

# apt install snmptt

# systemctl disable snmptt

# systemctl stop snmptt

# cat /etc/snmp/snmptt.conf
EVENT general .* "General event" Normal
FORMAT ZBXTRAP $aA $ar
# cat /etc/snmp/snmptt.ini
...
date_time_format = %H:%M:%S %Y/%m/%d
...
#log_file = /var/log/snmptt/snmptt.log
log_file = /tmp/my_zabbix_traps.tmp
...
# cat /etc/snmp/snmptrapd.conf
traphandle default snmptt

authCommunity execute writetrap
# cat /lib/systemd/system/snmptrapd.service
...
ExecStart=/usr/sbin/snmptrapd -Lsd -f -On
...
# systemctl daemon-reload
# service snmptrapd restart

Создание своих шаблонов

  • Пример с использованием макроса
Configuration
  Templates
    Template App SSH Service
  Full Clone
    Template App SSH Port Service
  Add

  Templates
    Template App SSH Port Service
      Items
        SSH service is running
          Key: net.tcp.service[ssh,,{$SSH_PORT}]
      Macros
        {$SSH_PORT}=22

Low-Level Discovery (LLD)

server# zabbix_get -s gate -k vfs.fs.discovery | jq

server# zabbix_get -s gate -k vfs.fs.size[/,free]


server# zabbix_get -s gate -k net.if.discovery | jq

server# zabbix_get -s gate -k net.if.in[eth0]
gate# cat /etc/zabbix/dhcp-pools-discovery.sh
#!/bin/bash

echo -n '{"data":['

str=`/usr/bin/dhcpd-pools -c /etc/dhcp/dhcpd.conf -f x | \
/usr/bin/xmlstarlet sel -T -t -m '//shared-network' \
-o '{"{#POOLNAME}":"' -v location -o '"},'`

echo -n ${str::-1}

echo -n ']}'
# /etc/zabbix/dhcp-pools-discovery.sh | jq

# cat /etc/zabbix/dhcp-pools-shared-network.sh
#!/bin/sh

res_field=2
test "x$2" = "xused" && res_field=3

/usr/bin/dhcpd-pools -c /etc/dhcp/dhcpd.conf -f x | \
  /usr/bin/xmlstarlet sel -T -t -m '//shared-network' \
  -v location -o ' ' -v defined -o ' ' -v used -n | \
  grep $1 | cut -d ' ' -f $res_field
gate# /etc/zabbix/dhcp-pools-shared-network.sh LAN1 defined

gate# /etc/zabbix/dhcp-pools-shared-network.sh LAN2 used

gate# cat /etc/zabbix/zabbix_agentd.conf
...
UserParameter=dhcp.pools.discovery,/etc/zabbix/dhcp-pools-discovery.sh

UserParameter=dhcp.pools.shared-network[*],/etc/zabbix/dhcp-pools-shared-network.sh $1 $2
server# zabbix_get -s gate -k dhcp.pools.discovery | jq

server# zabbix_get -s gate -k dhcp.pools.shared-network[LAN2,used]
Configuration->Templates->Create template
  Template name: Template App DHCP Pools
  Groups In groups: Templates

  Macros: {$DHCP.POOLS.MAX.PERCENT}=90
Add

  Applications: DHCP
  
  Discovery rules
    Name: Search DHCP Pools
    Type: Zabbix Agent
    Key: dhcp.pools.discovery
  Add
    Item prototypes
      Name: DHCP Pool $1 max addr
      Type: Zabbix Agent
      Key: dhcp.pools.shared-network[{#POOLNAME},defined]
      Applications: DHCP
    Add

      Name: DHCP Pool $1 cur addr
      Type: Zabbix Agent
      Key: dhcp.pools.shared-network[{#POOLNAME},used]
      Applications: DHCP
    Add

    Graph prototypes
      Name: DHCP Pool {#POOLNAME} max cur
      Y axis MIN value: Fixed 0
      Items: 
        Template App DHCP Pools: DHCP Pool {#POOLNAME} cur addr
        Template App DHCP Pools: DHCP Pool {#POOLNAME} max addr

    Trigger prototypes
      Name: On {HOST.NAME} in the DHCP pool {#POOLNAME}
      Expression: {Template App DHCP Pools:dhcp.pools.shared-network[{#POOLNAME},used].last()}/{Template App DHCP Pools:dhcp.pools.shared-network[{#POOLNAME},defined].last()}*100 > {$DHCP.POOLS.MAX.PERCENT}
      Severity: Warning

Экспорт/импорт в XML

Configuration
  Templates
    Export/Import
<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
    <version>3.0</version>
    <date>2018-07-26T11:10:12Z</date>
    <groups>
        <group>
            <name>Templates</name>
        </group>
    </groups>
    <templates>
        <template>
            <template>Template App DHCP Pools</template>
            <name>Template App DHCP Pools</name>
            <description/>
            <groups>
                <group>
                    <name>Templates</name>
                </group>
            </groups>
            <applications>
                <application>
                    <name>DHCP</name>
                </application>
            </applications>
            <items/>
            <discovery_rules>
                <discovery_rule>
                    <name>Search DHCP Pools</name>
                    <type>0</type>
                    <snmp_community/>
                    <snmp_oid/>
                    <key>dhcp.pools.discovery</key>
                    <delay>30</delay>
                    <status>0</status>
                    <allowed_hosts/>
                    <snmpv3_contextname/>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authprotocol>0</snmpv3_authprotocol>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privprotocol>0</snmpv3_privprotocol>
                    <snmpv3_privpassphrase/>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <filter>
                        <evaltype>0</evaltype>
                        <formula/>
                        <conditions/>
                    </filter>
                    <lifetime>30</lifetime>
                    <description/>
                    <item_prototypes>
                        <item_prototype>
                            <name>DHCP Pool $1 max addr</name>
                            <type>0</type>
                            <snmp_community/>
                            <multiplier>0</multiplier>
                            <snmp_oid/>
                            <key>dhcp.pools.shared-network[{#POOLNAME},defined]</key>
                            <delay>30</delay>
                            <history>90</history>
                            <trends>365</trends>
                            <status>0</status>
                            <value_type>3</value_type>
                            <allowed_hosts/>
                            <units/>
                            <delta>0</delta>
                            <snmpv3_contextname/>
                            <snmpv3_securityname/>
                            <snmpv3_securitylevel>0</snmpv3_securitylevel>
                            <snmpv3_authprotocol>0</snmpv3_authprotocol>
                            <snmpv3_authpassphrase/>
                            <snmpv3_privprotocol>0</snmpv3_privprotocol>
                            <snmpv3_privpassphrase/>
                            <formula>1</formula>
                            <delay_flex/>
                            <params/>
                            <ipmi_sensor/>
                            <data_type>0</data_type>
                            <authtype>0</authtype>
                            <username/>
                            <password/>
                            <publickey/>
                            <privatekey/>
                            <port/>
                            <description/>
                            <inventory_link>0</inventory_link>
                            <applications>
                                <application>
                                    <name>DHCP</name>
                                </application>
                            </applications>
                            <valuemap/>
                            <logtimefmt/>
                            <application_prototypes/>
                        </item_prototype>
                        <item_prototype>
                            <name>DHCP Pool $1 cur addr</name>
                            <type>0</type>
                            <snmp_community/>
                            <multiplier>0</multiplier>
                            <snmp_oid/>
                            <key>dhcp.pools.shared-network[{#POOLNAME},used]</key>
                            <delay>30</delay>
                            <history>90</history>
                            <trends>365</trends>
                            <status>0</status>
                            <value_type>3</value_type>
                            <allowed_hosts/>
                            <units/>
                            <delta>0</delta>
                            <snmpv3_contextname/>
                            <snmpv3_securityname/>
                            <snmpv3_securitylevel>0</snmpv3_securitylevel>
                            <snmpv3_authprotocol>0</snmpv3_authprotocol>
                            <snmpv3_authpassphrase/>
                            <snmpv3_privprotocol>0</snmpv3_privprotocol>
                            <snmpv3_privpassphrase/>
                            <formula>1</formula>
                            <delay_flex/>
                            <params/>
                            <ipmi_sensor/>
                            <data_type>0</data_type>
                            <authtype>0</authtype>
                            <username/>
                            <password/>
                            <publickey/>
                            <privatekey/>
                            <port/>
                            <description/>
                            <inventory_link>0</inventory_link>
                            <applications>
                                <application>
                                    <name>DHCP</name>
                                </application>
                            </applications>
                            <valuemap/>
                            <logtimefmt/>
                            <application_prototypes/>
                        </item_prototype>
                    </item_prototypes>
                    <trigger_prototypes>
                        <trigger_prototype>
                            <expression>{Template App DHCP Pools:dhcp.pools.shared-network[{#POOLNAME},used].last()}/{Template App DHCP Pools:dhcp.pools.shared-network[{#POOLNAME},defined].last()}*100 &gt; {$DHCP.POOLS.MAX.PERCENT}</expression>
                            <name>On {HOST.NAME} in the DHCP pool {#POOLNAME}</name>
                            <url/>
                            <status>0</status>
                            <priority>2</priority>
                            <description/>
                            <type>0</type>
                            <dependencies/>
                        </trigger_prototype>
                    </trigger_prototypes>
                    <graph_prototypes>
                        <graph_prototype>
                            <name>DHCP Pool {#POOLNAME} max cur</name>
                            <width>900</width>
                            <height>200</height>
                            <yaxismin>0.0000</yaxismin>
                            <yaxismax>100.0000</yaxismax>
                            <show_work_period>1</show_work_period>
                            <show_triggers>1</show_triggers>
                            <type>0</type>
                            <show_legend>1</show_legend>
                            <show_3d>0</show_3d>
                            <percent_left>0.0000</percent_left>
                            <percent_right>0.0000</percent_right>
                            <ymin_type_1>1</ymin_type_1>
                            <ymax_type_1>0</ymax_type_1>
                            <ymin_item_1>0</ymin_item_1>
                            <ymax_item_1>0</ymax_item_1>
                            <graph_items>
                                <graph_item>
                                    <sortorder>0</sortorder>
                                    <drawtype>0</drawtype>
                                    <color>1A7C11</color>
                                    <yaxisside>0</yaxisside>
                                    <calc_fnc>2</calc_fnc>
                                    <type>0</type>
                                    <item>
                                        <host>Template App DHCP Pools</host>
                                        <key>dhcp.pools.shared-network[{#POOLNAME},used]</key>
                                    </item>
                                </graph_item>
                                <graph_item>
                                    <sortorder>1</sortorder>
                                    <drawtype>0</drawtype>
                                    <color>F63100</color>
                                    <yaxisside>0</yaxisside>
                                    <calc_fnc>2</calc_fnc>
                                    <type>0</type>
                                    <item>
                                        <host>Template App DHCP Pools</host>
                                        <key>dhcp.pools.shared-network[{#POOLNAME},defined]</key>
                                    </item>
                                </graph_item>
                            </graph_items>
                        </graph_prototype>
                    </graph_prototypes>
                    <host_prototypes/>
                </discovery_rule>
            </discovery_rules>
            <macros/>
            <templates/>
            <screens/>
        </template>
    </templates>
</zabbix_export>

API

Аутентификация

server.corp1.un:~# apt install curl

server.corp1.un:~# curl -s -k -X POST -H 'Content-Type: application/json-rpc' -d '
{
   "jsonrpc": "2.0",
   "method": "user.login",
   "params": {
      "user": "Admin",
      "password": "zabbix"
   },
   "id": 1
} ' http://127.0.0.1/zabbix/api_jsonrpc.php
{"jsonrpc":"2.0","result":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","id":1}

Работа с объектами host/template

  • Утилита для обработки JSON
server.corp1.un:~# apt install jq
  • Получение списка идентификаторов и имен коммутаторов из Zabbix
server.corp1.un:~# curl -s -k -X POST -H 'Content-Type: application/json-rpc' -d '
{
    "jsonrpc": "2.0",
    "method": "host.get",
    "params": {},
    "auth": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "id": 2
} ' http://127.0.0.1/zabbix/api_jsonrpc.php | jq
...
  • Варианты параметра «method»
...
    "method": "template.get",
...
...
    "params": {
       "output": "extend"
    },
...
...
    "params": {
        "output": ["hostid", "host"],
        "templateids": ["10299"]
    },
...

Оформление запросов в виде BASH скриптов

server:~# export AUTH=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

server:~# cat /root/zab_get_hosts.sh
#!/bin/sh

curl -s -k -X POST -H 'Content-Type: application/json-rpc' -d "
{
    \"jsonrpc\": \"2.0\",
    \"method\": \"host.get\",
    \"params\": {},
    \"auth\": \"${AUTH}\",
    \"id\": 2
} " http://127.0.0.1/zabbix/api_jsonrpc.php
server:~# /root/zab_get_hosts.sh | jq

Список имен узлов
server:~# /root/zab_get_hosts.sh | jq '.result | .[] | { host: .host} | tostring' | tr -d '{}\\' | tr '"' ' ' | cut -d ' ' -f5

Получение списка карт и их элементов из Zabbix

server.corp1.un:~# cat /root/zab_get_maps.sh
#!/bin/sh

curl -s -k -X POST -H 'Content-Type: application/json-rpc' -d "
{
    \"jsonrpc\": \"2.0\",
    \"method\": \"map.get\",
    \"params\": {
        \"selectLinks\": \"extend\",
        \"selectSelements\": \"extend\"
    },
    \"auth\": \"${AUTH}\",
    \"id\": 2
} " http://127.0.0.1/zabbix/api_jsonrpc.php | jq

Пример изменения конфигурации через Zabbix API

server.corp1.un:~# cat /root/zab_set_map_name.sh
#!/bin/sh

MAPID=$1
MAPNAME=$2

curl -s -k -X POST -H 'Content-Type: application/json-rpc' -d "
{
    \"jsonrpc\": \"2.0\",
    \"method\": \"map.update\",
    \"params\": {
        \"sysmapid\": \"${MAPID}\",
        \"name\": \"${MAPNAME}\"
    },
    \"auth\": \"${AUTH}\",
    \"id\": 2
} " http://127.0.0.1/zabbix/api_jsonrpc.php
server.corp1.un:~# /root/zab_set_map_name.sh 2 "Super MAP"
сервис_zabbix.txt · Последние изменения: 2019/06/26 11:32 — val