Multi Router Traffic Grapher
The Multi Router Traffic Grapher (MRTG) is a free software tool for monitoring and measuring the traffic load on network links, utilizing the Simple Network Management Protocol (SNMP) to query devices such as routers and generate web-accessible graphs that visualize data trends over time.[1][2]
Developed by Tobias Oetiker in the summer of 1994 at De Montfort University in the United Kingdom, MRTG was originally created to track the usage of a 64 kbit/s internet connection serving over 1,000 computers, with its first public release occurring in spring 1995.[2] 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 network performance visualization.[2] Written primarily in Perl, MRTG operates by polling SNMP data at configurable intervals—typically every five minutes—processing it to calculate rates, and producing HTML pages with embedded PNG images showing traffic patterns for daily, weekly, monthly, and yearly views.[1][2]
Key features of MRTG include its cross-platform compatibility with Unix/Linux, Windows, and NetWare 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.[1][2] Released under the GNU General Public License, 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.[1] The tool evolved through versions, with MRTG 2.0 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.[2][3] Although its core codebase was last updated in 2022, MRTG remains a foundational open-source solution in network management.[1][4]
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.[1][5] 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.[5] This core functionality leverages SNMP as the standard protocol for data collection to provide insights into network performance and capacity planning.[5]
Beyond basic network traffic monitoring, MRTG's capabilities extend to tracking a wide range of SNMP variables, including system load, login sessions, modem availability, temperature, and even custom metrics derived from external scripts or programs.[5] 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.[5]
MRTG operates cross-platform, compatible with Unix/Linux, Windows, Mac OS, and NetWare systems.[1] It is licensed under the GNU General Public License, ensuring its availability as freely modifiable and distributable software.[1] 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 system administrator at De Montfort University in the United Kingdom, to monitor traffic on a single 64 kbit/s external Internet link. Initially conceived as a simple hack using Perl and external tools for SNMP queries and GIF generation, it addressed the need for visualizing network usage without complex setups.[5] 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 Perl script, initially focused exclusively on router traffic monitoring, and quickly gained popularity after being made available on the Internet.[5] By early 1996, 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 GD library for faster image generation and a Perl SNMP module for better portability across systems. Community contributions during beta testing further refined the tool through bug fixes and feature patches.[5]
Over time, MRTG evolved from a router-specific utility into a general-purpose network monitoring 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; RRDTool 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.[5] 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 Simple Network Management Protocol (SNMP), polling network devices at regular intervals to retrieve traffic counters. By default, MRTG performs these polls every 5 minutes, though this interval is configurable via the Interval directive in the configuration file, allowing adjustments for different monitoring needs.[5][6] 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.[5][7]
MRTG supports SNMP version 1 (SNMPv1) and version 2c (SNMPv2c), with the latter enabling 64-bit counter support to prevent rollover issues inherent in 32-bit counters, which cap at approximately 4 gigabytes before wrapping around and causing inaccurate readings.[7] 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 Management Information Base (MIB).[7] SNMP version 3 (SNMPv3) is also supported when the Net::SNMP Perl module is available, providing enhanced security features like user-based authentication.[8]
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.[7] 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.[7]
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.[7] A single MRTG run processes multiple targets from the configuration, optimizing SNMP requests by caching results for duplicate targets to minimize network load.[7] 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.[9]
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.[10] 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.[9]
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.[10] For each polling interval, the rateup component calculates traffic rates in bytes per second by computing the difference (delta) between the current counter values and those from the previous poll, then dividing by the elapsed time since the last update.[10] This approach handles both counter types, with SNMPv2c and SNMPv3 supporting 64-bit ifHighCapacity (ifHC) counters to minimize wrap-around issues in high-traffic scenarios.[10]
To manage counter wrap-around, particularly for 32-bit counters, MRTG employs configuration parameters such as MaxBytes, which sets the expected maximum traffic volume per polling interval, and AbsMax, typically twice MaxBytes, to detect anomalies.[10] If the computed delta exceeds AbsMax, MRTG interprets this as a counter wrap and adjusts the calculation by subtracting the counter range (e.g., 2^32 for 32-bit) to derive the correct value, ensuring accurate rate computations even when counters overflow.[10]
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.[3] 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.[3] 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.[3]
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.[10] By default, MRTG configures RRAs to retain approximately 1 day of high-resolution data at the polling interval (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.[10] These defaults can be adjusted per target using options like RRDRowCount for the base interval or RRDRowCount1d for yearly data, allowing customization based on retention needs.[10]
In terms of performance, the RRD-based approach enables MRTG to efficiently monitor hundreds of targets, as the fixed-size databases and optimized logging minimize I/O operations.[3] MRTG typically runs as a cron 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 Unix-like systems to further enhance scalability for large deployments.[10]
Output and Visualization
Graph Generation
MRTG generates visual representations of network traffic data by creating PNG images from stored log files (or optionally from Round-Robin Database (RRD) files when using RRDtool integration), utilizing the GD library—a C-based graphics library integrated via Perl bindings—to plot traffic rates over specified time periods.[5] In earlier versions prior to 2.0, GIF format was used due to initial GD library limitations, but PNG has been the standard since to avoid patent issues with GIF compression. The process involves rateup, a companion C program, which updates the log files (or RRD files with RRDtool) and triggers graph rendering by extracting averaged data points and scaling the vertical axis dynamically based on observed peak traffic values for optimal visibility.[11]
The primary graph type is a line graph depicting input traffic as a green filled area, output traffic as a blue line overlaid on the input, and additional lines in darker green or violet for maximum input and output peaks, respectively; average values can also be plotted in configurable colors to highlight trends.[10] These graphs emphasize conceptual traffic 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 resolution), 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.[10] 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 traffic for capacity planning.[11]
Customization is achieved through the configuration file, allowing users to adjust colors (e.g., via hexadecimal 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.[10]
Web Interface and Views
The Multi Router Traffic Grapher (MRTG) delivers its monitoring data through a static web interface composed of HTML pages that embed PNG graphs generated from logged traffic metrics. These pages are output to a configurable web server directory, enabling straightforward access via any standard web browser without requiring specialized software or plugins.[5]
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 Unix-like 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 web server configurations.[10][12]
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 graph alongside numeric summaries of peak and average traffic rates, plus inbound/outbound values, complemented by direct links to other time views and the main index for seamless traversal.[5][12]
During each MRTG run, the script regenerates all relevant HTML pages and associated PNG 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 cron or daemon mode, to maintain current visualizations.[10][13]
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 HTML and CSS2 for presentation.[13]
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 Simple Network Management Protocol (SNMP) counters at regular intervals, typically every five minutes, to generate time-series graphs of network activity.[2] 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 network performance without requiring specialized hardware beyond standard SNMP-enabled devices.[5]
MRTG tracks a wide range of SNMP Object Identifiers (OIDs) to capture diverse system metrics, including CPU load, memory usage, disk space availability, and environmental sensors such as temperature in server rooms.[2] For instance, it can poll OIDs from host systems to monitor processor utilization as a percentage or free disk space in gigabytes, extending beyond pure network traffic to holistic infrastructure health.[5] These capabilities rely on SNMP for standard metrics, allowing flexible configuration of any accessible OID to suit specific monitoring needs.[2]
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.[5] This scalability is demonstrated in deployments handling thousands of variables from hundreds of interfaces, ensuring efficient resource use while maintaining granular control over display preferences.[2]
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.[5] For asymmetric links, such as those with differing upload and download capacities in DSL connections, MRTG applies separate scaling to accurately represent each direction's utilization without distortion.[2]
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 web server request counts or database query rates.[5] These scripts, often written in Perl, allow customization for proprietary protocols or local system calls, broadening MRTG's applicability to diverse environments while preserving its lightweight design.[2]
Alerting and Customization
MRTG supports threshold-based alerting through configurable upper and lower limits for input and output traffic values, enabling notifications when these thresholds are breached or recovered. Administrators can define per-target minimum and maximum thresholds 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 traffic loads. Upon crossing a threshold boundary, MRTG executes specified programs or scripts, which can send email notifications via an external SMTP server configured with ThreshMailServer, ThreshMailSender, and ThreshMailAddress. Hysteresis is adjustable via the global ThreshHyst parameter to prevent rapid-fire alerts, typically set to a small percentage like 5% to ensure stability in fluctuating traffic conditions.[10]
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.[10]
MRTG integrates seamlessly with cron 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 syslog support requires external scripting; environment variables passed via SetEnv facilitate integration with custom notification scripts. For advanced setups, SNMPv2c is enabled in target definitions (e.g., using :2: in the Target line) to perform bulk queries, reducing network 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.[10]
Despite its flexibility, MRTG has limitations in alerting and customization, lacking a built-in graphical user interface 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 email, and polling remains single-threaded, potentially constraining scalability in large deployments without additional wrappers. Email warnings for threshold breaches tie directly into graph generation processes, providing contextual links to affected visualizations.[10]
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.[13] 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.[13] Optionally, RRDTool can be integrated for enhanced data storage, requiring the RRDs Perl module.[3] A web server, such as Apache, is necessary to host and view the generated HTML pages and PNG images.[1]
On Debian-based systems such as Ubuntu, 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.[14]
For systems requiring compilation or custom installation, such as other Unix/Linux variants, begin by ensuring a C compiler like GCC is installed, then download the latest MRTG tarball from the official repository.[13] 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.[13] 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.[13]
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.[15] 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.[15] No MSI installer is provided officially; manual extraction suffices for setup.[15]
To verify the installation, run mrtg --version from the command line on Unix/Linux or perl mrtg on Windows, confirming the tool's presence and Perl integration.[13][15] 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.[1]
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.[13] On Unix/Linux, compilation failures often stem from undetected libraries, addressed by specifying paths in the configure script; on Windows, path-related errors arise if Perl is not in the system PATH, fixable through environment variable adjustments.[13][15] Ensure the user account has write permissions to directories for logs and graphs, such as /var/www/html/mrtg, to prevent runtime errors.[13] Initial runs may report missing log files, which is expected and resolves after the first two executions.[15]
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 configuration files can be included using the Include: directive.[10]
Essential global directives include WorkDir, which specifies the directory where log files and generated HTML 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 Target, which identifies the data sources to monitor; MaxBytes, which sets the maximum expected value for traffic counters to scale graphs appropriately; Title, which provides a descriptive label for the generated HTML page; and YLegend, which labels the Y-axis, typically as "Bits per Second" for network traffic.[10]
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.[10]
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
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 public community string on the host "router," with MaxBytes scaled to 12.5 MB/s to match the link speed.[10]
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 HTML index page aggregating graph links, using indexmaker mrtg.cfg --output index.html for a basic daily view table.[16][12]
For validation, execute mrtg mrtg.cfg in a dry-run mode, 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. Logging can be enabled via the command-line option --logging /var/log/mrtg.log to capture detailed output for troubleshooting during setup.[10]