Fact-checked by Grok 2 weeks ago

Multi Router Traffic Grapher

The Multi Router Traffic Grapher (MRTG) is a tool for monitoring and measuring the traffic load on network links, utilizing the (SNMP) to query devices such as routers and generate web-accessible graphs that visualize data trends over time. Developed by Tobias Oetiker in the summer of 1994 at in the , MRTG was originally created to track the usage of a 64 kbit/s connection serving over 1,000 computers, with its first public release occurring in spring 1995. By 1998, it had been adopted by approximately 17,500 hosts across more than 11,400 second-level domains worldwide, demonstrating its rapid growth as a standard for . Written primarily in , MRTG operates by polling SNMP data at configurable intervals—typically every five minutes—processing it to calculate rates, and producing pages with embedded images showing traffic patterns for daily, weekly, monthly, and yearly views. Key features of MRTG include its cross-platform compatibility with Unix/, Windows, and systems, as well as its use of lossy data storage techniques that consolidate historical information without unbounded file growth, enabling efficient long-term monitoring of hundreds of interfaces. Released under the , it supports not only network traffic but also diverse metrics from non-traditional devices like weather stations or vending machines, making it versatile for system administrators. The tool evolved through versions, with MRTG in 1997 introducing performance enhancements and scalability for up to 500 ports, and it can optionally use the Round-Robin Database (RRD) tool for improved speed and flexibility in data handling. Although its core codebase was last updated in 2022, MRTG remains a foundational open-source solution in .

Overview

Purpose and Capabilities

The Multi Router Traffic Grapher (MRTG) is free, open-source software written in Perl designed for monitoring and graphing the traffic load on network links and devices. It primarily measures inbound and outbound traffic—commonly referred to as input and output—on SNMP-enabled devices such as routers, switches, and servers, enabling users to visualize usage trends over time through generated HTML pages containing PNG images. This core functionality leverages SNMP as the standard protocol for data collection to provide insights into network performance and capacity planning. Beyond basic network traffic monitoring, MRTG's capabilities extend to tracking a wide range of SNMP variables, including system load, login sessions, , temperature, and even custom metrics derived from external scripts or programs. It supports combining multiple data sources into a single graph and offers views spanning daily, weekly, monthly, and yearly periods, making it versatile for diverse monitoring needs across various hardware and environmental metrics. MRTG operates cross-platform, compatible with Unix/Linux, Windows, Mac OS, and systems. It is licensed under the GNU General Public License, ensuring its availability as freely modifiable and distributable software. The latest stable version, 2.17.10, was released on January 19, 2022.

History and Development

The Multi Router Traffic Grapher (MRTG) was developed in the summer of 1994 by Tobias Oetiker, then a at in the , to monitor traffic on a single 64 kbit/s external link. Initially conceived as a simple hack using and external tools for SNMP queries and GIF generation, it addressed the need for visualizing network usage without complex setups. This early version was limited in scope, capable of monitoring only about 20 router ports due to performance constraints from its reliance on lossy ASCII log files and external graphing libraries. MRTG-1.0 was released in spring 1995 as a configurable script, initially focused exclusively on router traffic monitoring, and quickly gained popularity after being made available on the . By early , collaboration with Dave Rand led to significant enhancements, including the rewriting of time-critical sections in C code via the "rateup" utility, which improved performance by up to 40 times and allowed monitoring of hundreds of interfaces. This effort culminated in the release of MRTG-2.0 in January 1997, incorporating the library for faster image generation and a SNMP module for better portability across systems. Community contributions during beta testing further refined the tool through bug fixes and feature patches. Over time, MRTG evolved from a router-specific into a general-purpose tool, capable of tracking diverse metrics beyond just traffic. A key milestone in this development was the initiation of MRTG-3 in November 1997, which introduced the Round Robin Database (RRD) Tool for more efficient, fixed-size storage of time-series data; was later released independently in 1998 to handle graphing and data consolidation for broader applications. Tobias Oetiker has maintained the project since its inception, hosting it at oss.oetiker.ch, with ongoing updates to ensure compatibility, such as the addition of SNMPv2c support for 64-bit counters to mitigate wrapping issues on high-speed interfaces. By August 1998, MRTG was in use on an estimated 17,500 hosts worldwide.

