textfsm-rust
A Rust implementation of Google's TextFSM template-based state machine for parsing semi-formatted text.
Overview
TextFSM is a template-based state machine originally developed by Google for parsing CLI output from network devices. This crate provides a native Rust implementation with the same template syntax and behavior.
Features
- Battle-tested compatibility - 98.5% pass rate against the ntc-templates test suite (1612/1637 tests)
- Compile-time template validation - Catch template errors at compile time with proc macros, not at runtime
- Serde integration - Deserialize parsed results directly into typed Rust structs
- Thread-safe design -
TemplateandCliTableareSend + Sync; share across threads with zero overhead - Detailed error messages - Template errors include line numbers, context, and suggestions
- Full TextFSM syntax - All value options (
Required,Filldown,Fillup,List,Key) and actions (Next,Continue,Record,Clear,Error) - Efficient regex handling - Uses fancy-regex which delegates to the fast regex crate when advanced features aren't needed
- Python regex compatibility - Handles Python regex quirks like
\<and\>automatically
Installation
Add to your Cargo.toml:
[]
= "0.3"
Quick Start
use Template;
let template = parse_str?;
let mut parser = template.parser;
let input = "Name: Alice, Age: 30\nName: Bob, Age: 25\n";
let results = parser.parse_text?;
Compile-Time Template Validation
Catch template errors before your program runs:
use ;
// Validate a single template at compile time
validate_template!;
// Validate all .textfsm files in a directory
validate_templates!;
// Parse at runtime when you need it
let template = parse_str.expect;
If a template is invalid, you get a compile error with the template line number:
error: Template validation failed for 'templates/bad.textfsm':
invalid variable substitution at line 8: unknown variable 'Interfce'
--> src/main.rs:4:21
|
4 | validate_template!("templates/bad.textfsm");
| ^^^^^^^^^^^^^^^^^^^^^^^^
Template Syntax
TextFSM templates consist of two sections:
Value Definitions
Value [Options] Name (Regex)
Options:
Required- Record only saved if this value is matchedFilldown- Value retained across recordsFillup- Value fills upward into previous recordsList- Value is a list of matchesKey- Marks value as a key field
State Rules
StateName
^Regex -> [Actions]
Actions:
Next- Continue to next line (default)Continue- Continue processing current lineRecord- Save current recordClear- Clear non-filldown valuesError- Stop processing with error
Serde Integration
Enable the serde feature to deserialize parsed results directly into typed Rust structs:
[]
= { = "0.3", = ["serde"] }
use ;
let template = parse_str?;
let mut parser = template.parser;
let input = "Interface: eth0 is up\n IP: 192.168.1.1\nInterface: eth1 is down\n IP: 10.0.0.1\n";
// Deserialize directly into typed structs
let interfaces: = parser.parse_text_into?;
assert_eq!;
assert_eq!;
assert_eq!;
Field names are matched case-insensitively against template value names (underscores are preserved).
Thread Safety
Template is Send + Sync and can be safely shared across threads. The compiled template (including all regexes) is immutable after creation, so you can wrap it in an Arc and share it freely.
Parser is a lightweight, stateful wrapper that borrows a Template. Create one per thread - they're cheap since they don't copy the compiled regexes.
use Arc;
use thread;
let template = new;
let handles: = inputs.into_iter.map.collect;
This design is efficient for concurrent workloads like parsing output from multiple network devices in parallel.
CliTable - Automatic Template Selection
CliTable automatically selects the right template based on command and platform attributes, using the same index format as ntc-templates:
use CliTable;
use HashMap;
// Load index and templates directory
let cli_table = new?;
// Parse CLI output with automatic template selection
let mut attrs = new;
attrs.insert;
attrs.insert;
let table = cli_table.parse_cmd?;
// Access results
for row in table.iter
With serde, deserialize directly into typed structs:
let versions: = cli_table.parse_cmd_into?;
Error Messages
Template errors include line numbers to help you fix issues quickly:
invalid variable substitution at line 8: unknown variable 'Interfce'
invalid Value definition at line 3: regex must be wrapped in parentheses
invalid rule at line 12: unclosed variable substitution
missing required 'Start' state
Known Limitations
Compatibility with Python TextFSM
This implementation achieves 98.5% compatibility with ntc-templates (1612/1637 tests passing for direct template parsing). The remaining differences are documented below.
Empty List Handling
When a Value List field is defined but never matches any input:
| Implementation | Output | Example |
|---|---|---|
| Python TextFSM | ["None"] |
List with literal string "None" |
| Rust TextFSM | [] |
Empty list |
This affects ~14 ntc-templates tests.
Workaround: Check for empty lists in your code rather than checking for ["None"].
Regex: Quantified Lookbehinds
The fancy-regex crate doesn't support quantifiers directly after lookbehinds:
# This pattern in cisco_ios_show_access-list.textfsm fails:
(?<=[^()\s])+
# Error: "Target of repeat operator is invalid"
This is a limitation of the regex engine, not our implementation. The pattern itself is arguably malformed (lookbehinds shouldn't be quantified). This affects 3 ntc-templates tests.
Test Results
Direct Template Parsing: 98.5% (1612/1637 tests)
Most failures are in edge cases for specific vendors (huawei_vrp, fortinet). Core functionality for Cisco IOS/NXOS/ASA, Arista EOS, and Juniper works reliably.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Acknowledgments
This project is a Rust port of Google's TextFSM, originally developed by Google Inc. and licensed under Apache 2.0.
Thanks to Network to Code for their extensive collection of TextFSM templates and test data, which made it possible to validate this implementation against real-world use cases.