# SNMP мониторинг в VyOS

> Настройка SNMP v2c и v3 в VyOS для мониторинга через Zabbix, Nagios и PRTG - community strings, USM пользователи, SNMP traps и OID-деревья в облаке

Source: https://opennix.org/docs/vyos/services/vyos-snmp/



SNMP обеспечивает мониторинг и управление сетевым оборудованием. VyOS поддерживает SNMP v1, v2c, и v3, позволяя интегрировать роутер с системами мониторинга (Nagios, Zabbix, PRTG, LibreNMS) и получать метрики о производительности, статусе интерфейсов, и других параметрах.

## Обзор

### Что такое SNMP

**Simple Network Management Protocol**:
- Протокол для мониторинга сетевых устройств
- Сбор метрик (CPU, memory, bandwidth, interfaces)
- Алерты через SNMP traps
- Стандартизированные MIB (Management Information Base)

### Версии SNMP

**SNMPv1**:
- Базовая версия
- Community strings для аутентификации
- Не encrypted
- Устаревшая, но широко поддерживается

**SNMPv2c**:
- Улучшенная производительность
- Community strings
- Bulk operations
- Не encrypted
- Наиболее используемая версия

**SNMPv3**:
- Аутентификация и encryption
- User-based security
- Рекомендуется для production
- Более сложная конфигурация

### SNMP компоненты

**Agent**:
- Запущен на VyOS
- Отвечает на SNMP запросы
- Отправляет traps

**Manager** (NMS - Network Management System):
- Мониторинг система (Zabbix, Nagios, etc.)
- Делает SNMP queries
- Получает traps

**MIB (Management Information Base)**:
- База данных объектов
- OID (Object Identifier) - уникальный ID
- Standard MIBs (IF-MIB, HOST-RESOURCES-MIB, etc.)

### SNMP операции

- **GET** - получить значение OID
- **GETNEXT** - получить следующий OID
- **GETBULK** - получить множественные OID (SNMPv2c/v3)
- **SET** - установить значение (опасно, обычно disabled)
- **TRAP** - асинхронное уведомление от agent

## Базовая конфигурация

### SNMPv2c (простая конфигурация)

```bash
# Community string (read-only)
set service snmp community public authorization ro

# Разрешить доступ с monitoring server
set service snmp community public network 192.168.1.0/24

# Location и contact
set service snmp location 'Data Center - Rack A12'
set service snmp contact 'admin@company.com'

# Listen address
set service snmp listen-address 0.0.0.0 port 161

commit
save
```

### Проверка SNMP

```bash
# На VyOS проверить service
show service snmp

# С monitoring server
snmpwalk -v2c -c public 192.168.1.1

# Specific OID (system description)
snmpget -v2c -c public 192.168.1.1 1.3.6.1.2.1.1.1.0
```

### SNMPv3 (secure)

```bash
# User с аутентификацией и encryption
set service snmp v3 user monitor auth type md5
set service snmp v3 user monitor auth plaintext-password 'AuthPassword123!'
set service snmp v3 user monitor privacy type aes
set service snmp v3 user monitor privacy plaintext-password 'PrivPassword456!'

# Security level
set service snmp v3 user monitor mode ro

# View (ограничение доступа к MIB)
set service snmp v3 view default oid 1.3.6.1

# Group
set service snmp v3 group monitoring mode ro
set service snmp v3 group monitoring view default

# User в group
set service snmp v3 user monitor group monitoring

# Listen
set service snmp listen-address 0.0.0.0 port 161

commit
save
```

**SNMPv3 test**:
```bash
snmpwalk -v3 -l authPriv -u monitor \
  -a MD5 -A 'AuthPassword123!' \
  -x AES -X 'PrivPassword456!' \
  192.168.1.1
```

## Communities (SNMPv1/v2c)

### Read-only community

```bash
# Public community (не используйте в production!)
set service snmp community public authorization ro
set service snmp community public network 192.168.1.0/24

# Private community (лучше)
set service snmp community SecretMonitoring authorization ro
set service snmp community SecretMonitoring network 192.168.1.100/32

commit
```

