Долгое время для добавления в Zabbix информации об операционной системе использовал вывод команды lsb_release, но приходилось создавать на хостах в каталоге zabbix агента дополнительный скрипт для парсинга вывода. Вскоре заметил что в новых версиях Debian ещё и требуется ставить пакет lsb-release. И тут закралась коварная мысль — можно ли справиться с ситуацией стандартными средствами Zabbix и без дополнительных скриптов и пакетов? Как вы поняли по названию статьи — да, можно!
- Zabbix monitoring key entry using summary
- Intelligent Recommendation
- The port of the Zabbix monitoring server is using
- Zabbix add mysql monitoring summary
- [zabbix] custom monitoring item key value
- Zabbix custom key tcp connection monitoring
- <span href="https://www.programmersought.com/article/19053916362/" rel="bookmark" title="Zabbix monitoring custom key value»> Zabbix monitoring custom key value
- More Recommendation
- zabbix key monitoring mysal, nginx, php
- Zabbix updates the key value of Item monitoring
- Copyright DMCA © 2018-2023 — All Rights Reserved — www.programmersought.com User Notice
- Идентификация ОС. Версия 1.
- Third, built-in monitoring items list
- agent.hostname
- agent.ping
- agent.version
- kernel.maxfiles
- kernel.maxproc
- log[file,
- logrt[file_pattern,
- net.if.discovery
- net.if.in[if,
- net.if.out[if,
- net.if.total[if,
- net.tcp.listen[port]
- net.tcp.port[
- net.tcp.service[service,
- net.tcp.service.perf[service,
- proc.mem[
- proc.num[
- system.boottime
- system.cpu.intr
- system.cpu.load[
- system.cpu.num[
- system.cpu.switches
- system.cpu.util[
- system.hostname[
- system.hw.cpu[
- system.hw.devices[
- system.hw.macaddr[
- system.localtime[
- system.run[command,
- system.sw.arch
- system.sw.os[
- system.sw.packages[
- system.swap.in[
- system.swap.out[
- system.swap.size[
- system.uname
- system.uptime
- system.users.num
- vfs.dev.read[
- vfs.dev.write[
- vfs.file.cksum[file]
- vfs.file.exists[file]
- vfs.file.md5sum[file]
- vfs.file.regexp[file,regexp,
- vfs.file.regmatch[file,regexp,
- vfs.file.size[file]
- vfs.file.time[file,
- vfs.fs.discovery
- vfs.fs.inode[fs,
- vfs.fs.size[fs,
- vm.memory.size[
- web.page.get[host,
- web.page.perf[host,
- web.page.regexp[host,
- Идентификация ОС. Версия 2.
- First, built-in Key description
Zabbix monitoring key entry using summary
The key range (Chinese) Documentation: https: //www.zabbix.com/documentation/4.0/zh/manual/appendix/items/supported_by_platform
Using the command line to see if support:
# Use zabbix_get testzabbix_get -s 192.168.4.35 -k # Use zabbix_agentd, client command to view the support of keyzabbix_agentd -p vfs.fs.size - CPU
- linux card
- Disk
- RAM
- Common key
Intelligent Recommendation
![]()
The port of the Zabbix monitoring server is using
![]()
Zabbix add mysql monitoring summary
![]()
[zabbix] custom monitoring item key value
Zabbix custom key tcp connection monitoring
![]()
<span href="https://www.programmersought.com/article/19053916362/" rel="bookmark" title="Zabbix monitoring
custom key value»> Zabbix monitoring
custom key value
More Recommendation
zabbix key monitoring mysal, nginx, php
Zabbix updates the key value of Item monitoring
Copyright DMCA
© 2018-2023 — All Rights Reserved — www.programmersought.com
User Notice
Top
The function items of zabbix monitoring, some of the monitoring content does not exist (such as the reading speed of the hard disk), I want to use the existing module to complete the monitoring, here consider other key values that zabbix already exists to see if it can meet the demand;
The zabbix4.4 version is used here to describe the key (key), other lower versions may not support it;
2. Key value description
1) Description of all key values
For all the key values of zabbix4.4, please check【Reference 1】
Based on these values, think about whether there are other key values, complete the monitoring of the speed of the hard disk, and find other key values of the hard disk on the official website according to this idea;
vfs.dev.discovery vfs.dev.read[<device>,<type>,<mode>] vfs.dev.write[<device>,<type>,<mode>]
But according to the three parameters found on the official website, it is different from the key value in the figure below. I thought about whether a few values existed and tested it with the command;
[xxx@xxxxxxx ~]$ zabbix_get -s 127.0.0.1 -p 10050 -k 'vfs.dev.read.rate[vda]' ZBX_NOTSUPPORTED: Unsupported item key. [xxx@xxxxxxx ~]$
Attachment: I also used the three parameters found, but I can’t solve the problem of hard disk read and write speed;

3. How to use more keys
Although zabbix4.4 has provided hard disk write times, read times, utilization, waiting time, etc., but there is no Mbps rate; I hope to use zabbix’s existing key value to complete the monitoring of other hard disks. After all, Mbps is easier to understand It can also be associated with the network speed. Check whether 12 hard disks are raid5 under the optical fiber network. When large traffic is written, it is a hard disk problem, a network speed problem, a software problem, or a switch problem; (finally it is a software problem. The client side is configured with compression parameters. Хотя на стороне сервера настроено игнорирование определенных файлов без сжатия, это все же влияет на скорость передачи)
1) Узнайте больше параметров zabbix4.4
В процессе написания этой статьи я вручную внедрил скрипт zabbix, файл конфигурации zabbix и конфигурацию zabbixweb в три шага, чтобы завершить мониторинг Мбит/с жесткого диска, но это очень неудобно (есть ошибка, первая строка данных в IOstat Это исторические данные, а не данные в реальном времени); при этом я также знаю, что данные команды iostat для мониторинга IO находятся в /proc/diskstats, и я также проверил значение столбцов /proc/diskstats, но в /proc нет скорости скачивания Mbps /diskstats, скорость чтения, полученная командой iostat, рассчитывается на основе данных /proc/diskstats;
vfs.file.contents[file,] # Просмотр содержимого файла vfs.file.size[file] # Просмотр размера файла (папки)
2) Использование параметров
Сначала посмотрите на шаблон, чтобы увидеть, как это написано в шаблоне; просмотреть значение шаблона, результат шаблона, все части шаблона (включая процесс, правила самообнаружения) и просмотреть все содержимое шаблона, содержащего ключ;

js на картинке ниже преобразует содержимое в /proc/diskstats в коллекцию массива карт;

На рисунке ниже вы можете увидеть данные, запрашиваемые в соответствии со значением ключа. Вы можете видеть, что данные в формате json.


Невозможно получить единственное значение этого ключа сверху;
Продолжить поиск других изображений и найти «тип: связанные элементы», согласно анализу, это единственные данные, которые могут получить указанное выше ключевое значение;


4. Больше вариантов использования ключевых значений
Объясните разницу между «изменением каждую секунду» и «простым изменением» на примере








Идентификация ОС. Версия 1.
Задача представляет больший академический интерес, так как информация по операционным системам хостов проще и логичнее собирает средства оркестровки типа ansible, что я обычно и делаю. Но Zabbix сервер так же не лыком шит и умеет отображать нужные элементы (элементы) у развертывания хостов в одном окне, что быстро и удобно.
В системе есть файл /etc/os-release, в котором много полезной информации в виде ключ=значение. Полное его описание лучше прочесть в os-release — Идентификация операционной системы
.
. Значения присваивания переменной должны быть заключены в двойные или одинарные кавычки, если они содержат пробелы, точки с запятой или другие специальные символы за пределами A-Z, a-z, 0-9.
Вот небольшой пример из мира Дебиан
PRETTY_NAME=»Debian GNU/Linux 10 (бастер)»
VERSION_CODENAME=бастер
ID=дебиан
Самое главное, что vfs.file.regexp в качестве возвращаемого значения отдаёт совпадающую подстроку. То что нужно! Но помните поговорку? Если у вас есть проблема и вам пришла в голову идея, которую можно решить с помощью регулярных выражений, то теперь у вас есть две проблемы. 
. Удалось с помощью Гугла и такой-то матери родить набор знаков, извлекающее необходимое значение в различных вариантах — без кавычек, с одинарными или внедрени.
- Требования к шаблонам и особенностям элементов внутри разнятся от версии к версии Zabbix, поэтому с прицелом на будущее всё заточил под 5+ версию. Если у вас Zabbix еще не тот калибр, то уже самостоятельно конвертируйте шаблон в нужное вам.
- Ключей в /etc/os-release много и много дистроспецифичных. Выбрал некоторые и общие.
- Информация в /etc/os-release может меняться только при обновлении системы. Например, Убунту при появлении новых релизных точек (вех) может отобразить этот факт в виде строки Ubuntu 18.04.5 LTS, а «завтра» Ubuntu 18.04.6 LTS. Частота опроса выставлена в 1 день (1d).
- Неявно ожидается что для хостов вы используете стандартный шаблон Template OS Linux, который даёт раздел OS. Данные шаблона Template_OSI.xml так же можно найти в разделе OS.
Third, built-in monitoring items list
agent.hostname
Returns the name of the monitored end (string) Use the way: The way is used later: root@BJ-monitor-h-01 bin# zabbix_get -s 192.168.10.100 -k agent.hostname Zabbix server agent.ping
Detection is survived by the survived end (1: Other: Unbound) Use the function nodata () to detect if the client is running agent.version
Zabbix Agent version string kernel.maxfiles
System supports the largest Open files integer kernel.maxproc
System supports the maximum number of processes log[file,
Monitor log file FILE - File Detailed Path Regexp - Regular Encoding - Code Maxlines - Zabbix Agent sends the maximum number of rows to Server or Proxy. This parameter covers the 'maxlinespersecond' in zabbxi_agentd.conf Mode - Optional Value: All (default), SKIP (Skip processing old data). Mode parameter starts from version 2.0 Output - Optional, Output Format Template. Example: log [/ var / log / syslog] log [/ var / log / syslog, error] log [/ home / zabbix / logs / logfile ,, 100] logrt[file_pattern,
Monitoring of log file with log rotation support. FILE_PATTERN - File absolute path net.if.discovery
List the network card. Usually used for low-level discovery.json objects net.if.in[if,
NIC entry traffic integer. IF - Net card name Mode - available value: Bytes - bytes (default) Packets - package number Errors - Error quantity Dropped - packet loss quantity Example Keys: Net.if.in [Eth0, Errors] Net.if.in [eth0] net.if.out[if,
NIC export traffic (parameter see Net.If.in) net.if.total[if,
The sum of the network cards / out of the flow (parameters see Net.If.in) net.tcp.listen[port]
Detect the port to open 0 - (Not Listen) 1 - in Listen Stateport Example: net.tcp.listen [80] net.tcp.port[
Whether you can connect to the specified TCP port 0 - Cannot Connect 1 - CAN Connect IP - IP address (default is 127.0.0.1) Port - port Example: Net.tcp.port [, 80] Deterent whether the web server port is running net.tcp.service[service,
The detection service is turned on, and the port can be used with 0 - service 1 - service operation Service - as follows: SSH, NTP, LDAP, SMTP, FTP, HTTP, POP, NNTP, IMAP, TCP, HTTPS, TELNET IP - IP address (default 127.0.0.1) Port - port (default is a standard port number) Example Key: net.tcp.service [ftp ,, 45] net.tcp.service.perf[service,
Detection server performance 0 - service hangs; seconds - link to server port consumption Service - as follows: SSH, NTP, LDAP, SMTP, FTP, HTTP, POP, NNTP, IMAP, TCP, HTTPS, TELNET IP - IP address (default 127.0.0.1) Port - port (default is a standard port number) Example Key: Net.tcp.Service.Perf [ssh] proc.mem[
The memory memory usage (byte unit) consumed by the user process. Name - Process Name (default "all processes") User - User Name (Default "all users") Mode - optional value: AVG, MAX, Min, SUM (default) CMDline - Command line filtering (regular expression) Example Keys: proc.mem [, root] - How much memory consumes root Proc.mem [Zabbix_Server, Zabbix] - How much memory is used by Zabbix_server running
proc.mem[,oracle,max,oracleZABBIX] proc.num[
Number of numbers of processes for certain users of certain users Name - Process Name (Default "All Processes") User - Username (Default "all users") State - Available: All (default), Run, Sleep, Zomb CMDline - Command line filtering (regular expression) Example Keys: proc.num [, mysql] - Number of processes running in mysql users Proc.num [Apache2, WWW-DATA] - How many apache2 processes have been running at WWW-DATA proc.num[,oracle,sleep,oracleZABBIX] Remarks: Windows system only supports both Name and User parameters system.boottime
Timestamp integer in the system .unix timestamp system.cpu.intr
Device interrupt integer system.cpu.load[
CPU load floating point CPU - Available: All (default), Percpu (Load of all online CPUs) Mode - available value: AVG1 (1 minute default), AVG5 (5 minutes average), AVG15 (15 minutes average) Sample Key: system.cpu.load [, avg5] system.cpu.num[
CPU number processor number TYPE - available value: online (default), max example: system.cpu.num system.cpu.switches
Context exchange exchange, old name: system [switches] system.cpu.util[
CPU utilization percentage CPU - CPU number (default is all CPUs) TYPE - Available: IDLE, Nice, User (default), System (Windows System Default), iowait, Interrupt, Softirq, Steal Mode - available value: AVG1 (average average, default), AVG5 (5 minutes average, AVG15 (15 minutes average) Sample Key: System.cpu.util [0, User, Avg5] system.hostname[
Returns the host name string TYPE (for Windows System only) - available value: NetBIOS (default) or host system.hw.cpu[
Returns the CPU information character / number CPU - CPU number or all (default) INFO - FULL (default), Curfreq, MaxFreq, Model or Vendor For example: system.hw.cpu [0, vendor] Authenticamd from / proc / cpuinfo, / sys / devices / system / cpu / [cpunum] / cpufreq / cpuinfo_max_freq Get information. If the number of CPUs and CurfReq or MaxFreq will be specified, will Return the value (Hz). system.hw.devices[
List PCI or USB text values TYPE - PCI (default) or usb Example: System.hw.devices [PCI] 00: 00.0 Host Bridge: Advanced Micro Devices [AMD] RS780 Host Bridge [.] Returns LSPCI or LSUSB (without parameters) system.hw.macaddr[
List the MAC address string Interface - All (default) or regular expression Format - Full (default), Short Example: System.hw.macaddr ["Eth0 $", FULL] [Eth0] 00: 11: 22: 33: 44: 55 lists the specified interface MAC address If the Format is specified as a short, the MAC address will be ignored system.localtime[
System time. Digital or string system.run[command,
Run command text on the developed host Command - command Mode - Wait (Default, Perform timeout), NOWAIT (not waiting) maximum can be used to return 512KB data, including blank data. Command output data must be text For example: system.run ["ls -l /"] - lists / files and directories. Note: Enable this method, Agent configuration file must be configured EnableRemMAVAnds = 1 option system.sw.arch
Return to software information string Example: system.sw.arch system.sw.os[
Returns the system information string
info - full (default), short ,name Example: system.sw.os [short] ubuntu 2.6.35-28.50-generic 2.6.35.11 The information comes as follows:
/proc/version [short]
/proc/version_signature [name]
/etc/issue.net system.sw.packages[
Installed Software List Text Value Package - All (default) or regular expression Manager - All (default) OR A Package Manager Format - Full (default), Short Example: system.sw.packages [http] system.swap.in[
Swapped partition in (Disk Switch to Memory) Number Device - Exchange Partition Equipment (Default ALL) TYPE - Optional value: Count (Swapins), Sectors (Swapped in), Pages (Pages Swapped in).
Example Key: System.swap.in [, Pages] Data collection from: Linux 2.4: / proc / swaps, / proc / partitions, / proc / stat Linux 2.6: /proc/swaps, /proc/diskstats, /proc/vmstat system.swap.out[
SWAP OUT (f memory to disk). Number DEVICE - SWAP device (default ALL) Type - Count (Number of swapouts), Sectors (Sectors Swapped Out), Pages (Pages Swapped Out). Example Key: System.swap.out [, Pages] Data collection from: Linux 2.4: / proc / swaps, / proc / partitions, / proc / stat Linux 2.6: /proc/swaps, /proc/diskstats, /proc/vmstat system.swap.size[
Exchange partition size byte or percentage Device - Exchange Partition (Default ALL)
type - free (free swap space, default), pfree (free swap space, in percent), pused (used swap space, in percent), total (total swap space), used (used swap space) Example System.swap.size [, Pfree] - Free SWAP Percentage system.uname
Return to the host to believe in information. String system.uptime
System running time (seconds) How many seconds use S / UPtime to get system.users.num
How many user Agent uses the who command to get vfs.dev.read[
Disk read status integer, floating point (if Type is as follows) Device - Disk device (default "all") TYPE - Optional value: Sectors, Operations, Bytes, SPS, OPS, BPS (must be specified, different operating systems). SPS, OPS, BYTES PER: SECTORS, OPERATIONS, BYTES Per Second, Respectively Mode - optional value: AVG1, AVG5, AVG15. Remarks: Only Type is SPS, OPS, BPS, the third parameter is supported. TYPE parameters of different operating systems: freebsd - bps linux - SPS OpenBSD - Operations Solaris - Bytes Example Key: vfs.dev.read [, Operations] vfs.dev.write[
Disk write status integer, Device - Disk device (default ALL)
type - sectors, operations, bytes, sps, ops, bps
mode - one of avg1 (default),avg5 , avg15.
example: vfs.dev.write[,operations] Old naming: io vfs.file.cksum[file]
Calculate file verification UNIX CKSUM. File - Full Path
vfs.file.contents[file, If you get the text content, if you are empty, only LF / CR CHARACTERS is returned. File - Full Path For example: vfs.file.contents [/ etc / passwd] files can not exceed 64KB. vfs.file.exists[file]
Detect whether the file exists 1 - there is 0 - does not exist File - Full Path vfs.file.md5sum[file]
File MD5 check code file MD5 hash value File - full path vfs.file.regexp[file,regexp,
Searching in the file contains rows of strings, or empty File - Full Path Regexp - GNU regular expression Encoding - Code START LINE - from which row begins, the default line End line - From which line ends, the default line Such as: vfs.file.Regexp [/ etc / passwd, zabbix] vfs.file.regexp[/path/to/some/file,”([0-9]+)$”,,3,5,\1] vfs.file.regexp[/etc/passwd,^zabbix:.:([0-9]+),,,,\1] vfs.file.regmatch[file,regexp,
Search string 0 in the file - Not found 1 - Find File - Full Path Regexp - GNU regular expression Encoding - Code Start Line - Which line starts, default first line End line - Which row, the default line For example: vfs.file.regmatch [/VAR/LOG /APP.LOG ,EROR] vfs.file.size[file]
File size byte fzabbix must have permission to read this file vfs.file.time[file,
Document time information UNIX timestamp. Mode - Modify (default, modification time), Access - last accessed time, change - final change time For example: vfs.file.time [/ etc / passwd, modify] Remarks: File size has restrictions vfs.fs.discovery
List mounted file systems for LLD.json objects vfs.fs.inode[fs,
Inodes quantity number FS - file system Mode - Total, Free, Used, Pfree, Pused (percentage) For example: vfs.fs.inode [/, pfree] vfs.fs.size[fs,
Disk space, return to the usage byte of the local file system FS - file system Mode - Total, Free, Used, Pfree (Idle Percent), PUSED (Percentage). For example: vfs.fs.size [/ tmp, free] vm.memory.size[
Memory size byte or percentage Mode - Total, Active, Anon, Buffers, Cached, Exec, File, Free, Inactive, Pinned, Shared, Wired, USED, PUSED, AVAILABLE Monitoring item VM.Memory.size [] Allows three types of parameters: The first category: containing Total - total memory Second Category: System Specify Memory Type: Active, Anon, Buffers, Cached, Exec, File, Free, INACTIVE, PINNED, Shared, Wired. Third Category: User Level, How much memory uses, how much memory is available: USED, PUSED, AVAILABLE, PAVAILABLE. web.page.get[host,
Get web content web page source code Host - hostname / domain name PATH - File Address, Default / Port - port, default 80 return empty string indicates failure. For example, Web.Page.Get [ web.page.perf[host,
Get the time long diazo to fully load the web page, return 0 means failure Host - hostname / domain name PATH - HTML address, default is / Port - port, default 80 [root@BJ-monitor-h-01 bin]# ./zabbix_get -s 192.168.10.100 -k web.page.perf[www.baidu.com] web.page.regexp[host,
Searching a string in the web failed to return empty characters (mismatch). Host - host name Path - HTML file path (default) Port - port (default 80) Regexp - GNU regular expression Length - Returns the maximum number of strings
Output - Output Format Template Options. Идентификация ОС. Версия 2.
Первая версия шаблона работает, но где-то в глубоко в душе копошилась мысль, что тема до конца не раскрыта. Дело в том, что у различных дистрибутивов Linux различное количество строк в файле /etc/os-release. Если красиво и элегантно их представить всех в Zabbix у различных серверов с их различными операционными системами на базе Linux, то это автоматически подразумевает использование «Низкоуровневого обнаружения» (Low-level discovery, LLD). Так же нужно было ограничиться лишь средствами Zabbix, не требуя дополнительных скриптов. Такой вызов не мог не остаться мной не замеченным!
Итак, нам нужно для LLD:
- Прочесть файл /etc/os-release
- Распарсить его для получения лишь ключей (то что до знака равно)
- Выдать правильный JSON
var lld = [];
var lines = value.split("\n");
var lines_num = lines.length;
for (i = 0; i < lines_num; i++)
{ var row = {}; var k = lines[i].split("="); row["{#KEY}"] = k[0]; lld.push(row);
}
return JSON.stringify(lld); Прочитанное содержимое файла /etc/os-release разбивается по строкам (\n) и потом строка разбивается по символу = и берётся ключ, а значение отбрасывается.
Благодаря правилу обнаружения для каждого сервера Zabbix сможет извлекать все его ключи из /etc/os-release и через прототип формировать элементы данных под каждый ключ. Затем эти сформированные элементы данных будут периодически опрашиваться Zabbix сервером и получать данные. Вуаля! Дело сделано и чисто средствами Zabbix сервера.
Вот сам итоговый zabbix шаблон Template_OSI_v2.xml
. Файл лучше сохранить по ссылке и открывать в редакторах типа Notepad++. Пришлось интуитивно понять как мои наработки, сделанные вручную, указать в xml файле, так как я не нашёл толкового описания на просторах Интернет. Но, благодаря чутью, по аналогии с подсмотренными схожими тегами в стандартных шаблонах удалось создать рабочий шаблон. Так как операционная система редко меняется, поэтому опрос раз в сутки (1d). Для тестов или поменяйте на что-то поменьше или пользуйтесь функционалом Zabbix — «запустить здесь и сейчас».
Пример с сервера Debian GNU/Linux

Пример с сервера Ubuntu Server LTS

Если у вас не 5+ версия Zabbix и ручная правка-адаптация xml под вашу версию вас доконала, возможно, поможет создание шаблона с нуля и вставка лишь готовых строк key.
Дата последней правки: 2021-02-01 01:07:55
First, built-in Key description
Zabbix has a lot of rich keys, making us add Linux OS template, have helped us to define keys, so we can use it directly to link templates.