Technical Operation

Data Collection Methods

The Multi Router Traffic Grapher (MRTG) primarily collects data through the (SNMP), polling network devices at regular to retrieve traffic counters. By default, MRTG performs these polls every 5 minutes, though this interval is configurable via the Interval directive in the , allowing adjustments for different monitoring needs. Specifically, it queries standard SNMP objects such as ifInOctets for inbound traffic and ifOutOctets for outbound traffic on network interfaces, capturing byte counts to measure utilization. MRTG supports SNMP version 1 (SNMPv1) and version 2c (SNMPv2c), with the latter enabling 64-bit support to prevent rollover issues inherent in 32-bit counters, which cap at approximately 4 gigabytes before wrapping around and causing inaccurate readings. Authentication occurs via community strings, specified in the target configuration (e.g., public@router), which serve as read-only credentials for accessing the device's (MIB). SNMP version 3 (SNMPv3) is also supported when the Net::SNMP module is available, providing enhanced security features like user-based authentication. For scenarios where SNMP is unavailable or unsuitable, MRTG accepts input from external scripts or programs that output data in a specific format: four lines containing the current input value, current output value, system uptime in timeticks, and a descriptive name for the target. This allows monitoring of non-SNMP sources, such as log files, custom applications, or other metrics, by piping the numeric values directly into MRTG's data acquisition process. Polling targets are defined in the MRTG configuration file using the Target keyword, which can specify hostnames, IP addresses, ports, and OIDs (Object Identifiers) for precise data retrieval. A single MRTG run processes multiple targets from the configuration, optimizing SNMP requests by caching results for duplicate targets to minimize network load. Rate limiting is enforced through directives like MaxBytes, which discards data points exceeding a predefined maximum (e.g., physical link capacity) to prevent processing implausible values from misconfigurations or attacks. Error handling during collection includes logging SNMP timeouts, unreachable hosts, or invalid responses to a specified log file or syslog, configurable via the --logging option. Invalid or out-of-range data points are skipped, ensuring only reliable measurements proceed to storage in round-robin databases, as detailed in subsequent sections on data processing.

Data Processing and Storage

MRTG processes data obtained from SNMP queries on network devices, focusing on two counters per monitored target: input and output byte counts, which can be 32-bit or 64-bit depending on the SNMP version used. For each polling interval, the rateup component calculates traffic rates in bytes per second by computing the difference () between the current values and those from the previous poll, then dividing by the elapsed time since the last update. This approach handles both types, with SNMPv2c and SNMPv3 supporting 64-bit ifHighCapacity (ifHC) s to minimize wrap-around issues in high-traffic scenarios. To manage counter wrap-around, particularly for 32-bit s, MRTG employs parameters such as MaxBytes, which sets the expected maximum volume per polling interval, and AbsMax, typically twice MaxBytes, to detect anomalies. If the computed delta exceeds AbsMax, MRTG interprets this as a counter wrap and adjusts the by subtracting the (e.g., 2^32 for 32-bit) to derive the correct value, ensuring accurate rate computations even when s . For storage, MRTG integrates with RRDTool to use the Round Robin Database (RRD) format, replacing the traditional unbounded log files with fixed-size archives that prevent disk space growth over time. Upon enabling LogFormat: rrdtool in the configuration file, MRTG creates an RRD file for each target during the initial run, converting any existing log data if available, and subsequently updates these files with each poll using RRDTool's update mechanism. This integration leverages RRDTool's efficiency, reducing MRTG's runtime to approximately 20% of its classic mode by deferring graph generation and focusing solely on data logging. RRD storage employs multiple Round Robin Archives (RRAs) for data consolidation, aggregating values using average, maximum, and last (current) functions to maintain historical summaries without excessive storage demands. By default, MRTG configures RRAs to retain approximately 1 day of high-resolution at the polling (e.g., 5 minutes), 17 days of 30-minute averages (800 rows), 2 months of 2-hour averages (800 rows), and 2 years of daily averages (800 rows), providing compact files that support long-term analysis while keeping file sizes manageable. These defaults can be adjusted per target using options like RRDRowCount for the base or RRDRowCount1d for yearly , allowing customization based on retention needs. In terms of , the RRD-based approach enables MRTG to efficiently hundreds of , as the fixed-size databases and optimized logging minimize I/O operations. MRTG typically runs as a job every 5 minutes to perform these processing and storage tasks in batch, with options like Forks (default 1, up to system limits) allowing parallel execution on systems to further enhance for large deployments.

