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

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


сервис_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
#end newline!!!
# 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

# 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

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

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

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

Настройка подсистемы Email

Administration->Media types->Email
  SMTP server: mail.isp.un
  SMTP helo: server.corpX.un
  SMTP email: zabbix@server.corpX.un

Administration->Users->Admin или userX->Media
  Type: email
  Send to: userX@isp.un

Настройка уведомлений о срабатывании триггеров по Email

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

Отчет об отправленных сообщениях

Reports -> Action log

Добавление информации о значении элемента в сообщение

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

    Operations:
      Default message
...
{ITEM.NAME1} ({HOST.NAME1}:{ITEM.KEY1}): 

Current:

{ITEM.VALUE1}

Previous:

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

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

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 admin/host windows
    Type: Simple check
    Key: net.tcp.service[tcp,192.168.X.5,3389]
    Applications: Service check

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

server# zabbix_server --help | grep ExternalScripts

server# less /etc/zabbix/zabbix_server.conf
...
Timeout=...
...
server# mkdir /etc/zabbix/externalscripts

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

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

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

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

server# less /etc/sudoers.d/zabbix
zabbix ALL = (ALL) NOPASSWD: /usr/bin/nmap -O *
server# cat /etc/zabbix/externalscripts/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

zabbix@server:~$ ssh-keygen

zabbix@server:~$ ssh-copy-id root@gate

zabbix@server:~$ ssh root@gate hostname
zabbix@server:~$ ssh root@gate /usr/local/bin/dhcp_stat.sh CUR

zabbix@server:~$ ssh root@gate /usr/local/bin/dhcp_stat.sh MAX

server# cat /etc/zabbix/externalscripts/dhcp_stat_ext.sh
#!/bin/sh
ssh root@$1 /usr/local/bin/dhcp_stat.sh $2
zabbix@server:~$ /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

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

hostN->Items
  Name: my item
    Type: Zabbix trapper
    Key:  my.item
    Allowed hosts: 127.0.0.1, 192.168.X.0/24
$ zabbix_sender -z server -p 10051 -s hostN -k my.item -o 1

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

val.bmstu.ru->Items
  Name: my nmap
    Type: Zabbix trapper
    Key:  my.nmap
    Type of information: Text
    Allowed hosts: 127.0.0.1
server# zabbix_sender -z 127.0.0.1 -p 10051 -s val.bmstu.ru -k my.nmap -o "$(nmap -O val.bmstu.ru)"
server# cat /root/detect_host_nmap.sh
#!/bin/sh
/usr/bin/nmap -O $1 | grep -v 'Starting Nmap\|Host is up\|Nmap done\|Network Distance'
server# chmod +x /root/detect_host_nmap.sh
server# zabbix_sender -z 127.0.0.1 -p 10051 -s val.bmstu.ru -k my.nmap -o "$(/root/detect_host_nmap.sh val.bmstu.ru)"

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

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

#---------------------

gate.corpX.un->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
    
#---------------------

last(openvpn1:openvpn.server.clients)+last(openvpn2:openvpn.server.clients)+last(openvpn2:openvpn.server.clients)

Web сценарии

или просто:

  • Web сценарии (обзор значений в Latest data позволит создать соответствующие триггеры)
# tail -f /var/log/apache2/access.log  | grep ast
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 
    Name: HTTPS service on {HOST.NAME} is not available
    Expression: {ya.ru:net.tcp.service.perf[https].last(#2)}=0

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

    Severity: Average

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

Host: ya.ru                                       
    Name: HTTP service on {HOST.NAME} is slow
    Expression: {ya.ru:net.tcp.service.perf[https].avg(5m)}>0.4  


    Expression: {ya.ru:my.avg.perf.http.last()}>0.4

    Значение подобрать на основе графика
    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.corpX.un:detect_host_nmap.sh["{HOST.CONN}"].diff()}=1
  или
Expression: {val.bmstu.ru:my.nmap.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

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

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

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

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

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

# zabbix_agentd -p

# zabbix_agentd -p | grep vfs.fs.size

Минимальная конфигурация агента, включая 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

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

Клонирование шаблона для 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 - Actions - Auto registration 
  Name: Add windows clients
  Conditions: Host name contains CLIENT
  Action operations: Add to host groups: windows clients
  Link to templates: Template OS Windows Active
                     Template OS Windows list installed soft Active
  Set host inventory mode: Automatic
Настройка агента на активный режим
...
#Server=server
...
ListenIP=0.0.0.0
...
StartAgents=0
...
ServerActive=server
...

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

gate# cat /etc/zabbix/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
...
Timeout=30

UserParameter=listinstalledsoft,powershell -Command Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall; powershell -Command Get-ChildItem HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

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
  Update interval: 5m
  Device uniqueness criteria: IP address  
  Enabled: yes

Configuration->Actions
  Event source: Discovery
    Name: Action add snmp device to zabbix
    Conditions: 
      Received value: like или contains router
      Discovery status: equals Up                 без этого появляются ghost hosts :)
      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
      Set host inventory mode: Automatic
    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}]
          Update interval: 30s
      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 vfs.fs.size[/,total]
server# zabbix_get -s gate -k vfs.fs.size[/,used]
...

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

server# zabbix_get -s gate -k net.if.in[eth0]
...

Статистика дискового ввода/вывода

  • Пример использования встроенных средств для LLD
agent# zabbix_agentd -p | grep vfs.dev
...

server# zabbix_get -s agent -k "vfs.dev.read[sda,sps]"
...

agent# cat /etc/zabbix/zabbix_agentd.conf.d/my.linux.disk.discovery.conf
UserParameter=my.disks.discovery,/bin/lsblk -dJ | /bin/sed -e 's/blockdevices/data/' -e 's/name/{#NAME}/g' -e 's/type/{#TYPE}/g'
server# zabbix_get -s agent -k my.disks.discovery | jq
...
Configuration->Templates->Create template
  Template name: My Template Linux disks utilization
  Groups: Templates/Server hardware

  Discovery rules->
    Name: my disks discovery
    Key: my.disks.discovery
    Filters->
      {#TYPE} matches disk
    Item prototypes->
      Name: disk {#NAME} read bytes
      Key: vfs.dev.read[{#NAME},sps]
      Type of information: Numeric (float)
      Units: Байт
      Preprocessing->
        Preprocessing steps
        Custom multiplier 512

      Name: disk {#NAME} write bytes
      ...  

Статистика DHCP сервера

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 ']}'
gate# /etc/zabbix/dhcp-pools-discovery.sh | jq

gate# 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/Applications

  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      или DHCP Pool {#POOLNAME} 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

API

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

server:~# apt install curl

server:~# 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:~# apt install jq
  • Получение списка узлов и шаблонов из Zabbix
server:~# 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": "template.get",
...
...
    "params": {
        "output": ["hostid", "host"],
        "templateids": ["10NNN"]
    },
...

Оформление запросов в виде 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 · Последние изменения: 2020/07/30 14:10 — val