[comment]: # ({382ff618-7d35b712})
# 10 Мониторинг сетевого коммутатора или маршрутизатора с помощью Zabbix

[comment]: # ({/382ff618-7d35b712})

[comment]: # ({d9702cdc-aea68f1a})
## Введение

Это руководство проведет вас через шаги, необходимые для начала базового мониторинга вашего сетевого коммутатора или маршрутизатора с помощью Zabbix.
В качестве примера используется маршрутизатор Cisco, но процедура применима к любому сетевому устройству с поддержкой SNMP.

**Для кого предназначено это руководство**

Это руководство предназначено для новых пользователей Zabbix и сетевых администраторов, которые хотят быстро включить базовый мониторинг сетевых устройств.
Если вам требуется глубокая настройка или расширенные параметры конфигурации, обратитесь к странице [SNMP agent](/manual/config/items/itemtypes/snmp) или разделу [Configuration](/manual/config) руководства Zabbix.

**Предварительные требования**

Перед тем как продолжить, убедитесь, что у вас есть:

-   Установлены сервер Zabbix и веб-интерфейс Zabbix: установите их в соответствии с инструкциями для вашей операционной системы (см. [Installation from packages](/manual/installation/install_from_packages) и [Web interface installation](/manual/installation/frontend)).
-   Установлен агент Zabbix, если выполняется мониторинг локальных сетевых метрик.
-   Устройство с поддержкой SNMP: сетевой коммутатор или маршрутизатор (например, маршрутизатор Cisco) с включенным SNMP.
-   Установлены [MIB files](/manual/config/items/itemtypes/snmp/mibs): установка MIB-файлов позволяет Zabbix преобразовывать числовые OID в понятные человеку имена и описания.
Без надлежащей поддержки MIB вы можете видеть только числовые значения, что затрудняет настройку элементов данных и устранение неполадок.

Чтобы установить MIB-файлы в Ubuntu:

1\. Установите пакет загрузчика MIB:

```bash
sudo apt-get update
sudo apt-get install snmp-mibs-downloader
```

Если вам нужно добавить MIB-файлы, специфичные для производителя (например, от Cisco, Juniper), поместите их в соответствующий каталог MIB:

-   Для систем на базе Linux обычные расположения включают /usr/share/snmp/mibs/ или /usr/local/share/snmp/mibs/.
-   Для установок Zabbix MIB-файлы можно хранить в /var/lib/zabbix/mibs/.

Убедитесь, что переменная окружения MIBDIRS или файл snmp.conf содержит правильный путь.

Чтобы проверить, что система распознает новые MIB, используйте:

```bash
snmptranslate -IR -On <MIB-NAME>::<object>
```

Подробные инструкции см. в документации вашей SNMP-библиотеки:

-   [Cisco MIBs](https://github.com/cisco/cisco-mibs)
-   [Juniper MIBs](https://apps.juniper.net/mib-explorer/)

2\. Отредактируйте ``/etc/snmp/snmp.conf`` и закомментируйте строку, начинающуюся с `mibs :`, чтобы разрешить системе загружать все доступные MIB.

3\. Проверьте работу, выполнив ``snmpwalk`` (например, ``snmpwalk -v 2c -c <your_community_string> <device_IP>``), и убедитесь, что OID отображаются с описательными именами.

В зависимости от вашей среды некоторые шаги в этом руководстве могут немного отличаться.
Это руководство основано на среде с Ubuntu и сетевым устройством Cisco Catalyst 3750V2-24FS, находящимся под мониторингом.

Предполагается, что ваше сетевое устройство уже физически установлено и подключено.

[comment]: # ({/d9702cdc-aea68f1a})

[comment]: # ({aea0a787-703f62e1})

## Configure the network device (Cisco router example)

For monitoring via SNMP, you must configure your network device to allow SNMP queries.
The example below is for SNMPv2 and does not take into account existing settings.
Caution: applying these commands may override current SNMP configurations.

For a Cisco router, the configuration typically involves steps written below.

[comment]: # ({/aea0a787-703f62e1})

[comment]: # ({08cfb265-e36b1d35})

### SNMPv2 Example

1\. Enable SNMP and set community string.

[Log in](https://www.cisco.com/c/en/us/support/docs/smb/switches/cisco-small-business-300-series-managed-switches/smb4982-access-an-smb-switch-cli-using-ssh-or-telnet.html) to your Cisco router's console and enter configuration mode:

```default
configure terminal
```

Then, [enable SNMP](https://www.cisco.com/c/en/us/support/docs/ip/simple-network-management-protocol-snmp/7282-12.html) by specifying a read-only community string.
For example:

```default
snmp-server community <your_community_string> RO
```

Replace ``<your_community_string>`` with your secure community string.
Note: the RO (Read-Only) option allows SNMP to retrieve data from the device but prevents any configuration changes.

It is recommended to restrict SNMP access to only the necessary devices for security reasons.
For further guidance on configuring access control lists (ACLs), refer to [Cisco's official documentation](https://www.cisco.com/c/en/us/td/docs/switches/datacenter/nexus3000/sw/security/503_u2_2/Cisco_n3k_security_cg_503_u2_2_chapter7.html?dtid=osscdc000283).

2\. Save the configuration.

Save your changes to ensure SNMP settings persist after a reboot:

```default
write memory
```

[comment]: # ({/08cfb265-e36b1d35})

[comment]: # ({5c8aa85b-87017956})

### SNMPv3 Example

SNMPv3 provides enhanced security with authentication and encryption.
Its configuration is more secure than SNMPv2 and should be verified against your device-specific documentation.

1\. Create an SNMP group.

Configure an SNMPv3 group with privacy (encryption) enabled:

```default
configure terminal
snmp-server group <your_group> v3 priv
```

2\. Create an SNMP user.

Add an SNMPv3 user with authentication and privacy.
Replace the placeholders with your desired values:

```default
snmp-server user <your_user> <your_group> v3 auth md5 <auth_password> priv aes 128 <priv_password>
```

3\. Save the configuration:

```default
write memory
```

For further details or model-specific instructions, you may refer to external [Cisco SNMP configuration tutorials](https://www.cisco.com/c/en/us/td/docs/ios-xml/ios/snmp/configuration/xe-16/snmp-xe-16-book/nm-snmp-cfg-snmp-support.html).
This guide, however, provides the basic steps for enabling SNMP monitoring.

[comment]: # ({/5c8aa85b-87017956})

[comment]: # ({9891bde8-8df5d064})
## Настройка веб-интерфейса Zabbix

[comment]: # ({/9891bde8-8df5d064})

[comment]: # ({5860d3dc-3dc3ccce})

### Create a host in Zabbix frontend

1\. Log into Zabbix frontend.

2\. Add a new host.

Navigate to *Data collection > Hosts* and click on *Create host*.

-   *Host name*: enter a name for your device (e.g., "Cisco Router").
-   Host groups: select an existing group or create a new group such as "Network Devices".
-   Interfaces:
    -   Click *Add* under Interfaces.
    -   Choose *SNMP* as the interface type.
    -   Enter the IP address or DNS name of your Cisco router.
    -   Set the default SNMP port (usually 161).
    -   Use the drop-down menu to select the appropriate SNMP version (e.g. SNMPv2).
    -   For SNMPv1/v2, enter the community string in the *SNMP community* field.
    For SNMPv3, additional credentials (*Context name*, *Security name*, and *Security level*, etc.) will be prompted.

3\. Link Templates

In the *Templates* field, select the SNMP template that best matches your device.
Zabbix provides a range of pre-built [SNMP templates](/manual/config/templates_out_of_the_box/network_devices#devices) for many device families.
For example, if you are monitoring a Cisco device, choose the template that corresponds to your device's OS or model (such as Cisco IOS SNMP or Cisco Catalyst 3750\<device model\> SNMP).

4\. Click on *Add* to save the host.

![](../../../assets/en/manual/guides/switch_host.png){width="600"}

![](../../../assets/en/manual/guides/switch_host1.png){width="600"}

[comment]: # ({/5860d3dc-3dc3ccce})

[comment]: # ({6df3857c-a35d4c3a})
## View collected metrics

Congratulations! Zabbix is now set up to monitor your network device.

Latest Data:

-   Navigate to Monitoring > Latest data in the Zabbix frontend.

![](../../../assets/en/manual/guides/switch_hosts.png){width="600"}

-   Select your "Cisco Router" host (or discovered hosts) to view metrics such as hardware and network uptime, ICMP loss, ping, and response time, etc.

![](../../../assets/en/manual/guides/switch_data.png){width="600"}

-   Graphs and screens:

To visualize the performance data, click on *Graphs* next to the SNMP items to see detailed metrics.

As a next step, you can:

-   [Add custom SNMP items](#create-snmp-items) to monitor additional metrics.
-   [Set up problem alerts](#set-up-problem-alerts) to receive notifications about potential issues.

[comment]: # ({/6df3857c-a35d4c3a})

[comment]: # ({d0b21274-ff776e8a})
### Create SNMP items

Once the host is set up, you can create items to monitor specific metrics.
Note: this step is optional if you're using a template, as templates already contain default sets of items.

1\. Identify the SNMP OID:

Use the ``snmpwalk`` command to list available OIDs on your device.
For example:

```bash
snmpwalk -v 2c -c <your_community_string> <device_IP> .
```

Find the OID for the metric you wish to monitor (for instance, IF-MIB::ifHCInOctets.3 for incoming traffic on port 3).
To get the numeric OID, you can use:

```bash
snmpget -v 2c -c <your_community_string> -On <device_IP> IF-MIB::ifHCInOctets.3
```

2\. Create an SNMP item:

-   Navigate to *Data collection > Hosts* and click on the *Items* tab for your SNMP host and click *Create item*.
-   *Name*: enter a descriptive name (e.g., "Port 3 Incoming Traffic").
-   *Type*: select *SNMP agent*.
-   *Key*: provide a meaningful key (e.g., ``cisco.ifHCInOctets.3``).
-   *Host interface*: ensure the SNMP interface is selected.
-   *SNMP OID*: enter the OID using one of the supported formats, for example:
    -   ``get[1.3.6.1.2.1.31.1.1.1.6.3]`` for a single value;
    -   ``walk[1.3.6.1.2.1.31.1.1.1.6.3]`` to retrieve a subtree of values asynchronously.

![](../../../assets/en/manual/guides/switch_item.png){width="600"}

-   *Preprocessing* (if needed): if the item returns a cumulative counter (such as interface traffic), navigate to the *Preprocessing* tab, and add a preprocessing step like "Change per second" to calculate the rate.

![](../../../assets/en/manual/guides/switch_preprocessing.png){width="600"}

To retrieve multiple values in one SNMP transaction, you can specify several OIDs using the syntax ``walk[OID1,OID2,...]``.

[comment]: # ({/d0b21274-ff776e8a})

[comment]: # ({53a42dcd-1b28232c})
### Translating OIDs between Numeric and MIB Names

When working with SNMP, you might need to convert between numeric OIDs and their corresponding MIB names.
This translation helps in identifying and troubleshooting metrics more easily.

-   Translating a MIB name to a numeric OID: use the ``snmptranslate`` command with the ``-On`` option.
For example, to translate the MIB name ``IF-MIB::ifHCInOctets.3`` to its numeric OID, run:

```bash
snmptranslate -On IF-MIB::ifHCInOctets.3
```

This command might output:

```bash
.1.3.6.1.2.1.31.1.1.1.6.3
```

-   Translating a numeric OID to its MIB name: use the ``snmptranslate`` command with the ``-IR`` (or ``-m ALL``) option to reverse the translation.
For example, to translate the numeric OID ``.1.3.6.1.2.1.31.1.1.1.6.3`` back to its MIB name, run:

```bash
snmptranslate -IR -On .1.3.6.1.2.1.31.1.1.1.6.3
```

This command might output:

```bash
IF-MIB::ifHCInOctets.3
```

[comment]: # ({/53a42dcd-1b28232c})

[comment]: # ({133d5107-c98bb7b1})
## Настройка оповещений о проблемах

Это руководство содержит основные шаги настройки отправки оповещений по электронной почте.

1\. Перейдите в [*Настройки пользователя > Профиль*](/manual/web_interface/user_profile), откройте вкладку *Media* и [добавьте свой email](/manual/quickstart/login#adding-user).

![](../../../assets/en/manual/quickstart/new_media.png){width="600"}

2\. Следуйте инструкциям из руководства [Получение уведомления о проблеме](/manual/quickstart/notification).

В следующий раз, когда Zabbix обнаружит проблему, вы должны получить оповещение по электронной почте.

[comment]: # ({/133d5107-c98bb7b1})

[comment]: # ({1be06fac-a0c24d90})
## Проверьте вашу конфигурацию

Чтобы убедиться, что Zabbix корректно обнаруживает проблемы с производительностью сети, смоделируйте реальную проблему, увеличив порог времени отклика ICMP ping.

1\. Откройте конфигурацию узла сети "Cisco Router" в Zabbix.

2\. Перейдите на вкладку *Macros* и выберите *Inherited and host macros*.

3\. Найдите макрос ``{$ICMP_RESPONSE_TIME_WARN}`` (или аналогичный макрос порога времени отклика).

4\. Установите очень низкое значение (например, 0.001), чтобы сработало оповещение, когда время отклика ping превысит это значение.

5\. Нажмите *Update*, чтобы применить изменения.

6\. Подождите несколько минут, пока Zabbix обнаружит смоделированную проблему.

7\. Перейдите в *Monitoring > Problems*, чтобы убедиться, что появилось оповещение (например, "High ICMP ping response time").

![](../../../assets/en/manual/guides/switch_problem.png){width="600"}

Если оповещения [настроены](#set-up-problem-alerts), вы также должны получить оповещение о проблеме.

8\. Верните значение макроса к исходному и нажмите *Update*, чтобы сохранить изменения.

9\. Убедитесь, что проблема устранена и исчезла из раздела *Problems*.

[comment]: # ({/1be06fac-a0c24d90})

[comment]: # ({28c7c206-d7537870})
## Troubleshooting SNMP Monitoring

If you notice that the SNMP icon in the Zabbix frontend appears RED or no data is collected, try the following steps:

1\. Check SNMP connectivity.

For SNMPv2 run the following command from your Zabbix server:

```bash
snmpwalk -v 2c -c <community_string> <device_IP> .
```

This command verifies that the device responds to SNMP queries.

For SNMPv3, include the appropriate SNMPv3 credentials:

```bash
snmpwalk -v3 -u <your_user> -l authPriv -a MD5 -A <auth_password> -x AES -X <priv_password> <device_IP> .
```

This verifies that SNMPv3 credentials are correct and the device is responding securely.

2\. Ensure that MIB files are installed and enabled as described in the [prerequisites](#prerequisites).
To ensure that, following command must not give error when you query a network device:

```bash
snmpwalk -v 2c -c <your_community_string> <device_IP> ifInOctets
```

This should return translated OIDs without errors.

3\. Confirm that the SNMP version and credentials configured in Zabbix match those set on your device.
For instance, review the SNMP settings in the Zabbix host configuration and verify them against your device's configuration.
On a Cisco device, you might check the SNMP settings by running:

```default
show running-config | include snmp
```

This ensures that the community string (for SNMPv2) or SNMPv3 user details are correct.

4\. Verify that SNMP is correctly enabled on your network device.
On a Cisco router, log in to the console and run:

```default
show running-config | include snmp
```

This command displays the active SNMP configuration and helps confirm that SNMP is properly configured.

5\. Ensure that no firewalls or network issues are blocking SNMP traffic (typically on port 161) between the Zabbix server and the device.
You can test connectivity using:

nc -zv <device_IP> 161

``nc -zv`` checks if port 161 is open and listening on the device.

Additionally, if you are using UFW on Ubuntu, check the firewall status:

```bash
sudo ufw status
```

Or, for iptables:

```bash
sudo iptables -L -n
```

6\. Review the Zabbix server log files for any SNMP-related errors to help pinpoint the issue:

```bash
tail -f /tmp/zabbix_server.log
```

``tail -f`` allows you to monitor log updates in real time.

[comment]: # ({/28c7c206-d7537870})

[comment]: # ({20664b64-aeb05d60})
**См. также:**

- [Создание элемента данных](/manual/config/items/item) - узнайте, как добавлять дополнительные метрики.
- [Агент SNMP](/manual/config/items/itemtypes/snmp) - дополнительная информация о мониторинге SNMP с помощью Zabbix.
- [Стандартизированные шаблоны для сетевых устройств](/manual/config/templates_out_of_the_box/network_devices) - информация о доступных шаблонах SNMP.
- [Обнаружение OID SNMP](/manual/discovery/low_level_discovery/examples/snmp_oids_walk) - дополнительная информация об обнаружении SNMP на коммутаторе.
- [Настройка правила сетевого обнаружения](/manual/discovery/network_discovery/rule) - дополнительная информация о том, как настроить правило сетевого обнаружения, используемое Zabbix для обнаружения узлов сети и служб.

[comment]: # ({/20664b64-aeb05d60})