Output and Visualization

Graph Generation

MRTG generates visual representations of network data by creating images from stored log files (or optionally from Database (RRD) files when using integration), utilizing the library—a C-based graphics library integrated via bindings—to plot rates over specified time periods. In earlier versions prior to 2.0, format was used due to initial library limitations, but has been the standard since to avoid patent issues with compression. The process involves rateup, a companion C program, which updates the log files (or RRD files with ) and triggers graph rendering by extracting averaged data points and scaling the vertical axis dynamically based on observed peak values for optimal visibility. The primary graph type is a depicting input as a filled area, output as a line overlaid on the input, and additional lines in darker or for maximum input and output peaks, respectively; values can also be plotted in configurable colors to highlight trends. These graphs emphasize conceptual flow patterns rather than raw counters, with the vertical axis auto-scaled to encompass the highest recorded rates during the period, ensuring that minor fluctuations remain discernible without compressing the scale. Separate graphs are produced for daily (400x100 pixels at 5-minute ), weekly, monthly, and yearly views, where longer periods automatically consolidate finer-grained data from the log files (or RRD) into hourly or daily averages to maintain performance and readability. Graph legends include annotations for the current rate, time-averaged rate, and maximum rate, providing quick quantitative context; the dorelpercent option can be enabled to overlay a line showing the relative percentage of inbound to outbound for . Customization is achieved through the , allowing users to adjust colors (e.g., via codes like GREEN#00eb0c for input), image dimensions (using XSize and YSize parameters), titles (via PNGTitle), and Y-axis labels (via YLegend, such as "Bits per Second") to tailor graphs to specific monitoring needs.

Web Interface and Views

The Multi Router Traffic Grapher (MRTG) delivers its monitoring data through a static web interface composed of pages that embed graphs generated from logged traffic metrics. These pages are output to a configurable directory, enabling straightforward access via any standard without requiring specialized software or plugins. MRTG produces dedicated HTML files for each monitored target, named based on the target's identifier (e.g., targetname.html), stored in the WorkDir directory such as /var/www/mrtg on typical systems. An accompanying index page, created using the bundled indexmaker utility, compiles a listing of all targets, often featuring compact daily graph previews in a tabular layout with optional section-based organization for hierarchical grouping. This file arrangement employs relative hyperlinks, facilitating deployment portability across varied configurations. User views support hierarchical navigation by time period—daily, weekly, monthly, and yearly—along with per-target selection. Individual target pages display the selected period's alongside numeric summaries of peak and average traffic rates, plus inbound/outbound values, complemented by direct to other time views and the main for seamless traversal. During each MRTG run, the script regenerates all relevant pages and associated images, replacing prior iterations while preserving log file integrity through incremental data appends that retain historical records spanning up to two years. This automated refresh mechanism aligns with MRTG's polling cycle, typically every five minutes via or daemon mode, to maintain current visualizations. The interface prioritizes minimalism with purely static content, eschewing dynamic scripting to minimize server load and ensure compatibility across browsers, including legacy versions, while relying on basic and CSS2 for presentation.

Features

Core Monitoring Functions

The Multi Router Traffic Grapher (MRTG) primarily monitors interface traffic utilization, bandwidth usage, and error rates on routers, switches, and hosts by querying (SNMP) counters at regular intervals, typically every five minutes, to generate time-series graphs of network activity. This core function enables administrators to visualize inbound and outbound traffic patterns, peak loads, and anomalies such as packet discards or collisions, providing insights into without requiring specialized beyond standard SNMP-enabled devices. MRTG tracks a wide range of SNMP Object Identifiers (OIDs) to capture diverse system metrics, including CPU load, memory usage, disk availability, and environmental sensors such as temperature in server rooms. For instance, it can poll OIDs from systems to monitor utilization as a or disk in gigabytes, extending beyond pure network traffic to holistic health. These capabilities rely on SNMP for standard metrics, allowing flexible configuration of any accessible OID to suit specific monitoring needs. A single MRTG instance supports monitoring multiple targets, accommodating over 200 network links on standard hardware such as a modest UNIX system, with configuration options for each target including units (bits or bytes) and scaling factors to normalize data across disparate interfaces. This is demonstrated in deployments handling thousands of variables from hundreds of interfaces, ensuring efficient resource use while maintaining granular control over display preferences. Rate calculations form a foundational aspect of MRTG's operation, where it calculates rates from raw byte counters provided by SNMP, displaying in bytes per second by default, with an option to convert to bits per second for intuitive display, accounting for wrap-around in 32-bit or 64-bit counters via SNMPv2c support. For asymmetric links, such as those with differing upload and download capacities in DSL , MRTG applies separate to accurately represent each direction's utilization without . MRTG's extensibility enhances its core monitoring through integration with external scripts, which fetch non-standard data sources and feed them into the graphing engine, enabling tracking of application-specific metrics like request counts or database query rates. These scripts, often written in , allow customization for proprietary protocols or local system calls, broadening MRTG's applicability to diverse environments while preserving its lightweight design.

Alerting and Customization

MRTG supports threshold-based alerting through configurable upper and lower limits for input and output values, enabling notifications when these are breached or recovered. Administrators can define per-target minimum and maximum using options such as MaxBytes for absolute values or percentages relative to peak capacity, for example, setting an 80% utilization limit to trigger alerts on high loads. Upon crossing a threshold boundary, MRTG executes specified programs or scripts, which can send notifications via an external SMTP configured with ThreshMailServer, ThreshMailSender, and ThreshMailAddress. is adjustable via the global ThreshHyst parameter to prevent rapid-fire alerts, typically set to a small like 5% to ensure stability in fluctuating conditions. Customization in MRTG allows fine-tuning of visualizations and behaviors on a per-target basis, including graph colors defined via the Colours keyword for specifying hex values like GREEN#00eb0c and BLUE#1000ff to match organizational branding. Titles, axis labels, and value formatting are also adjustable; for instance, the Title option sets descriptive HTML page headers, YLegend customizes y-axis labels such as "Bits per Second," and Options enables transformations like bits to multiply values by 8 or perminute to scale by 60 for more intuitive displays. Globally, settings control image output formats—defaulting to PNG with extensibility via RRDTool integration—and logging verbosity through the --logging command-line flag, which directs output to files or Windows event logs for debugging purposes. MRTG integrates seamlessly with for automated scheduling, running polls at configurable intervals via the Interval keyword, with a default of 5 minutes and a practical minimum of 1 minute to balance monitoring granularity against system load. Error and threshold event logging can be directed to files, though direct support requires external scripting; environment variables passed via SetEnv facilitate with custom notification scripts. For advanced setups, SNMPv2c is enabled in definitions (e.g., using :2: in the Target line) to perform queries, reducing overhead compared to SNMPv1. Graph scaling options include growright to extend charts horizontally over time, while averages incorporate all daily data points without built-in weekend exclusions, though post-processing scripts can filter these if needed. Despite its flexibility, MRTG has limitations in alerting and customization, lacking a built-in for configuration and relying instead on manual editing of text-based .cfg files or generation via helper tools like cfgmaker. Threshold programs must be externally implemented for complex actions beyond basic , and polling remains single-threaded, potentially constraining in large deployments without additional wrappers. warnings for breaches tie directly into generation processes, providing contextual links to affected visualizations.

Deployment and Usage

Installation Procedures

Installing MRTG requires specific prerequisites to ensure compatibility and functionality across supported platforms. The core requirement is Perl version 5.005 or higher, as MRTG is implemented in Perl, with SNMP support provided through modules such as those from Net-SNMP for network device querying. Additionally, the GD graphics library is essential for generating graphs, often accompanied by dependencies like libpng and zlib; these can be installed via system package managers or compiled from source if not available. Optionally, RRDTool can be integrated for enhanced data storage, requiring the RRDs Perl module. A web server, such as Apache, is necessary to host and view the generated HTML pages and PNG images. On Debian-based systems such as , MRTG can be installed directly from the repositories using the package manager, which handles dependencies automatically: sudo apt update && [sudo](/page/Sudo) apt install mrtg. This method is recommended for simplicity on supported distributions. For systems requiring compilation or custom installation, such as other Unix/ variants, begin by ensuring a compiler like is installed, then download the latest MRTG tarball from the official repository. Extract the archive in a source directory, such as /usr/local/src, and if required, compile supporting libraries: for zlib, run ./configure, make, and make install; repeat similarly for libpng with appropriate CFLAGS for GD compatibility, followed by GD compilation using make with specified include and library paths. To compile MRTG itself, execute ./configure --prefix=/usr/local/mrtg-2 (adjusting the prefix as needed, potentially with --with-pkgconfig-path for library detection), then make and make install to place binaries in the target directory. On Windows, installation leverages pre-built Perl scripts rather than compilation. Download the MRTG ZIP archive and extract it to a directory like C:\mrtg-2.17.10, ensuring ActivePerl (version 5.8 or later) is installed on the system. Add the Perl binary path (e.g., C:\Perl\bin) to the system environment variables via the Control Panel under System > Environment, then verify by opening a Command Prompt, navigating to the MRTG bin subdirectory, and running perl mrtg, which should output an error indicating a missing configuration file if successful. No MSI installer is provided officially; manual extraction suffices for setup. To verify the installation, run mrtg --version from the command line on Unix/ or perl mrtg on Windows, confirming the tool's presence and integration. Test SNMP connectivity using the snmpwalk utility from Net-SNMP against a target device, such as snmpwalk -v1 -c public [localhost](/page/Localhost), to ensure data retrieval works prior to full deployment. Common issues during installation include missing libraries like libgd, which can be resolved by installing via package managers (e.g., apt install libgd-dev on Debian-based systems or yum install gd-devel on Red Hat-based ones) or compiling them manually. On , compilation failures often stem from undetected libraries, addressed by specifying paths in the ; on Windows, path-related errors arise if is not in the system , fixable through adjustments. Ensure the user account has write permissions to directories for logs and graphs, such as /var/www/html/mrtg, to prevent runtime errors. Initial runs may report missing log files, which is expected and resolves after the first two executions.

Configuration Essentials

The MRTG configuration file is a plain text file with a .cfg extension, consisting of keywords that begin at the start of a line, while continuation lines are indented with spaces or tabs. Empty lines and lines starting with a # are ignored as comments, and additional files can be included using the Include: directive. Essential global directives include WorkDir, which specifies the directory where log files and generated pages are stored, such as WorkDir: /var/www/mrtg. Per-target sections are defined using an alias in square brackets, like [eth0], followed by key directives such as , which identifies the sources to monitor; MaxBytes, which sets the maximum for counters to graphs appropriately; , which provides a descriptive label for the generated page; and YLegend, which labels the Y-axis, typically as "Bits per Second" for . The Target directive supports SNMP polling by specifying Object Identifiers (OIDs) in the format oid_in:community@hostname:oid_out, where oid_in and oid_out reference input and output counters, respectively, such as those for interface octets as described in SNMP data collection methods. Alternatively, for non-SNMP sources, Target can point to an external script that outputs four lines of data in MRTG's expected format. Polling intervals are set globally with the Interval directive in minutes (default: 5), and MRTG can run continuously using RunAsDaemon: Yes for frequent updates, or be scheduled via cron for periodic execution. A representative example for monitoring a router's Ethernet interface on a 100 Mbps link is:
WorkDir: /var/www/mrtg
Target[eth0]: 1.3.6.1.2.1.2.2.1.10.1:public@router:1.3.6.1.2.1.2.2.1.16.1
MaxBytes[eth0]: 12500000
Title[eth0]: Traffic on Ethernet 0
YLegend[eth0]: Bits per Second
This configuration polls the ifInOctets and ifOutOctets OIDs for interface index 1 using the community string on the host "router," with MaxBytes scaled to 12.5 MB/s to match the link speed. To automate initial configuration, the cfgmaker script queries SNMP devices via a provided community string and host list, generating a base .cfg file with per-interface targets; for instance, cfgmaker --global "WorkDir: /var/www/mrtg" public@router > mrtg.cfg creates entries for all active interfaces on the router. Similarly, indexmaker processes one or more .cfg files to produce an index page aggregating graph links, using indexmaker mrtg.cfg --output index.html for a basic daily view table. For validation, execute mrtg mrtg.cfg in a dry-run , which fetches SNMP data to verify targets without updating log files on the first pass, displaying any errors such as unreachable hosts or invalid OIDs. can be enabled via the command-line option --logging /var/log/mrtg.log to capture detailed output for during setup.

References

  1. [1]
    Tobi Oetiker's MRTG - The Multi Router Traffic Grapher
    Mar 5, 2017 · MRTG is for you. It will monitor SNMP network devices and draw pretty pictures showing how much traffic has passed through each interface.MRTG Download · Unix/Linux · Windows · MRTG Documentation
  2. [2]
    None
    ### Summary of MRTG Content
  3. [3]
    NAME DESCRIPTION HIGHLIGHTS DETAILS HISTORY ... - MRTG
    The Multi Router Traffic Grapher (MRTG) is a tool to monitor the traffic load on network links. MRTG generates HTML pages containing PNG images.
  4. [4]
  5. [5]
  6. [6]
  7. [7]
  8. [8]
    MRTG Reference - OETIKER+PARTNER AG
    This feature gets activated by switching to SNMPv2c. Unfortunately not all devices support SNMPv2c yet. If it works, this will prevent your counters from ...Missing: changelog | Show results with:changelog
  9. [9]
    NAME SYNOPSIS RRDTOOL INTEGRATION FUTURE ... - MRTG
    AUTHOR. NAME; SYNOPSIS; RRDTOOL INTEGRATION; FUTURE; AUTHOR. mrtg-rrd - How to use RRDtool with MRTG. After using MRTG for some time you may find some ...
  10. [10]
    MRTG 2.17.10 configuration reference - Ubuntu Manpage
    This feature gets activated by switching to SNMPv2c. Unfortunately not all devices support SNMPv2c yet. If it works, this will prevent your counters from ...Missing: changelog | Show results with:changelog
  11. [11]
  12. [12]
    NAME DESCRIPTION PREPARATION LIBRARY ... - MRTG
    MRTG generates traffic graphs in the PNG format. To be able to do this it needs several 3rd party libraries. When compiling these libraries I urge you to ...
  13. [13]
    how to setup mrtg as a windows service - OETIKER+PARTNER AG
    The first thing we do in setting up MRTG is making a default config file. Get to a cmd prompt and change to the c:\mrtg-2.17.4\bin directory.
  14. [14]
    NAME SYNOPSIS OPTIONS DESCRIPTION EXAMPLES ... - MRTG
    Unfortunately the interface numbering scheme in an SNMP tree can change. Some routers change their numbering when new interfaces are added, others change thier ...Missing: SNMPv2 | Show results with:SNMPv2<|control11|><|separator|>