### Read-write community

```bash
# Read-write (опасно!)
set service snmp community admin authorization rw
set service snmp community admin network 192.168.1.100/32

commit
```

**Внимание**: RW access позволяет изменять конфигурацию через SNMP SET. Используйте осторожно.

### Множественные communities

```bash
# Monitoring system
set service snmp community zabbix authorization ro
set service snmp community zabbix network 192.168.1.100/32

# Backup monitoring
set service snmp community nagios authorization ro
set service snmp community nagios network 192.168.1.101/32

# Management network
set service snmp community private authorization ro
set service snmp community private network 10.0.0.0/8

commit
```

## SNMPv3 Configuration

### Users и authentication

```bash
# User 1: MD5 auth, AES encryption
set service snmp v3 user monitor1 auth type md5
set service snmp v3 user monitor1 auth plaintext-password 'StrongAuth1!'
set service snmp v3 user monitor1 privacy type aes
set service snmp v3 user monitor1 privacy plaintext-password 'StrongPriv1!'
set service snmp v3 user monitor1 mode ro

# User 2: SHA auth, DES encryption
set service snmp v3 user monitor2 auth type sha
set service snmp v3 user monitor2 auth plaintext-password 'StrongAuth2!'
set service snmp v3 user monitor2 privacy type des
set service snmp v3 user monitor2 privacy plaintext-password 'StrongPriv2!'
set service snmp v3 user monitor2 mode ro

commit
```

### Views (ограничение MIB access)

```bash
# Default view (весь MIB tree)
set service snmp v3 view default oid 1.3.6.1

# Limited view (только interfaces)
set service snmp v3 view interfaces-only oid 1.3.6.1.2.1.2

# System view
set service snmp v3 view system-only oid 1.3.6.1.2.1.1

commit
```

### Groups

```bash
# Monitoring group
set service snmp v3 group monitoring mode ro
set service snmp v3 group monitoring view default

# Admin group (read-write)
set service snmp v3 group admin mode rw
set service snmp v3 group admin view default

# Assign users to groups
set service snmp v3 user monitor1 group monitoring
set service snmp v3 user admin1 group admin

commit
```

### Security levels

**noAuthNoPriv** - no authentication, no encryption:
```bash
set service snmp v3 user public mode ro
# Не используйте в production
```

**authNoPriv** - authentication, no encryption:
```bash
set service snmp v3 user monitor auth type md5
set service snmp v3 user monitor auth plaintext-password 'AuthPass!'
set service snmp v3 user monitor mode ro
# Privacy не настроен
```

**authPriv** - authentication и encryption (рекомендуется):
```bash
set service snmp v3 user secure auth type sha
set service snmp v3 user secure auth plaintext-password 'AuthPass!'
set service snmp v3 user secure privacy type aes
set service snmp v3 user secure privacy plaintext-password 'PrivPass!'
set service snmp v3 user secure mode ro
```

## SNMP Traps

### Trap configuration

```bash
# Trap target (monitoring server)
set service snmp trap-target 192.168.1.100 community 'trapCommunity'
set service snmp trap-target 192.168.1.100 port 162

# SNMPv3 trap
set service snmp v3 trap-target 192.168.1.100 user trapuser
set service snmp v3 trap-target 192.168.1.100 auth type md5
set service snmp v3 trap-target 192.168.1.100 auth plaintext-password 'TrapAuth!'
set service snmp v3 trap-target 192.168.1.100 privacy type aes
set service snmp v3 trap-target 192.168.1.100 privacy plaintext-password 'TrapPriv!'

commit
```

### Trap triggers

VyOS автоматически отправляет traps для:
- Link up/down events
- Cold start (router reboot)
- Authentication failures

## Listen configuration

### Listen addresses

```bash
# Listen на всех интерфейсах
set service snmp listen-address 0.0.0.0 port 161

# Или specific interfaces
set service snmp listen-address 192.168.1.1 port 161
set service snmp listen-address 10.0.0.1 port 161

# IPv6
set service snmp listen-address ::0 port 161

commit
```

### Custom port

