### Install mixtool and jsonnetfmt Source: https://github.com/prometheus/snmp_exporter/blob/main/snmp-mixin/README.md Install the necessary tools, mixtool and jsonnetfmt, using go install. This is the recommended method if you have a Go development environment set up. ```bash $ go install github.com/monitoring-mixins/mixtool/cmd/mixtool@latest $ go install github.com/google/go-jsonnet/cmd/jsonnetfmt@latest ``` -------------------------------- ### Example Lookup Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/generator.md An example snippet demonstrating how to configure a lookup in the generator configuration file. This example shows how to use 'ifIndex' to look up 'ifDescr' for label enrichment. ```yaml lookups: - source_indexes: [ifIndex] lookup: ifDescr # Adds ifDescr label using ifIndex to look up values ``` -------------------------------- ### SNMP Exporter Configuration Example Source: https://github.com/prometheus/snmp_exporter/blob/main/generator/FORMAT.md A comprehensive example of an SNMP Exporter configuration file. It demonstrates authentication, defining modules for walking and getting OIDs, and configuring metrics with labels, lookups, regex extracts, offsets, scales, and enum values. ```yaml auths: public_v2: version: 2 # There's various auth/version options here too. See the main README. community: public modules: module_name: walk: # List of OID subtrees to walk. - "IF-MIB::interfaces" # 1.3.6.1.2.1.2 from IF-MIB - ifXTable # 1.3.6.1.2.1.31.1.1 from IF-MIB get: # List of OIDs to get directly. - 1.3.6.1.2.1.1.3 metrics: # List of metrics to extract. # A simple metric with no labels. - name: sysUpTime oid: 1.3.6.1.2.1.1.3 type: gauge # The HELP text included with the scrape metrics. help: The value of sysUpTime on the most recent occasion at which any one or more of this entry's counters suffered a discontinuity - 1.3.6.1.4.1.30065.3.1.1.1.1.46 # See README.md type override for a list of valid types # Non-numeric types are represented as a gauge with value 1, and the rendered value # as a label value on that gauge. # A metric that's part of a table, and thus has labels. - name: ifMtu oid: 1.3.6.1.2.1.2.2.1.4 type: gauge # A list of the table indexes and their types. All indexes become labels. indexes: - labelname: ifIndex type: gauge - labelname: someString type: OctetString fixed_size: 8 # Only possible for OctetString/DisplayString types. # If only one length is possible this is it. Otherwise # this will be 0 or missing. - labelname: someOtherString type: OctetString implied: true # Only possible for OctetString/DisplayString types. # Must be the last index. See RFC2578 section 7.7. - name: ifSpeed oid: 1.3.6.1.2.1.2.2.1.5 type: gauge indexes: - labelname: ifDescr type: gauge # Lookups take original indexes, look them up in another part of the # oid tree and overwrite the given output label. lookups: - labels: [ifDescr] # Input label name(s). Empty means delete the output label. oid: 1.3.6.1.2.1.2.2.1.2 # OID to look under. labelname: ifDescr # Output label name. type: OctetString # Type of output object. # Creates new metrics based on the regex and the metric value. regex_extracts: Temp: # A new metric will be created appending this to the metricName to become metricNameTemp. - regex: '(.*)' # Regex to extract a value from the returned SNMP walks's value. value: '$1' # Parsed as float64, defaults to $1. offset: 0.0 # Adds the value to the sample. Applied after scale. scale: 0.125 # Scale the sample by this value, for example bits to bytes. enum_values: # Enum for this metric. Only used with the enum types. 0: true 1: false ``` -------------------------------- ### Example SNMP Lookup Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/types.md Example of how to configure lookups for additional label retrieval. ```yaml lookups: - labels: [ifIndex] labelname: ifName oid: 1.3.6.1.2.1.31.1.1.1.1 type: DisplayString ``` -------------------------------- ### Example RegexpExtract Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/types.md Example of configuring regex extracts to capture temperature values. ```yaml regex_extracts: temperature: - regex: 'temp[^0-9]*([0-9.]+)' value: '$1' ``` -------------------------------- ### Install Build Dependencies (RHEL) Source: https://github.com/prometheus/snmp_exporter/blob/main/generator/README.md Installs necessary packages for building the generator on RHEL-based systems. ```bash sudo yum install gcc make net-snmp net-snmp-utils net-snmp-libs net-snmp-devel golang-bin git patch # RHEL-based distros ``` -------------------------------- ### Example Secret Usage Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/types.md Demonstrates setting a secret password and how it marshals to YAML. ```go var pwd config.Secret pwd.Set("mysecretpassword") // When marshaled to YAML: password: ``` -------------------------------- ### Generator Configuration Example Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/generator.md Example of a generator.yml file specifying OIDs to walk for a specific module. ```yaml modules: my_device: walk: - 1.3.6.1.2.1.2 - 1.3.6.1.2.1.25 ``` -------------------------------- ### Environment Variable Substitution Example Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/errors.md This example demonstrates how to use environment variables in the SNMP exporter configuration. Ensure the environment variable is set before starting the exporter with the '--config.expand-environment-variables' flag. ```bash export SNMP_PASSWORD=mysecret ./snmp_exporter --config.expand-environment-variables ``` -------------------------------- ### SNMP Exporter Main Endpoint Example Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/OVERVIEW.md Example of a GET request to the main SNMP scraping endpoint. Specify the target device, authentication configuration, and the MIB module to use for scraping. ```http GET /snmp?target=192.168.1.100&auth=public_v2&module=if_mib ``` -------------------------------- ### Install Build Dependencies (Debian) Source: https://github.com/prometheus/snmp_exporter/blob/main/generator/README.md Installs necessary packages for building the generator on Debian-based systems. ```bash sudo apt-get install unzip build-essential libsnmp-dev golang-go git # Debian-based distros ``` -------------------------------- ### Example Metric Overrides Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/generator.md Provides examples of how to override metric names, types, and help text for specific metrics. ```yaml overrides: sysUpTime: name: snmp_system_uptime type: gauge help: System uptime in centiseconds temperature: scale: 0.1 name: device_temperature_celsius ``` -------------------------------- ### Example Dynamic Filter Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/types.md Example of configuring dynamic filters to include/exclude OID instances based on their operational status. ```yaml filters: - oid: 1.3.6.1.2.1.2.2.1.8 targets: [1.3.6.1.2.1.2.2.1.10] values: ['1'] # Only instances where ifOperStatus == up ``` -------------------------------- ### Start SNMP Exporter Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Basic commands to start the SNMP exporter with various configurations like custom files, environment variables, debug logging, dry run, custom ports, and parallel module scraping. ```bash # Basic start ./snmp_exporter ``` ```bash # Custom config ./snmp_exporter --config.file=custom.yml ``` ```bash # Multiple config files ./snmp_exporter --config.file=snmp.yml --config.file=custom/*.yml ``` ```bash # With environment variables ./snmp_exporter --config.expand-environment-variables ``` ```bash # Enable debug logging ./snmp_exporter --log.level=debug ``` ```bash # Just validate config ./snmp_exporter --config.file=snmp.yml --dry-run ``` ```bash # Custom port ./snmp_exporter --web.listen-address=:9117 ``` ```bash # Parallel module scraping ./snmp_exporter --snmp.module-concurrency=4 ``` -------------------------------- ### SNMP Exporter URL Examples Source: https://github.com/prometheus/snmp_exporter/blob/main/README.md Examples of how to construct URLs to scrape SNMP devices with different configurations. Prometheus automatically handles URL encoding for query parameters. ```text http://localhost:9116/snmp?target=192.0.0.8 ``` ```text http://localhost:9116/snmp?auth=my_secure_v3&module=ddwrt&target=192.0.0.8 ``` ```text http://localhost:9116/snmp?auth=my_secure_v3&module=ddwrt&target=tcp%3A%2F%2F192.0.0.8%3A1161 ``` ```text http://localhost:9116/snmp?auth=my_secure_v3&module=ddwrt&target=192.0.0.8&snmp_context=vrf-mgmt ``` ```text http://localhost:9116/snmp?auth=my_secure_v3&module=ddwrt&target=192.0.0.8&snmp_engineid=800004f7059c7a0307400529 ``` -------------------------------- ### Basic SNMP Exporter Execution Source: https://github.com/prometheus/snmp_exporter/blob/main/README.md Start the snmp_exporter from the command line. It will run as a daemon. ```sh ./snmp_exporter ``` -------------------------------- ### Manual SNMP Tests Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Command-line examples for manually testing SNMP connectivity and data retrieval using `snmpget` and `snmpwalk` for SNMPv2c and SNMPv3. ```bash # SNMPv2c GET snmpget -v 2c -c public 192.168.1.100 1.3.6.1.2.1.1.1.0 ``` ```bash # SNMPv2c WALK snmpwalk -v 2c -c public 192.168.1.100 1.3.6.1.2.1.2 ``` ```bash # SNMPv3 snmpget -v 3 -u admin -a SHA256 -A password -x AES -X privpass \ 192.168.1.100 1.3.6.1.2.1.1.1.0 ``` -------------------------------- ### RFC 2579 DISPLAY-HINT Formatting Examples Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Provides examples of how RFC 2579 DISPLAY-HINT strings are used to format SNMP byte values into human-readable representations like IP addresses, MAC addresses, or ASCII strings. ```text "1d.1d.1d.1d" on [192, 168, 1, 1] → "192.168.1.1" (IP address) "1x:" on [0, 26, 43, 60, 77, 94] → "00:1a:2b:3c:4d:5e" (MAC address) "255a" on [72, 101, 108, 108, 111] → "Hello" (ASCII string) ``` -------------------------------- ### Test SNMP Exporter Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/generator.md Example command to test the generated SNMP exporter configuration against a target device. ```bash curl 'http://localhost:9116/snmp?target=192.168.1.100&module=my_device' ``` -------------------------------- ### SNMP Exporter Generator Configuration Example Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/generator.md An example of a generator configuration file (generator.yml) defining authentication, modules to walk, and metric overrides. This configuration dictates how the snmp.yml is generated. ```yaml version: 1 auths: public_v2: community: public version: 2 modules: if_mib: walk: - 1.3.6.1.2.1.2.2.1 - 1.3.6.1.2.1.31.1.1.1 lookups: - source_indexes: [ifIndex] lookup: ifDescr - source_indexes: [ifIndex] lookup: ifName overrides: ifInOctets: name: ifInOctets type: counter ifAdminStatus: enum_values: 1: up 2: down 3: testing ``` -------------------------------- ### Initialize SNMP Exporter Metrics Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/collector.md Example of how to initialize the exporter-level SNMP metrics. This includes setting up histograms and counters with appropriate namespaces, names, and help text. Ensure buckets are defined for histograms. ```go buckets := prometheus.ExponentialBuckets(0.0001, 2, 15) metrics := collector.Metrics{ SNMPCollectionDuration: promauto.NewHistogramVec( prometheus.HistogramOpts{ Namespace: "snmp", Name: "collection_duration_seconds", Help: "Duration of collections", }, []string{"module"}, ), SNMPDuration: promauto.NewHistogram( prometheus.HistogramOpts{ Namespace: "snmp", Name: "packet_duration_seconds", Help: "SNMP packet latencies", Buckets: buckets, }, ), // ... other fields } ``` -------------------------------- ### New snmp_exporter Generator Config Source: https://github.com/prometheus/snmp_exporter/blob/main/auth-split-migration.md Example of the new configuration format after splitting modules and authentication. ```yaml auths: public_v2: community: public version: 2 modules: sys_uptime: walk: - sysUpTime ``` -------------------------------- ### SNMPv2c Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Example YAML configuration for SNMPv2c authentication using a community string. ```yaml auths: public_v2: community: public version: 2 ``` -------------------------------- ### Admin Endpoint Requests Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Examples of accessing admin endpoints for viewing configuration, exporter metrics, health checks, and reloading configuration. ```bash # View configuration curl http://localhost:9116/config ``` ```bash # View exporter metrics curl http://localhost:9116/metrics ``` ```bash # Health check curl http://localhost:9116/-/healthy ``` ```bash # Reload configuration curl -X POST http://localhost:9116/-/reload ``` -------------------------------- ### Batched GET Requests for Efficiency Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Explains the strategy of batching multiple OID requests into a single SNMP GET request to reduce the overall number of network round trips. MaxRepetitions is configurable. ```text MaxRepetitions = 25 (configurable) OIDs = [1, 2, 3, ..., 100] Batch 1: Get [1-25] Batch 2: Get [26-50] ... ``` -------------------------------- ### SNMP Exporter Configuration with Environment Variables Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Demonstrates how to use environment variables for sensitive configuration like SNMP credentials. Ensure the environment variables are exported before starting the exporter. ```yaml auths: my_auth: username: ${SNMP_USER} password: ${SNMP_PASS} priv_password: ${SNMP_PRIV_PASS} ``` ```bash export SNMP_USER=admin export SNMP_PASS=password123 export SNMP_PRIV_PASS=privkey456 ./snmp_exporter --config.expand-environment-variables ``` -------------------------------- ### Construct Integer Index Label Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Example of constructing an index label from an integer component of an OID, based on metric configuration. ```text OID: 1.3.6.1.2.1.2.2.1.10.2 Metric OID: 1.3.6.1.2.1.2.2.1.10 Index: [2] Metric defines: indexes: - labelname: ifIndex type: gauge Result: ifIndex="2" ``` -------------------------------- ### Module Configuration with Lookups Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Example YAML configuration for an SNMP module that uses lookups to enrich metric data with information from other OIDs. ```yaml modules: interfaces: walk: - 1.3.6.1.2.1.2.2.1 lookups: - source_indexes: [ifIndex] lookup: ifName metrics: - name: ifInOctets oid: 1.3.6.1.2.1.2.2.1.10 type: counter indexes: - labelname: ifIndex type: gauge ``` -------------------------------- ### MIB Parsing Options Example Source: https://github.com/prometheus/snmp_exporter/blob/main/generator/README.md Illustrates various flags available to control MIB parsing behavior in Net-SNMP version 5.9.1. ```text Toggle various defaults controlling MIB parsing: u: allow the use of underlines in MIB symbols c: disallow the use of "--" to terminate comments d: save the DESCRIPTIONs of the MIB objects e: disable errors when MIB symbols conflict w: enable warnings when MIB symbols conflict W: enable detailed warnings when MIB symbols conflict R: replace MIB symbols from latest module ``` -------------------------------- ### Construct String Index Label Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Example of constructing an index label from a length-prefixed string component of an OID, based on metric configuration. ```text OID: 1.3.6.1.2.1.1.4.0.76.97.98 (ASCII "Lab") Length-prefixed in index: 3.76.97.98 Metric defines: indexes: - labelname: sysContact type: DisplayString Parsing: read_length(3) → read_chars(3) → "Lab" Result: sysContact="Lab" ``` -------------------------------- ### Per-Module Error Handling Example Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Illustrates how errors within a specific SNMP module are handled by sending an invalid metric and continuing with other modules, allowing for partial results. ```text Error in module A ──→ Send InvalidMetric to channel Continue with module B Continue with module C Return with partial results ``` -------------------------------- ### SNMPv3 HTTP Requests Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Examples for making SNMPv3 specific HTTP requests, including options for context and engine ID. ```bash # With context curl 'http://localhost:9116/snmp?target=192.168.1.100&snmp_context=vrf-mgmt' ``` ```bash # With engine ID curl 'http://localhost:9116/snmp?target=192.168.1.100&snmp_engineid=800004f7059c7a0307400529' ``` -------------------------------- ### Module Configuration with Filters Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Example YAML configuration for an SNMP module that filters collected data based on specific OID values. ```yaml modules: active_interfaces: walk: - 1.3.6.1.2.1.2.2.1 filters: - oid: 1.3.6.1.2.1.2.2.1.8 # ifOperStatus targets: [1.3.6.1.2.1.2.2.1.10] # ifInOctets values: ['1'] # Only up metrics: - name: ifInOctets oid: 1.3.6.1.2.1.2.2.1.10 type: counter ``` -------------------------------- ### Establish SNMP Connection Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/scraper.md Opens a network connection to the SNMP target, required before performing Get or WalkAll operations. Handles context cancellation for timeouts. ```go func (g *GoSNMPWrapper) Connect() error ``` ```go if err := scraper.Connect(); err != nil { log.Fatalf("Failed to connect to target: %v", err) } deferr scraper.Close() ``` -------------------------------- ### Enable Detailed Logging Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/errors.md Enable debug logging for the SNMP Exporter to get more detailed troubleshooting information. ```bash ./snmp_exporter --log.level=debug ``` -------------------------------- ### SNMP Exporter Use Case - Monitor CPU and Memory Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/INDEX.md Query example for system resource monitoring using the UCD-SNMP-MIB. ```http GET /snmp?target=server.local&auth=public_v2&module=ucd_la_table ``` -------------------------------- ### SNMPv3 Auth and Privacy Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Example YAML configuration for SNMPv3 with both authentication and privacy (encryption). ```yaml auths: my_v3_secure: username: admin password: authpass auth_protocol: SHA256 priv_password: privpass priv_protocol: AES security_level: authPriv version: 3 ``` -------------------------------- ### Old snmp_exporter Generator Config Source: https://github.com/prometheus/snmp_exporter/blob/main/auth-split-migration.md Example of the previous flat configuration format for snmp_exporter generator. ```yaml modules: sys_uptime: version: 2 walk: - sysUpTime auth: community: public ``` -------------------------------- ### HTTP Request: Missing Target Parameter Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/errors.md This example shows incorrect and correct usage of the 'target' parameter for the /snmp endpoint. The 'target' parameter must be specified exactly once. ```bash # ❌ Wrong curl http://localhost:9116/snmp # ✓ Correct curl http://localhost:9116/snmp?target=192.168.1.100 ``` -------------------------------- ### SNMP Exporter Use Case - Multi-Module Scraping Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/INDEX.md Example query to collect metrics from multiple modules in a single request. ```http GET /snmp?target=device&module=if_mib,synology,ucd_la_table ``` -------------------------------- ### Construct Enum Index Label Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Example of constructing an index label from an enumerated value within an OID, based on metric configuration. ```text OID: 1.3.6.1.2.1.2.2.1.10.1 Metric defines: indexes: - labelname: ifType type: gauge enum_values: 1: ethernetCsmacd 2: tokenRing Result: ifType="ethernetCsmacd" ``` -------------------------------- ### Basic SNMP Scrape Request Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Examples of making basic HTTP requests to scrape SNMP data. Covers default settings, specifying modules, authentication, multiple modules, IPv6 targets, and TCP with custom ports. ```bash # Default (if_mib module, public_v2 auth) curl 'http://localhost:9116/snmp?target=192.168.1.100' ``` ```bash # Specify module curl 'http://localhost:9116/snmp?target=192.168.1.100&module=synology' ``` ```bash # Specify auth curl 'http://localhost:9116/snmp?target=192.168.1.100&auth=my_v3_auth' ``` ```bash # Multiple modules curl 'http://localhost:9116/snmp?target=192.168.1.100&module=if_mib,synology' ``` ```bash # IPv6 target curl 'http://localhost:9116/snmp?target=%5B2001:db8::1%5D' ``` ```bash # TCP with custom port (URL-encoded) curl 'http://localhost:9116/snmp?target=tcp%3A%2F%2Fswitch.local%3A1161' ``` -------------------------------- ### Docker Run with Environment Variables Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/configuration.md Example of running the SNMP exporter in a Docker container, passing environment variables for authentication. The `--config.expand-environment-variables` flag must be enabled. ```bash docker run -e SNMP_USER=admin -e SNMP_PASS=secret \ prom/snmp-exporter \ --config.expand-environment-variables ``` -------------------------------- ### Generated snmp_exporter Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/auth-split-migration.md Example of a generated snmp_exporter configuration file using the new format, including authentication and module definitions. ```yaml # WARNING: This file was auto-generated using snmp_exporter generator, manual changes will be lost. auths: public_v2: community: public security_level: noAuthNoPriv auth_protocol: MD5 priv_protocol: DES version: 2 modules: if_mib: get: - 1.3.6.1.2.1.1.3.0 metrics: - name: sysUpTime oid: 1.3.6.1.2.1.1.3 type: gauge help: The time (in hundredths of a second) since the network management portion of the system was last re-initialized. - 1.3.6.1.2.1.1.3 ``` -------------------------------- ### SNMP Exporter Internal Metrics Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/endpoints.md Example response from the /metrics endpoint, exposing internal Prometheus metrics about the SNMP exporter's operation. Useful for monitoring the exporter itself. ```text # HELP snmp_request_errors_total Errors in requests to the SNMP exporter # TYPE snmp_request_errors_total counter snmp_request_errors_total 0 # HELP snmp_collection_duration_seconds Duration of collections by the SNMP exporter # TYPE snmp_collection_duration_seconds histogram snmp_collection_duration_seconds_bucket{module="if_mib",le="0.005"} 0 snmp_collection_duration_seconds_bucket{module="if_mib",le="0.01"} 1 # ... ``` -------------------------------- ### Per-Request Error Handling Example Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Shows error handling at the request level, where validation or connection failures result in specific HTTP error codes or a 500 error metric, causing the entire scrape to fail. ```text Parameter validation fails ──→ Return 400 Bad Request Connection fails ──→ Return 500 error metric All modules fail ──→ Return 500 error metric ``` -------------------------------- ### Configure TLS and Basic Authentication for Web Server Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/configuration.md Use the --web.config.file flag to specify a path to an exporter-toolkit web configuration file for TLS and HTTP basic authentication. Applies to all HTTP endpoints. ```bash ./snmp_exporter --web.config.file=web-config.yml ``` ```yaml tls_server_config: cert_file: /etc/snmp_exporter/cert.pem key_file: /etc/snmp_exporter/key.pem basic_auth_users: admin: password_hash_here ``` -------------------------------- ### ScrapeTarget Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/collector.md Evaluates dynamic filters, performs SNMP gets and walks, and returns raw SNMP PDUs. Filters may modify the walk and get lists before execution. Results are keyed by OID for later matching to metrics. ```APIDOC ## ScrapeTarget ### Description Evaluates dynamic filters, performs SNMP gets and walks, and returns raw SNMP PDUs. Filters may modify the walk and get lists before execution. Results are keyed by OID for later matching to metrics. ### Function Signature ```go func ScrapeTarget(snmp scraper.SNMPScraper, target string, auth *config.Auth, module *config.Module, logger *slog.Logger, metrics Metrics) (ScrapeResults, error) ``` ### Parameters #### Path Parameters - **snmp** (scraper.SNMPScraper) - Required - SNMP client instance - **target** (string) - Required - Target device address - **auth** (*config.Auth) - Required - Authentication configuration - **module** (*config.Module) - Required - Module defining what to walk/get - **logger** (*slog.Logger) - Required - Logger instance - **metrics** (Metrics) - Required - Exporter metrics for tracking ### Return Type - **`(ScrapeResults, error)`** — Collection of PDUs or error ### Throws - **`error`** if SNMP walk or get fails, or target rejects the request ### Example ```go scraper, err := scraper.NewGoSNMP(logger, "192.168.1.100", "", false) if err != nil { log.Fatal(err) } auth := cfg.Auths["public_v2"] auth.ConfigureSNMP(scraper.c, "") results, err := collector.ScrapeTarget( scraper, "192.168.1.100", auth, cfg.Modules["if_mib"], logger, metrics, ) if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Scrape SNMP Target Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/collector.md Evaluates dynamic filters, performs SNMP gets and walks, and returns raw SNMP PDUs. Filters may modify the walk and get lists before execution. Results are keyed by OID for later matching to metrics. ```go func ScrapeTarget(snmp scraper.SNMPScraper, target string, auth *config.Auth, module *config.Module, logger *slog.Logger, metrics Metrics) (ScrapeResults, error) ``` ```go scraper, err := scraper.NewGoSNMP(logger, "192.168.1.100", "", false) if err != nil { log.Fatal(err) } auth := cfg.Auths["public_v2"] auth.ConfigureSNMP(scraper.c, "") results, err := collector.ScrapeTarget( scraper, "192.168.1.100", auth, cfg.Modules["if_mib"], logger, metrics, ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### SNMPv3 Auth Only Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/QUICK-REFERENCE.md Example YAML configuration for SNMPv3 with authentication only (no privacy). ```yaml auths: my_v3: username: admin password: mypassword auth_protocol: SHA256 security_level: authNoPriv version: 3 ``` -------------------------------- ### GoSNMPWrapper.WalkAll Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/scraper.md Performs an SNMP WALK for SNMPv1 or BULKWALK for SNMPv2c/v3. Automatically retrieves all objects under the specified OID subtree. Uses BulkWalkAll for efficiency on v2c/v3, falls back to WalkAll for v1. ```APIDOC ## GoSNMPWrapper.WalkAll ### Description Retrieve all objects in an OID subtree. Performs an SNMP WALK for SNMPv1 or BULKWALK for SNMPv2c/v3. Automatically retrieves all objects under the specified OID subtree. Uses BulkWalkAll for efficiency on v2c/v3, falls back to WalkAll for v1. ### Method GET (Implicit, as it's an SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **oid** (string) - Required - OID subtree to walk (e.g., "1.3.6.1.2.1.2.2") ### Return Type `([]gosnmp.SnmpPDU, error)` — Slice of all PDUs in subtree or error ### Throws `error` if walk operation fails or times out ### Example ```go // Walk the interfaces subtree pdus, err := scraper.WalkAll("1.3.6.1.2.1.2.2.1") if err != nil { log.Fatal(err) } fmt.Printf("Found %d interface objects\n", len(pdus)) for _, pdu := range pdus { fmt.Printf("OID: %s, Value: %v\n", pdu.Name, pdu.Value) } ``` ``` -------------------------------- ### SNMP Exporter Metrics Endpoint Source: https://github.com/prometheus/snmp_exporter/blob/main/README.md Access the endpoint to get metrics about the operation of the exporter itself. ```text http://localhost:9116/metrics ``` -------------------------------- ### / (Root) Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/endpoints.md Serves as the landing page for the SNMP Exporter, providing a web UI form for manual SNMP scraping and links to other endpoints like /config and /metrics. ```APIDOC ## GET / ### Description Serves as the landing page for the SNMP Exporter, providing a web UI form for manual SNMP scraping and links to other endpoints like /config and /metrics. ### Method GET ### Endpoint / ### Parameters ### Response #### Success Response (200) Returns HTML content for the landing page. ### Example Fields - **Target**: Default `::1` - **Auth**: Default `public_v2` - **Module**: Default `if_mib` ``` -------------------------------- ### SNMPScraper Interface Definition Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/scraper.md Defines the contract for SNMP operations, including Get, WalkAll, Connect, Close, and SetOptions. ```go type SNMPScraper interface { Get([]string) (*gosnmp.SnmpPacket, error) WalkAll(string) ([]gosnmp.SnmpPDU, error) Connect() error Close() error SetOptions(...func(*gosnmp.GoSNMP)) } ``` -------------------------------- ### Build Prometheus Rules and Grafana Dashboards Source: https://github.com/prometheus/snmp_exporter/blob/main/snmp-mixin/README.md Build the Prometheus rules files (alerts.yaml, rules.yaml) and Grafana JSON dashboard files by running the make build command. ```bash $ make build ``` -------------------------------- ### SNMP Data Collection Module Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/types.md Specifies OIDs to walk or get and how to transform them into Prometheus metrics. Used by collectors. ```go type Module struct { Walk []string `yaml:"walk,omitempty"` Get []string `yaml:"get,omitempty"` Metrics []*Metric `yaml:"metrics"` WalkParams WalkParams `yaml:",inline"` Filters []DynamicFilter `yaml:"filters,omitempty"` } ``` ```yaml if_mib: walk: - 1.3.6.1.2.1.2.2.1 - 1.3.6.1.2.1.31.1.1.1 metrics: - name: ifInOctets oid: 1.3.6.1.2.1.2.2.1.10 type: counter indexes: - labelname: ifIndex type: gauge ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/INDEX.md Enable debug logging for troubleshooting by setting the log level to debug. ```bash snmp_exporter --log.level=debug ``` -------------------------------- ### Load SNMP Exporter Configuration from File Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/config.md Loads SNMP exporter configuration from one or more YAML files. Supports glob patterns and environment variable expansion for sensitive fields. Use this to initialize the exporter's settings. ```go func LoadFile(logger *slog.Logger, paths []string, expandEnvVars bool) (*Config, error) ``` ```go cfg, err := config.LoadFile(logger, []string{"snmp.yml"}, false) if err != nil { log.Fatal(err) } // Access loaded configuration for authName, auth := range cfg.Auths { fmt.Printf("Auth: %s\n", authName) } for moduleName, module := range cfg.Modules { fmt.Printf("Module: %s with %d metrics\n", moduleName, len(module.Metrics)) } ``` -------------------------------- ### SNMP Exporter Authentication Configuration (v2 and v3) Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/OVERVIEW.md Shows how to configure authentication credentials and protocols for SNMP v2 and v3. ```yaml public_v2: community: public version: 2 my_v3_secure: username: admin password: secret auth_protocol: SHA256 priv_password: privkey priv_protocol: AES security_level: authPriv version: 3 ``` -------------------------------- ### SNMP Exporter Configuration - Type Reference Summary Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/INDEX.md Provides a structural overview of the configuration objects used by the SNMP Exporter. ```text Config ├─ Auths: map[string]*Auth │ └─ Auth (SNMP credentials and settings) └─ Modules: map[string]*Module └─ Module ├─ Walk: []string ├─ Get: []string ├─ Metrics: []*Metric ├─ WalkParams └─ Filters: []DynamicFilter └─ DynamicFilter Metric ├─ Indexes: []*Index ├─ Lookups: []*Lookup ├─ RegexpExtracts: map[string][]RegexpExtract └─ EnumValues: map[int]string Index ├─ Labelname: string ├─ Type: string └─ EnumValues: map[int]string Lookup ├─ Labels: []string ├─ Labelname: string └─ Type: string ``` -------------------------------- ### Safe Configuration Reload Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Implements a safe configuration reload mechanism using read-write mutexes to prevent race conditions during in-flight scrapes. ```go type SafeConfig struct { mu sync.RWMutex C *config.Config } // Scrape path: Read lock func (sc *SafeConfig) GetConfig() { sc.mu.RLock() defer sc.mu.RUnlock() return sc.C // Safe to read } // Reload path: Write lock func (sc *SafeConfig) ReloadConfig(logger, paths, expandEnv) error { cfg, err := config.LoadFile(logger, paths, expandEnv) if err != nil { return err } sc.mu.Lock() defer sc.mu.Unlock() sc.C = cfg // Atomic swap // Initialize metric labels for new modules for module := range sc.C.Modules { snmpCollectionDuration.WithLabelValues(module) } return nil } ``` -------------------------------- ### Configure GoSNMP Client Options Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/scraper.md Applies configuration functions to the underlying GoSNMP client, such as setting timeouts, retries, or context. ```go func (g *GoSNMPWrapper) SetOptions(fns ...func(*gosnmp.GoSNMP)) ``` ```go scraper.SetOptions( func(g *gosnmp.GoSNMP) { g.Timeout = 5 * time.Second g.Retries = 3 }, func(g *gosnmp.GoSNMP) { g.Context = ctx }, ) ``` -------------------------------- ### Dynamic Filter Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/configuration.md Conditionally include OID instances based on values of other OIDs. This example filters for interfaces with an operational status of 'up'. ```yaml modules: interfaces: walk: - 1.3.6.1.2.1.2.2.1 filters: - oid: 1.3.6.1.2.1.2.2.1.8 targets: [1.3.6.1.2.1.2.2.1.10] values: ['1'] # Only interfaces with ifOperStatus=up ``` -------------------------------- ### Build Metric Tree Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Constructs a trie (MetricNode) from a list of SNMP metrics for efficient lookup. ```go func buildMetricTree(metrics []*config.Metric) *MetricNode { head := &MetricNode{children: map[int]*MetricNode{}} for _, metric := range metrics { // For metric OID "1.3.6.1.2.1.2.2.1.10" oidList := oidToList("1.3.6.1.2.1.2.2.1.10") // → [1, 3, 6, 1, 2, 1, 2, 2, 1, 10] current := head for _, component := range oidList { if _, exists := current.children[component]; !exists { current.children[component] = &MetricNode{children: map[int]*MetricNode{}} } current = current.children[component] } current.metric = metric // Store metric at leaf } return head } ``` -------------------------------- ### Bad Request Response (Missing Target) Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/endpoints.md Example of a 400 Bad Request response when the 'target' parameter is missing. The exporter requires a target to perform a scrape. ```text 'target' parameter must be specified once ``` -------------------------------- ### View SNMP Exporter Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/errors.md Fetch and view the current SNMP Exporter configuration to validate it on load. ```bash curl http://localhost:9116/config ``` -------------------------------- ### GoSNMPWrapper.Connect Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/scraper.md Establishes a network connection to the SNMP target, which is required before performing Get or WalkAll operations. It handles connection timeouts and errors, wrapping them with additional context. ```APIDOC ## GoSNMPWrapper.Connect ### Description Establish a network connection to the SNMP target. ### Signature ```go func (g *GoSNMPWrapper) Connect() error ``` ### Return Type `error` — nil on success, error on failure ### Throws `error` if connection fails or is canceled ### Description Opens a UDP or TCP connection to the target. Must be called before any Get or WalkAll operations. Wraps timeouts from context cancellation with a helpful message. ### Example ```go if err := scraper.Connect(); err != nil { log.Fatalf("Failed to connect to target: %v", err) } defer scraper.Close() ``` ``` -------------------------------- ### Enable Environment Variable Expansion in Auth Configuration Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/configuration.md Use the --config.expand-environment-variables flag to enable environment variable substitution in auth configuration fields like username and password. Required variables must exist. ```bash export SNMP_USERNAME=admin export SNMP_PASSWORD=secret123 ./snmp_exporter --config.expand-environment-variables ``` ```yaml auths: my_v3_user: username: ${SNMP_USERNAME} password: ${SNMP_PASSWORD} auth_protocol: SHA256 priv_protocol: AES priv_password: ${SNMP_PRIV_PASSWORD} security_level: authPriv version: 3 ``` -------------------------------- ### Define SNMP Modules for OID Collection Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/configuration.md Configure SNMP modules to specify which OID subtrees to walk or which specific OIDs to get, and how to map them to Prometheus metrics. ```yaml modules: if_mib: walk: - 1.3.6.1.2.1.2.2.1 - 1.3.6.1.2.1.31.1.1.1 get: - 1.3.6.1.2.1.1.1.0 metrics: - name: ifInOctets oid: 1.3.6.1.2.1.2.2.1.10 type: counter help: Octets received on interface indexes: - labelname: ifIndex type: gauge ``` -------------------------------- ### Counter64 Wrapping for Precision Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/ARCHITECTURE.md Demonstrates how large SNMP Counter64 values can exceed Prometheus's 53-bit mantissa precision. Wrapping preserves precision by using the modulo operator. ```go // Without wrapping: may lose precision above 2^53 value = 2^54 = 18014398509481984.0 (rounded) // With wrapping: stays within precision value = (2^54) % 2^53 = 2 (preserved) ``` -------------------------------- ### Create a Named Module Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/collector.md Wraps a config.Module with its name for identification during collection. Used when registering modules with a Collector. ```go func NewNamedModule(name string, module *config.Module) *NamedModule ``` ```go nm := collector.NewNamedModule("if_mib", cfg.Modules["if_mib"]) ``` -------------------------------- ### Configure GoSNMP Client with Authentication Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/config.md Applies authentication settings from an Auth struct to a GoSNMP client. Supports SNMP v1, v2c, and v3. Use this to prepare a GoSNMP client for making SNMP requests based on loaded configuration. ```go func (c Auth) ConfigureSNMP(g *gosnmp.GoSNMP, snmpContext string) ``` ```go auth := cfg.Auths["my_v3_auth"] g := &gosnmp.GoSNMP{ Target: "192.168.1.100", Port: 161, } auth.ConfigureSNMP(g, "") // Use auth.ContextName auth.ConfigureSNMP(g, "vrf-mgmt") // Override with specific context ``` -------------------------------- ### Manually Test SNMP Access (SNMPv2c) Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/errors.md Use snmpget to manually test SNMP access to a device using SNMPv2c. ```bash snmpget -v 2c -c public 192.168.1.100 1.3.6.1.2.1.1.1.0 ``` -------------------------------- ### Perform SNMP GET Request Source: https://github.com/prometheus/snmp_exporter/blob/main/_autodocs/api-reference/scraper.md Use this function to retrieve specific OIDs from an SNMP agent. Ensure you handle potential errors and check the returned packet for results. ```go func (g *GoSNMPWrapper) Get(oids []string) (*gosnmp.SnmpPacket, error) ``` ```go packet, err := scraper.Get([]string{ "1.3.6.1.2.1.1.1.0", // sysDescr "1.3.6.1.2.1.1.3.0", // sysUpTime }) if err != nil { log.Fatal(err) } for _, variable := range packet.Variables { fmt.Printf("OID: %s, Value: %v\n", variable.Name, variable.Value) } ```