```bash
# Нестандартный порт (security through obscurity)
set service snmp listen-address 0.0.0.0 port 10161

commit
```

**Примечание**: Большинство NMS ожидают port 161.

## Common OIDs

### System information

```bash
# System description
1.3.6.1.2.1.1.1.0

# System uptime
1.3.6.1.2.1.1.3.0

# System contact
1.3.6.1.2.1.1.4.0

# System name (hostname)
1.3.6.1.2.1.1.5.0

# System location
1.3.6.1.2.1.1.6.0
```

### Interfaces

```bash
# Interface table
1.3.6.1.2.1.2.2

# Interface names
1.3.6.1.2.1.31.1.1.1.1

# Interface status (up/down)
1.3.6.1.2.1.2.2.1.8

# Interface speed
1.3.6.1.2.1.2.2.1.5

# Interface in octets (RX)
1.3.6.1.2.1.2.2.1.10

# Interface out octets (TX)
1.3.6.1.2.1.2.2.1.16
```

### CPU и Memory

```bash
# CPU usage (HOST-RESOURCES-MIB)
1.3.6.1.2.1.25.3.3.1.2

# Memory total
1.3.6.1.2.1.25.2.2.0

# Memory used
1.3.6.1.4.1.2021.4.6.0
```

### Storage

```bash
# Disk usage
1.3.6.1.4.1.2021.9.1.9

# Disk percentage
1.3.6.1.4.1.2021.9.1.9
```

## Integration с Monitoring Systems

### Zabbix

**SNMP template для VyOS**:

1. Zabbix → Configuration → Hosts → Create host
2. Host name: `vyos-router`
3. Groups: `Network devices`
4. Interfaces: SNMP
   - IP: `192.168.1.1`
   - Port: `161`
   - SNMP version: `SNMPv2`
   - SNMP community: `{$SNMP_COMMUNITY}`
5. Templates: Link template
   - `Template Net Network Generic Device SNMP`
   - `Template Module Interfaces SNMP`

**Macros**:
```
{$SNMP_COMMUNITY} = SecretMonitoring
{$IF_ERRORS_WARN} = 2
{$BANDWIDTH_WARN} = 80
```

**Custom items**:
```
Name: CPU Usage
Type: SNMP agent
Key: system.cpu.util
SNMP OID: 1.3.6.1.4.1.2021.11.9.0
Type of information: Numeric (float)
Units: %
```

### Nagios

**SNMP checks**:

```bash
# Install plugin
apt-get install nagios-plugins-snmp

# Check interface status
/usr/lib/nagios/plugins/check_snmp -H 192.168.1.1 \
  -C public \
  -o 1.3.6.1.2.1.2.2.1.8.2 \
  -r 1 -m RFC1213-MIB

# Check CPU
/usr/lib/nagios/plugins/check_snmp -H 192.168.1.1 \
  -C public \
  -o 1.3.6.1.4.1.2021.11.9.0 \
  -w 80 -c 90

# Check bandwidth
/usr/lib/nagios/plugins/check_snmp -H 192.168.1.1 \
  -C public \
  -o 1.3.6.1.2.1.2.2.1.10.2 \
  -w 100000000 -c 150000000
```

**Nagios config** (`/etc/nagios/objects/vyos.cfg`):
```
define host{
    use                     generic-switch
    host_name               vyos-router
    alias                   VyOS Router
    address                 192.168.1.1
    _snmp_community         public
}

define service{
    use                     generic-service
    host_name               vyos-router
    service_description     SNMP - CPU Usage
    check_command           check_snmp_cpu!80!90
}
```

### LibreNMS

**Add device**:

1. Devices → Add Device
2. Hostname: `192.168.1.1`
3. SNMP Version: `v2c`
4. Community: `SecretMonitoring`
5. Port: `161`
6. Add Device

LibreNMS автоматически обнаружит:
- Interfaces
- VLANs
- Routing protocols
- System metrics

**SNMPv3 в LibreNMS**:
```
SNMP Version: v3
Auth Level: authPriv
Auth User: monitor
Auth Password: AuthPassword123!
Crypto: AES
Crypto Password: PrivPassword456!
```

### PRTG

**SNMP Traffic sensor**:

1. Add Sensor → SNMP Traffic Sensor
2. Device: VyOS Router
3. SNMP Version: v2c
4. Community String: public
5. Interface: eth0
6. Traffic Mode: Use interface counters
7. Add Sensor

**Custom SNMP sensor**:
1. Add Sensor → SNMP Custom
2. OID: `1.3.6.1.4.1.2021.11.9.0` (CPU)
3. Sensor name: CPU Usage
4. Unit: Percent

### Prometheus + SNMP Exporter

**snmp.yml**:
```yaml
auths:
  public_v2:
    community: public
    security_level: noAuthNoPriv
    version: 2

modules:
  vyos:
    walk:
      - 1.3.6.1.2.1.1    # System
      - 1.3.6.1.2.1.2    # Interfaces
      - 1.3.6.1.4.1.2021 # UCD-SNMP-MIB
    metrics:
      - name: sysUpTime
        oid: 1.3.6.1.2.1.1.3
        type: gauge
      - name: ifInOctets
        oid: 1.3.6.1.2.1.2.2.1.10
        type: counter
```

**Prometheus config**:
```yaml
scrape_configs:
  - job_name: 'snmp'
    static_configs:
      - targets:
        - 192.168.1.1
    metrics_path: /snmp
    params:
      module: [vyos]
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_target
      - source_labels: [__param_target]
        target_label: instance
      - target_label: __address__
        replacement: localhost:9116
```

## Мониторинг и диагностика

### Проверка SNMP service

```bash
# Service status
show service snmp

# SNMP daemon status
systemctl status snmpd

# Listening ports
netstat -ulnp | grep 161
```

### SNMP tools на VyOS

```bash
# snmpwalk (получить все OID)
snmpwalk -v2c -c public localhost

# snmpget (specific OID)
snmpget -v2c -c public localhost 1.3.6.1.2.1.1.5.0

# snmpbulkwalk (faster для больших MIB)
snmpbulkwalk -v2c -c public localhost
```

### Debugging

```bash
# SNMP logs
show log | grep snmp

# Detailed snmpd log
cat /var/log/snmpd.log

# Test from remote
snmpwalk -v2c -c public -d 192.168.1.1
```

### Performance monitoring

```bash
# SNMP request rate
watch -n 1 'netstat -s | grep -i snmp'

# Bandwidth через SNMP
snmpget -v2c -c public 192.168.1.1 1.3.6.1.2.1.2.2.1.10.2
# Repeat и calculate delta
```

## Troubleshooting

### SNMP не отвечает

**Проблема**: SNMP queries timeout.

**Причины**:
1. SNMP service не запущен
2. Firewall блокирует UDP 161
3. Wrong community string
4. Listen address неправильный

**Диагностика**:
```bash
# Проверить service
show service snmp

# Проверить слушает ли
netstat -ulnp | grep 161

# Firewall
show firewall ipv4 input filter

# Test локально
snmpget -v2c -c public localhost 1.3.6.1.2.1.1.5.0
```

**Решение**:
```bash
# Enable SNMP
set service snmp community public authorization ro
set service snmp listen-address 0.0.0.0 port 161

# Firewall
set firewall ipv4 input filter rule 50 action accept
set firewall ipv4 input filter rule 50 source address 192.168.1.0/24
set firewall ipv4 input filter rule 50 destination port 161
set firewall ipv4 input filter rule 50 protocol udp

commit
```

### SNMPv3 authentication failed

**Проблема**: "Authentication failure" для SNMPv3.

**Причины**:
1. Wrong username/password
2. Auth type mismatch
3. Security level mismatch

**Диагностика**:
```bash
# Проверить users
show service snmp v3

# Test с verbose
snmpwalk -v3 -l authPriv -u monitor \
  -a MD5 -A 'WrongPassword' \
  -x AES -X 'PrivPassword' \
  -d 192.168.1.1
```

**Решение**:
```bash
# Проверить пароли
show configuration service snmp v3 user monitor

# Пересоздать user
delete service snmp v3 user monitor
set service snmp v3 user monitor auth type md5
set service snmp v3 user monitor auth plaintext-password 'CorrectAuthPass!'
set service snmp v3 user monitor privacy type aes
set service snmp v3 user monitor privacy plaintext-password 'CorrectPrivPass!'

commit
```

### Community string не работает

**Проблема**: "No Such Name" или timeout.

**Причины**:
1. Community не существует
2. Network restriction блокирует
3. Authorization type неправильный

**Решение**:
```bash
# Проверить communities
show configuration service snmp community

# Добавить network
set service snmp community public network 192.168.1.0/24

# Или allow all (не рекомендуется)
set service snmp community public network 0.0.0.0/0

commit
```

### Traps не приходят

**Проблема**: Monitoring server не получает traps.

**Причины**:
1. Trap target не настроен
2. Firewall на NMS блокирует UDP 162
3. Community string неправильный

**Решение**:
```bash
# Configure trap
set service snmp trap-target 192.168.1.100 community 'trapCommunity'
set service snmp trap-target 192.168.1.100 port 162

# Test trap
snmptrap -v2c -c trapCommunity 192.168.1.100 '' \
  1.3.6.1.6.3.1.1.5.3 \
  1.3.6.1.2.1.1.5.0 s "Test Trap"

commit
```

### OID не возвращает данные

**Проблема**: Specific OID возвращает "No Such Object".

**Причины**:
1. OID не существует
2. View restriction блокирует
3. Feature не enabled

**Решение**:
```bash
# Walk MIB для поиска OID
snmpwalk -v2c -c public localhost | grep -i cpu

# Проверить view restrictions
show configuration service snmp v3 view

# Enable необходимые MIB
# VyOS поддерживает standard MIBs по умолчанию
```

## Безопасность

### Рекомендации по безопасности

1. **Используйте SNMPv3**:
```bash
set service snmp v3 user secure auth type sha
set service snmp v3 user secure auth plaintext-password 'StrongAuth!'
set service snmp v3 user secure privacy type aes
set service snmp v3 user secure privacy plaintext-password 'StrongPriv!'
```

2. **Strong community strings**:
```bash
# Не используйте 'public', 'private'
set service snmp community H8kL2mP9qR4sT7v authorization ro
```

3. **Network restrictions**:
```bash
# Только с monitoring servers
set service snmp community secure network 192.168.1.100/32
set service snmp community secure network 192.168.1.101/32
```

4. **Firewall**:
```bash
set firewall ipv4 input filter rule 50 action accept
set firewall ipv4 input filter rule 50 source address 192.168.1.100/32
set firewall ipv4 input filter rule 50 destination port 161
set firewall ipv4 input filter rule 50 protocol udp
```

5. **Read-only access**:
```bash
# Избегайте RW communities
set service snmp community monitor authorization ro
```

6. **Specific listen address**:
```bash
# Не listen на WAN
set service snmp listen-address 192.168.1.1 port 161
```

7. **Views для SNMPv3**:
```bash
# Ограничить доступ к sensitive OID
set service snmp v3 view limited oid 1.3.6.1.2.1.2
set service snmp v3 group monitoring view limited
```

8. **Rate limiting**:
```bash
set firewall ipv4 input filter rule 50 recent count 10
set firewall ipv4 input filter rule 50 recent time minute 1
```

9. **Logging**:
```bash
# Monitor SNMP access
show log | grep snmp
```

10. **Regular audits**:
    - Review communities
    - Check access logs
    - Update passwords

## Примеры конфигураций

### Пример 1: Basic monitoring (SNMPv2c)

```bash
# Community для Zabbix
set service snmp community zabbix authorization ro
set service snmp community zabbix network 192.168.1.100/32

# System info
set service snmp location 'Main Office - Server Room'
set service snmp contact 'netadmin@company.com'

# Listen
set service snmp listen-address 0.0.0.0 port 161

# Firewall
set firewall ipv4 input filter rule 50 action accept
set firewall ipv4 input filter rule 50 source address 192.168.1.100/32
set firewall ipv4 input filter rule 50 destination port 161
set firewall ipv4 input filter rule 50 protocol udp

commit
save
```

### Пример 2: Enterprise SNMPv3

```bash
# SNMPv3 users
set service snmp v3 user monitor auth type sha
set service snmp v3 user monitor auth plaintext-password 'MonitorAuth2024!'
set service snmp v3 user monitor privacy type aes
set service snmp v3 user monitor privacy plaintext-password 'MonitorPriv2024!'
set service snmp v3 user monitor mode ro

# View
set service snmp v3 view monitoring oid 1.3.6.1

# Group
set service snmp v3 group monitoring-group mode ro
set service snmp v3 group monitoring-group view monitoring

# Assign
set service snmp v3 user monitor group monitoring-group

# Trap
set service snmp v3 trap-target 192.168.1.100 user monitor
set service snmp v3 trap-target 192.168.1.100 auth type sha
set service snmp v3 trap-target 192.168.1.100 auth plaintext-password 'TrapAuth!'
set service snmp v3 trap-target 192.168.1.100 privacy type aes
set service snmp v3 trap-target 192.168.1.100 privacy plaintext-password 'TrapPriv!'

# System
set service snmp location 'Data Center A - Rack 12'
set service snmp contact 'noc@enterprise.com'

# Listen
set service snmp listen-address 10.0.0.1 port 161

commit
save
```

### Пример 3: Multi-NMS environment

```bash
# Zabbix
set service snmp community zabbix authorization ro
set service snmp community zabbix network 192.168.1.100/32

# Nagios
set service snmp community nagios authorization ro
set service snmp community nagios network 192.168.1.101/32

# PRTG
set service snmp community prtg authorization ro
set service snmp community prtg network 192.168.1.102/32

# Management
set service snmp community mgmt authorization ro
set service snmp community mgmt network 10.0.0.0/8

# Traps для всех
set service snmp trap-target 192.168.1.100 community 'trapCommunity'
set service snmp trap-target 192.168.1.101 community 'trapCommunity'
set service snmp trap-target 192.168.1.102 community 'trapCommunity'

# System
set service snmp location 'Branch Office'
set service snmp contact 'admin@branch.com'

set service snmp listen-address 0.0.0.0 port 161

commit
save
```

## Лучшие практики

1. **SNMPv3 для production**:
   - Authentication и encryption
   - User-based access control

2. **Strong credentials**:
   - Community strings: 20+ символов
   - SNMPv3 passwords: 12+ символов

3. **Network restrictions**:
   - Specific monitoring server IPs
   - Не allow 0.0.0.0/0

4. **Read-only access**:
   - RW только если absolutely необходимо
   - Ограничить RW к specific OID

5. **Firewall protection**:
   - Allow только monitoring servers
   - Rate limiting

6. **Regular monitoring**:
   - Check SNMP performance
   - Review access logs
   - Monitor for authentication failures

7. **Documentation**:
   - Document communities/users
   - NMS configurations
   - Custom OID mappings

8. **Testing**:
   - Test after configuration
   - Verify all OID accessible
   - Test traps

9. **Backup**:
   - Document SNMP credentials separately
   - Include в disaster recovery plan

10. **Keep updated**:
    - Regular password rotation
    - Update NMS templates
    - Review and cleanup unused communities

## Заключение

SNMP в VyOS обеспечивает мощный инструмент для мониторинга и управления сетевой инфраструктурой. Основные возможности:

- **SNMPv1/v2c/v3 support** - совместимость со всеми NMS
- **Standard MIBs** - IF-MIB, HOST-RESOURCES-MIB, UCD-SNMP-MIB
- **Traps** - асинхронные уведомления
- **Security** - SNMPv3 с аутентификацией и encryption

Используйте SNMP для:
- Bandwidth monitoring
- Interface status tracking
- CPU/Memory monitoring
- Alerting через traps
- Integration с enterprise NMS

Правильная конфигурация SNMP обеспечивает visibility в сетевую инфраструктуру и позволяет proactive monitoring и troubleshooting.

