Compare commits

...

27 Commits

Author SHA1 Message Date
Pim van Pelt
57fc8d3630 Release v1.3.2 2025-07-13 22:23:20 +02:00
Pim van Pelt
64212fce8c Twiddle ssh auth, use password before --key-file flag before homedir before agent 2025-07-13 22:21:27 +02:00
Pim van Pelt
83797aaa34 Release v1.3.1 2025-07-07 09:10:08 +02:00
Pim van Pelt
3da4de7711 Fix lint errors, ensure errors start with 'hostname:' 2025-07-07 09:06:20 +02:00
Pim van Pelt
9a2264e867 Remove old comments; Count auth mechanisms independently 2025-07-07 09:02:41 +02:00
Pim van Pelt
6c1993282c Release v1.3.0 2025-07-07 01:11:49 +02:00
Pim van Pelt
53c7bca43e Add parallelism 2025-07-07 01:08:42 +02:00
Pim van Pelt
c6775736ac Update docs with exclude patterns 2025-07-07 00:54:52 +02:00
Pim van Pelt
4260067ea8 Release v1.2.4 2025-07-07 00:52:43 +02:00
Pim van Pelt
90f5ec4e26 In preparation for parallelism, emit all log lines prefixed by hostname 2025-07-07 00:51:47 +02:00
Pim van Pelt
c8df809c29 Add types.exclude pattern 2025-07-07 00:39:56 +02:00
Pim van Pelt
88e30a40b1 Print description instead of status 2025-07-07 00:23:02 +02:00
Pim van Pelt
631a387708 Cut v1.2.3 2025-07-06 23:48:17 +02:00
Pim van Pelt
2bba484e6c Output terse 2025-07-06 23:46:59 +02:00
Pim van Pelt
db98af84b0 Release v1.2.2 2025-07-06 23:36:16 +02:00
Pim van Pelt
963cc3eed6 Add mikrotik 2025-07-06 23:33:59 +02:00
Pim van Pelt
9475d7b5c0 Allow glob of --host and --yaml; cut release 1.2.1 2025-07-06 23:31:41 +02:00
Pim van Pelt
fd74c41fb3 Add interface status 2025-07-06 23:05:40 +02:00
Pim van Pelt
7442a83c9d Cut v1.2.0 release 2025-07-06 22:44:35 +02:00
Pim van Pelt
7f6b030b31 Use a .new temp file while gathering info, only move it into place on success 2025-07-06 22:43:33 +02:00
Pim van Pelt
f05124b703 Add RC values, update docs, rename manpage 2025-07-06 22:27:51 +02:00
Pim van Pelt
f2c484e9c1 Rework and simplify the docs 2025-07-06 22:22:40 +02:00
Pim van Pelt
1afa1e6d43 Allow all three auth types 2025-07-06 22:16:01 +02:00
Pim van Pelt
96c7c3aeaa Update README 2025-07-06 18:23:45 +02:00
Pim van Pelt
8032a5a605 Cut release 1.1.1 2025-07-06 18:21:32 +02:00
Pim van Pelt
d212abcc87 Add an 'address' field to devices. Can be hostname, ipv4 or ipv6 2025-07-06 18:17:32 +02:00
Pim van Pelt
4a95221732 Reduce spurious logging 2025-07-06 18:03:30 +02:00
11 changed files with 726 additions and 521 deletions

View File

@@ -10,6 +10,19 @@ SSH-based network device configuration backup tool with support for multiple dev
- **SSH config integration**: Automatically uses `~/.ssh/config` settings for legacy device compatibility
- **Modular configuration**: Load and merge multiple YAML files for organized configuration management
## Supported Devices
Pre-configured device types with optimized command sets:
- **Nokia SR Linux** (`srlinux`) - Show version, linecard, fans, power, full config
- **Arista EOS** (`eos`) - Version, inventory, power status, running config
- **Centec Switches** (`centec`) - Version, boot images, transceivers, interfaces, config
- **Cisco IOS/IOS-XE** (`cisco-ios`) - Version, inventory, config, interfaces, CDP neighbors
- **Juniper JunOS** (`junos`) - Version, chassis hardware, configuration, interfaces
- **Mikrotik RouterOS** (`routeros`) - Packages, routerboard info, license, interfaces, config
Each device type includes carefully selected commands for comprehensive backup coverage. You can override commands per device or create custom device types.
## Quick Start
### Installation
@@ -26,7 +39,7 @@ make build
1. **Create configuration files**:
**Device types** (`etc/00-device-types.yaml`):
**Device types** (`00-device-types.yaml`):
```yaml
types:
srlinux:
@@ -37,10 +50,11 @@ make build
centec:
commands:
- show version
- show transciever
- show running-config
```
**Device config** (`etc/config.yaml`):
**Device config** (`config.yaml`):
```yaml
devices:
asw100:
@@ -55,13 +69,11 @@ make build
```bash
# Backup all devices (multiple YAML files are automatically merged)
ipng-router-backup --yaml etc/00-device-types.yaml --yaml etc/config.yaml --output-dir /backup
# Or use wildcards
ipng-router-backup --yaml etc/*.yaml --output-dir /backup
ipng-router-backup --yaml "00-*.yaml" --yaml config.yaml --output-dir /backup
# Backup specific devices
ipng-router-backup --yaml etc/*.yaml --host asw100 --output-dir /backup
ipng-router-backup --yaml 00-device-types.yaml --yaml config.yaml --output-dir /backup \
--host "asw*"
```
3. **Check output**:
@@ -104,5 +116,5 @@ This allows connecting to older routers that require legacy SSH algorithms while
## Documentation
- **[Detailed Documentation](docs/DETAILS.md)** - Complete feature guide, configuration reference, and examples
- **[Manual Page](docs/router_backup.1)** - Unix manual page
- **[Manual Page](docs/ipng-router-backup.1)** - Unix manual page
- **[Changelog](debian/changelog)** - Version history and changes

68
debian/changelog vendored
View File

@@ -1,3 +1,71 @@
ipng-router-backup (1.3.2) stable; urgency=low
* Fix --key-file authentication priority issue
* Prioritize explicit key file over SSH agent authentication
-- Pim van Pelt <pim@ipng.ch> Sun, 13 Jul 2025 23:30:00 +0100
ipng-router-backup (1.3.1) stable; urgency=low
* Fix golangci-lint issues, replace deprecated io/ioutil
* Add SSH key error messages with hostname prefix
* Independently validate sshkey, agent auth and password methods
-- Pim van Pelt <pim@ipng.ch> Sun, 07 Jul 2025 23:30:00 +0100
ipng-router-backup (1.3.0) stable; urgency=low
* Add --parallel flag for concurrent device processing (default: 10)
* Implement worker pool pattern for much faster multi-device backups
* Maintain atomic file operations and error handling in parallel mode
-- Pim van Pelt <pim@ipng.ch> Sun, 07 Jul 2025 23:00:00 +0100
ipng-router-backup (1.2.4) stable; urgency=low
* Add regex exclude patterns to filter unwanted output lines per device type
* Prefix all log messages with hostname for better multi-device visibility
* Add exclude pattern support for RouterOS timestamp headers
-- Pim van Pelt <pim@ipng.ch> Sun, 07 Jul 2025 22:00:00 +0100
ipng-router-backup (1.2.3) stable; urgency=low
* For routeros, set mikrotik export to terse
-- Pim van Pelt <pim@ipng.ch> Sun, 07 Jul 2025 21:30:00 +0100
ipng-router-backup (1.2.2) stable; urgency=low
* Add supported devices list to README.md
* Document all 6 pre-configured device types with command summaries
-- Pim van Pelt <pim@ipng.ch> Sun, 07 Jul 2025 21:15:00 +0100
ipng-router-backup (1.2.1) stable; urgency=low
* Add glob pattern support for --yaml flag (e.g., --yaml "*.yaml")
* Add glob pattern support for --host flag (e.g., --host "asw*")
* Update documentation with glob pattern examples
-- Pim van Pelt <pim@ipng.ch> Sun, 07 Jul 2025 21:00:00 +0100
ipng-router-backup (1.2.0) stable; urgency=low
* Add atomic file operations with .new suffix for backup reliability
* Add exit codes: 10 (some devices failed), 11 (all devices failed)
* Update manpage filename to ipng-router-backup.1
-- Pim van Pelt <pim@ipng.ch> Sun, 07 Jul 2025 20:00:00 +0100
ipng-router-backup (1.1.1) stable; urgency=low
* Add 'address' field to device configuration for explicit IP/hostname override
* Automatic IPv6 address detection and proper bracket formatting
* Fix output message to show once at end instead of per command
-- Pim van Pelt <pim@ipng.ch> Sun, 07 Jul 2025 18:00:00 +0100
ipng-router-backup (1.1.0) stable; urgency=low
* Replace --config flag with --yaml flag supporting multiple files

2
debian/rules vendored
View File

@@ -18,7 +18,7 @@ override_dh_auto_install:
mkdir -p debian/ipng-router-backup/usr/share/man/man1
cp ipng-router-backup debian/ipng-router-backup/usr/bin/
cp etc/* debian/ipng-router-backup/etc/ipng-router-backup/
cp docs/router_backup.1 debian/ipng-router-backup/usr/share/man/man1/ipng-router-backup.1
cp docs/ipng-router-backup.1 debian/ipng-router-backup/usr/share/man/man1/ipng-router-backup.1
gzip debian/ipng-router-backup/usr/share/man/man1/ipng-router-backup.1
override_dh_auto_clean:

View File

@@ -2,26 +2,48 @@
## Overview
IPng Networks Router Backup is a SSH-based network device configuration backup tool written in Go. It connects to multiple network devices defined in a YAML configuration file, executes commands via SSH, and saves the output to local files.
IPng Networks Router Backup is a SSH-based network device configuration backup tool written in Go. It connects to multiple network devices defined in YAML configuration files, executes commands via SSH, and saves the output to local files.
## Key Features
- **Multi-device support**: Backup multiple routers in a single run
- **Device type templates**: Define command sets per device type
- **Configuration merging**: Load and merge multiple YAML files automatically using mergo
- **SSH config integration**: Automatically uses `~/.ssh/config` for legacy device compatibility
- **Configuration merging**: Load and merge multiple YAML files using mergo
- **SSH config integration**: Uses `~/.ssh/config` for legacy device compatibility
- **Flexible authentication**: SSH agent, key files, or password authentication
- **Selective execution**: Target specific devices with `--host` flags
- **Automatic file organization**: Output files named by hostname
- **Command identification**: Each command output prefixed with command name
- **Version synchronization**: Automatic version sync between package and binary
- **IPv6 support**: Automatic IPv6 address detection and proper formatting
## Configuration File Format
The tool uses YAML configuration files with two main sections: `types` and `devices`. Multiple YAML files can be loaded simultaneously using the `--yaml` flag, and their contents are automatically merged using the mergo library. Later files override earlier ones, allowing for flexible configuration organization.
The tool uses YAML configuration files with two main sections: `types` and `devices`. Multiple YAML files can be loaded and merged automatically.
### Complete Example
**Device types** (`00-device-types.yaml`):
```yaml
types:
srlinux:
commands:
- show version
- show platform linecard
- info flat from running
eos:
commands:
- show version
- show inventory
- show running-config
routeros:
commands:
- system package print detail without-paging
- / export terse
exclude:
- "^# ....-..-.. ..:..:.. by RouterOS" # Filter timestamp headers
- "^# .../../.... ..:..:.. by RouterOS" # Alternative date format
```
**Main configuration** (`config.yaml`):
```yaml
devices:
@@ -29,203 +51,151 @@ devices:
user: admin
type: srlinux
asw120:
user: netops
type: srlinux
core-01:
user: admin
type: eos
address: 192.168.1.100 # Override connection address
ipv6-router:
user: netops
address: 2001:678:d78:500:: # IPv6 address support
edge-router:
user: operator
commands:
commands: # Direct commands (no type)
- show version
- show ip route summary
```
**Device types file** (`00-device-types.yaml`):
```yaml
types:
srlinux:
commands:
- show version
- show platform linecard
- show platform fan-tray
- show platform power-supply
- info flat from running
eos:
commands:
- show version
- show inventory
- show env power
- show running-config
centec:
commands:
- show version | exc uptime
- show boot images
- show transceiver
- show running-config
```
### Configuration Fields
#### Types Section
**`types`**: Define reusable command sets for different device types.
- **`<type-name>`**: Arbitrary name for the device type (e.g., `srlinux`, `eos`)
- **`commands`**: Array of CLI commands to execute on devices of this type
- **`<type-name>`**: Device type name (e.g., `srlinux`, `eos`)
- **`commands`**: Array of CLI commands to execute
- **`exclude`** (optional): Array of regex patterns to filter out unwanted lines from output
#### Devices Section
**`devices`**: Define individual network devices to backup.
- **`<hostname>`**: Device hostname or IP address
- **`user`** (required): SSH username for authentication
- **`type`** (optional): Reference to a type definition for commands
- **`<hostname>`**: Device hostname (used for SSH config lookup and output filename)
- **`user`** (required): SSH username
- **`type`** (optional): Reference to a type definition
- **`commands`** (optional): Direct command list (overrides type commands)
- **`address`** (optional): IP address or hostname to connect to (overrides hostname)
### Configuration Validation
### Configuration Merging
- Each device must have a `user` field
- Each device must have either a `type` field (referencing a valid type) or a `commands` field
- Type references must exist in the `types` section
- Commands can be specified either via type reference or directly per device
Files are merged automatically using mergo. Later files override earlier ones:
### Configuration Merging with Mergo
```bash
# Load multiple files - later files override earlier ones
ipng-router-backup --yaml 00-device-types.yaml --yaml config.yaml --yaml overrides.yaml
The tool automatically merges multiple YAML files using the mergo library. Files specified later in the `--yaml` flag override values from earlier files, enabling flexible configuration organization:
**Example file structure:**
```
/etc/ipng-router-backup/
├── etc/
│ ├── 00-device-types.yaml # Device type definitions (loaded first)
│ ├── 10-production.yaml # Production device definitions
│ ├── 20-staging.yaml # Staging device definitions
│ └── 99-overrides.yaml # Environment-specific overrides
└── config.yaml # Simple single-file config
# Load files using glob patterns
ipng-router-backup --yaml "*.yaml"
ipng-router-backup --yaml "config/*.yaml"
```
**Usage patterns:**
## Output Filtering
1. **Load multiple files with automatic merging:**
```bash
ipng-router-backup --yaml etc/00-device-types.yaml --yaml etc/10-production.yaml
```
The tool supports filtering unwanted lines from command output using regular expressions in the `exclude` field of device types.
2. **Use wildcards for directory-based loading:**
```bash
ipng-router-backup --yaml etc/*.yaml
```
### How Exclude Patterns Work
3. **Override configurations per environment:**
```bash
# Base config + production overrides
ipng-router-backup --yaml base.yaml --yaml production-overrides.yaml
# Base config + development overrides
ipng-router-backup --yaml base.yaml --yaml dev-overrides.yaml
```
- **Regex matching**: Each line of command output is tested against all exclude patterns
- **Line removal**: Lines matching any pattern are completely removed from the output file
- **Per-device type**: Exclude patterns are defined at the device type level and apply to all devices of that type
**Merging behavior:**
- **Maps are merged**: Device and type definitions from multiple files are combined
- **Arrays are replaced**: Later files completely replace arrays from earlier files
- **Values are overridden**: Later files override individual values from earlier files
- **Types are preserved**: Device types from any file can be referenced by devices in any other file
### Common Use Cases
## Command Line Flags
```yaml
types:
routeros:
commands:
- / export terse
exclude:
- "^# ....-..-.. ..:..:.. by RouterOS" # Remove timestamp headers
- "^# .../../.... ..:..:.. by RouterOS" # Alternative date format
cisco-ios:
commands:
- show running-config
exclude:
- "^Building configuration" # Remove config build messages
- "^Current configuration" # Remove current config headers
- "^!" # Remove comment lines
debug-device:
commands:
- show logs
exclude:
- "^DEBUG:" # Filter debug messages
- "^TRACE:" # Filter trace messages
```
## Command Line Usage
### Required Flags
- **`--yaml`**: Path to YAML configuration file(s)
- **`--yaml`**: Path to YAML configuration file(s) or glob patterns (can be repeated)
### Optional Flags
- **`--output-dir`**: Output directory (default: `/tmp`)
- **`--host`**: Specific hostname(s) or glob patterns to process (can be repeated)
- **`--password`**: SSH password
- **`--key-file`**: SSH private key file path
- **`--port`**: SSH port (default: `22`)
- **`--parallel`**: Maximum number of devices to process in parallel (default: `10`)
- **`--output-dir`**: Output directory for backup files (default: `/tmp`)
- **`--host`**: Specific hostname(s) to process (can be repeated)
- **`--password`**: SSH password for authentication
- **`--key-file`**: Path to SSH private key file
- **`--port`**: SSH port number (default: `22`)
- **`--help`**: Show help information
- **`--version`**: Show version information
### Flag Examples
### Examples
```bash
# Basic usage - all devices
ipng-router-backup --yaml /etc/ipng-router-backup/*.yaml
# Basic usage with glob patterns
ipng-router-backup --yaml "*.yaml"
# Multiple files
ipng-router-backup --yaml 00-device-types.yaml --yaml config.yaml
# Devices matching patterns
ipng-router-backup --yaml config.yaml --host "asw*" --host "*switch*"
# Custom output directory
ipng-router-backup --yaml *.yaml --output-dir /backup/network
ipng-router-backup --yaml config.yaml --output-dir /backup/network
# Specific devices only
ipng-router-backup --yaml *.yaml --host asw100 --host core-01
# With password authentication
ipng-router-backup --yaml config.yaml --password mypassword
# Multiple specific devices
ipng-router-backup --yaml *.yaml --host asw100 --host asw120 --host core-01
# Custom SSH port
ipng-router-backup --yaml *.yaml --port 2222
# Using password authentication
ipng-router-backup --yaml *.yaml --password mypassword
# Using specific SSH key
ipng-router-backup --yaml *.yaml --key-file ~/.ssh/network_key
# Process more devices in parallel
ipng-router-backup --yaml config.yaml --parallel 20
```
## SSH Authentication Methods
## SSH Authentication
The tool supports multiple SSH authentication methods in the following priority order:
### 1. SSH Agent (Highest Priority)
Automatically used when the `SSH_AUTH_SOCK` environment variable is set.
The tool supports multiple authentication methods in priority order:
### 1. SSH Agent (Recommended)
Automatically used when `SSH_AUTH_SOCK` is set:
```bash
# Start SSH agent and add keys
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa
# Run backup (will use SSH agent automatically)
ipng-router-backup --yaml *.yaml
ipng-router-backup --yaml config.yaml
```
**Advantages:**
- Most secure (keys remain in memory)
- No password prompts
- Works with hardware security modules
- Single sign-on experience
### 2. SSH Key File
Specify a private key file with `--key-file`, use SSH config, or default locations.
```bash
# Explicit key file
ipng-router-backup --yaml *.yaml --key-file ~/.ssh/network_key
ipng-router-backup --yaml config.yaml --key-file ~/.ssh/network_key
# SSH config integration (IdentityFile from ~/.ssh/config)
ipng-router-backup --yaml *.yaml
# Tool automatically checks these default locations:
# ~/.ssh/id_rsa
# ~/.ssh/id_ed25519
# ~/.ssh/id_ecdsa
# Automatic detection from default locations:
# ~/.ssh/id_rsa, ~/.ssh/id_ed25519, ~/.ssh/id_ecdsa
ipng-router-backup --yaml config.yaml
```
**Key File Requirements:**
- Must be in OpenSSH format
- Proper permissions (600 recommended)
- Corresponding public key must be on target devices
### 3. Password Authentication
```bash
ipng-router-backup --yaml config.yaml --password mypassword
```
### SSH Configuration Integration
## SSH Configuration Integration
The tool automatically reads `~/.ssh/config` for each host, supporting:
The tool automatically reads `~/.ssh/config` for each host:
```bash
# ~/.ssh/config
@@ -234,273 +204,45 @@ Host old-switch*
Port 2222
IdentityFile ~/.ssh/legacy_key
KexAlgorithms +diffie-hellman-group1-sha1
Ciphers aes128-cbc,aes192-cbc,aes256-cbc
HostKeyAlgorithms +ssh-rsa
Host modern-router*
User netops
Port 22
IdentityFile ~/.ssh/modern_key
```
**Supported SSH config options:**
- `Hostname`: Target hostname override
- `Port`: SSH port override
- `User`: Username override (command line takes precedence)
- `IdentityFile`: SSH key file path
- `KexAlgorithms`: Key exchange algorithms (explicit lists only, + syntax ignored for compatibility)
- `Ciphers`: Encryption ciphers (filtered for Go SSH library compatibility)
- `MACs`: Message authentication codes
- `HostKeyAlgorithms`: Host key algorithms (explicit lists only, + syntax ignored for compatibility)
**Legacy device compatibility:**
The tool is designed to work with older network devices that require legacy SSH algorithms while maintaining security for modern devices.
### 3. Password Authentication (Lowest Priority)
Use `--password` flag for password-based authentication.
```bash
# Command line password (not recommended for scripts)
ipng-router-backup --yaml *.yaml --password mypassword
# Interactive password prompt (when no other auth available)
ipng-router-backup --yaml *.yaml
# Output: "No SSH key found. Enter SSH password: "
```
**Security Considerations:**
- Passwords visible in process lists
- Not suitable for automation
- Consider using key-based authentication instead
**Supported options:** Hostname, Port, User, IdentityFile, KexAlgorithms, MACs, HostKeyAlgorithms
## Output Format
### File Naming
Output files are named after the device hostname:
- Output files are named after the device hostname
- Device `asw100` → File `asw100`
- Device `192.168.1.1` → File `192.168.1.1`
### File Content Structure
Each output file contains all command outputs with headers:
### File Content
Each file contains all command outputs with headers:
```
## COMMAND: show version
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Hostname : asw100
Chassis Type : 7220 IXR-D4
Software Version : v25.3.2
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------
## COMMAND: show platform linecard
+-------------+----+-------------+-------------------+---------------------------------+
| Module Type | ID | Admin State | Operational State | Model |
+=============+====+=============+===================+=================================+
| linecard | 1 | N/A | up | imm28-100g-qsfp28+8-400g-qsfpdd |
+-------------+----+-------------+-------------------+---------------------------------+
```
### File Behavior
- **New runs**: Files are truncated and recreated
- **Multiple commands**: All outputs concatenated in single file
- **Command identification**: Each command prefixed with `## COMMAND: <command>`
## Usage Examples
### Basic Backup All Devices
```bash
ipng-router-backup --yaml /etc/backup/*.yaml --output-dir /backup/$(date +%Y%m%d)
```
### Backup Specific Device Types
Create a config with only the devices you want, or use `--host`:
```bash
# Backup only SR Linux devices
ipng-router-backup --yaml network.yaml --host asw100 --host asw120 --host asw121
```
### Scheduled Backup with SSH Agent
```bash
#!/bin/bash
# /etc/cron.daily/network-backup
# Start SSH agent
eval "$(ssh-agent -s)"
ssh-add /root/.ssh/network_backup_key
# Run backup
BACKUP_DIR="/backup/network/$(date +%Y%m%d)"
mkdir -p "$BACKUP_DIR"
ipng-router-backup \
--yaml /etc/ipng-router-backup/*.yaml \
--output-dir "$BACKUP_DIR"
# Kill SSH agent
ssh-agent -k
```
### Emergency Single Device Backup
```bash
# Quick backup of single device with password
ipng-router-backup \
--yaml emergency.yaml \
--host core-router-01 \
--password emergency123 \
--output-dir /tmp/emergency-backup
+-------------+----+-------------+-------------------+
| Module Type | ID | Admin State | Operational State |
+=============+====+=============+===================+
| linecard | 1 | N/A | up |
+-------------+----+-------------+-------------------+
```
## Error Handling
### Common Issues and Solutions
**Device Connection Failures:**
- Check SSH connectivity: `ssh user@hostname`
- Verify authentication method
- Check firewall rules and network connectivity
**Configuration Errors:**
- Validate YAML syntax: `yamllint config.yaml`
- Check that all referenced types exist
- Ensure all devices have required fields
**Permission Issues:**
- Verify SSH key permissions (600)
- Check output directory write permissions
- Ensure user has SSH access to target devices
### Common Issues
- **Connection failures**: Check SSH connectivity and authentication
- **Configuration errors**: Validate YAML syntax and required fields
- **Permission issues**: Verify SSH key permissions (600) and output directory access
### Exit Codes
- `0`: Success
- `0`: Success (all devices processed successfully)
- `1`: Configuration error, authentication failure, or connection issues
## Advanced Usage
### Configuration Organization with Mergo
For large deployments, organize configurations using multiple YAML files with automatic merging:
**Environment-based structure:**
```bash
network-backup/
├── etc/
│ ├── 00-device-types.yaml # All device types (loaded first)
│ ├── 10-common.yaml # Common settings
│ ├── 20-production.yaml # Production devices
│ ├── 30-staging.yaml # Staging devices
│ ├── 40-lab.yaml # Lab devices
│ ├── 50-east-datacenter.yaml # East datacenter devices
│ └── 60-west-datacenter.yaml # West datacenter devices
└── overrides/
├── emergency.yaml # Emergency override settings
└── maintenance.yaml # Maintenance mode settings
```
**Device types** (`etc/00-device-types.yaml`):
```yaml
types:
srlinux:
commands:
- show version
- show platform linecard
- info flat from running
eos:
commands:
- show version
- show inventory
- show running-config
```
**Production devices** (`etc/20-production.yaml`):
```yaml
devices:
prod-asw100:
user: netops
type: srlinux
prod-asw120:
user: netops
type: srlinux
prod-core-01:
user: netops
type: eos
```
**Usage examples:**
```bash
# Load all standard configs
ipng-router-backup --yaml etc/*.yaml
# Load with environment-specific overrides
ipng-router-backup --yaml etc/*.yaml --yaml overrides/emergency.yaml
# Load only specific environments
ipng-router-backup --yaml etc/00-device-types.yaml --yaml etc/20-production.yaml
```
### Integration with Git
```bash
#!/bin/bash
# Backup and commit to git repository
BACKUP_DIR="/backup/network-configs"
cd "$BACKUP_DIR"
# Run backup
ipng-router-backup --yaml config.yaml --output-dir .
# Commit changes
git add .
git commit -m "Network backup $(date '+%Y-%m-%d %H:%M:%S')"
git push origin main
```
### Custom Command Sets per Environment
```yaml
types:
production-srlinux:
commands:
- show version
- show system information
- info flat from running
lab-srlinux:
commands:
- show version
- show interface brief
devices:
prod-asw100:
user: readonly
type: production-srlinux
lab-asw100:
user: admin
type: lab-srlinux
```
### Monitoring and Alerting
```bash
#!/bin/bash
# Backup with monitoring
if ipng-router-backup --yaml config.yaml --output-dir /backup; then
echo "Backup completed successfully" | logger
else
echo "Backup failed!" | logger
# Send alert email
echo "Network backup failed at $(date)" | mail -s "Backup Alert" admin@company.com
fi
```
- `10`: Some devices failed
- `11`: All devices failed

View File

@@ -18,7 +18,7 @@ The tool supports multiple device types with predefined command sets, SSH agent
.SH OPTIONS
.TP
.BR --yaml " \fICONFIG_FILE\fR"
YAML configuration file(s) (required)
YAML configuration file(s) or glob patterns (required)
.TP
.BR --output-dir " \fIDIRECTORY\fR"
Output directory for command output files (default: /tmp)
@@ -33,7 +33,10 @@ SSH private key file path
SSH port number (default: 22)
.TP
.BR --host " \fIHOSTNAME\fR"
Specific host(s) to process (can be repeated, processes all if not specified)
Specific host(s) or glob patterns to process (can be repeated, processes all if not specified)
.TP
.BR --parallel " \fINUMBER\fR"
Maximum number of devices to process in parallel (default: 10)
.TP
.BR --help
Show help message
@@ -48,6 +51,11 @@ types:
commands:
- show version
- show platform linecard
routeros:
commands:
- / export terse
exclude:
- "^# ....-..-.. ..:..:.. by RouterOS"
.EE
.SS devices
Define individual devices:
@@ -70,11 +78,13 @@ Default SSH keys (~/.ssh/id_rsa, ~/.ssh/id_ed25519, ~/.ssh/id_ecdsa)
Password authentication (--password option)
.SH OUTPUT
For each device, a text file named after the hostname is created in the specified directory. Each command output is prefixed with "## COMMAND: <command_name>" for easy identification.
.PP
Output can be filtered using regex patterns defined in the device type's 'exclude' field to remove unwanted lines such as timestamps or debug messages.
.SH EXAMPLES
.TP
Basic usage:
Basic usage with glob patterns:
.EX
ipng-router-backup --yaml /etc/ipng-router-backup/*.yaml
ipng-router-backup --yaml "*.yaml"
.EE
.TP
Custom output directory:
@@ -87,9 +97,14 @@ Using password authentication:
ipng-router-backup --yaml config.yaml --password mysecretpass
.EE
.TP
Process specific hosts only:
Process hosts matching patterns:
.EX
ipng-router-backup --yaml config.yaml --host asw100 --host asw120
ipng-router-backup --yaml config.yaml --host "asw*" --host "*switch*"
.EE
.TP
Process devices in parallel:
.EX
ipng-router-backup --yaml config.yaml --parallel 20
.EE
.SH FILES
.TP
@@ -98,10 +113,16 @@ Example configuration file
.SH EXIT STATUS
.TP
.B 0
Success
Success (all devices processed successfully)
.TP
.B 1
General error (configuration file not found, authentication failure, etc.)
.TP
.B 10
Some devices failed
.TP
.B 11
All devices failed
.SH AUTHOR
Written by Pim van Pelt.
.SH REPORTING BUGS

View File

@@ -28,6 +28,7 @@ types:
- show version | exc uptime # Version info without uptime line
- show boot images # Boot image information
- show transceiver # SFP/transceiver status
- show interface description # Interface status
- show running-config # Running configuration
# Cisco IOS/IOS-XE devices
@@ -46,3 +47,15 @@ types:
- show chassis hardware # Chassis hardware details
- show configuration | display set # Configuration in set format
- show interfaces terse # Interface status summary
# Mikrotik routeros devices
routeros:
commands:
- system package print detail without-paging # Installed Packaged
- system routerboard print # System information
- system license print # License information
- / interface print # Interfaces
- / export terse # Configuration
exclude:
- "^# ....-..-.. ..:..:.. by RouterOS"
- "^# .../../.... ..:..:.. by RouterOS"

View File

@@ -4,7 +4,7 @@ package main
import (
"fmt"
"io/ioutil"
"os"
"dario.cat/mergo"
"gopkg.in/yaml.v3"
@@ -18,16 +18,18 @@ type Config struct {
type DeviceType struct {
Commands []string `yaml:"commands"`
Exclude []string `yaml:"exclude,omitempty"`
}
type Device struct {
User string `yaml:"user"`
Type string `yaml:"type,omitempty"`
Commands []string `yaml:"commands,omitempty"`
Address string `yaml:"address,omitempty"`
}
func readYAMLFile(path string) (map[string]interface{}, error) {
data, err := ioutil.ReadFile(path)
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}

View File

@@ -319,3 +319,44 @@ func TestConfigReadComplexMerge(t *testing.T) {
t.Errorf("Expected 1 custom command for lab-switch, got %d", len(labDevice.Commands))
}
}
func TestConfigReadAddress(t *testing.T) {
tempDir := t.TempDir()
// Create config file with address field
configPath := filepath.Join(tempDir, "address-config.yaml")
configContent := `devices:
router-with-address:
user: testuser
address: 192.168.1.100
router-without-address:
user: testuser`
err := os.WriteFile(configPath, []byte(configContent), 0644)
if err != nil {
t.Fatalf("Failed to create test config file: %v", err)
}
cfg, err := ConfigRead([]string{configPath})
if err != nil {
t.Fatalf("Failed to load config: %v", err)
}
// Test device with address
deviceWithAddress, exists := cfg.Devices["router-with-address"]
if !exists {
t.Error("Expected 'router-with-address' to exist")
}
if deviceWithAddress.Address != "192.168.1.100" {
t.Errorf("Expected address '192.168.1.100', got '%s'", deviceWithAddress.Address)
}
// Test device without address (should be empty)
deviceWithoutAddress, exists := cfg.Devices["router-without-address"]
if !exists {
t.Error("Expected 'router-without-address' to exist")
}
if deviceWithoutAddress.Address != "" {
t.Errorf("Expected empty address, got '%s'", deviceWithoutAddress.Address)
}
}

View File

@@ -6,19 +6,35 @@ import (
"fmt"
"log"
"os"
"path/filepath"
"sync"
"github.com/spf13/cobra"
)
const Version = "1.1.0"
const Version = "1.3.2"
// Config and SSH types are now in separate packages
func processDevice(hostname string, deviceConfig Device, commands []string, excludePatterns []string, password, keyFile string, port int, outputDir string) bool {
// Create backup instance
backup := NewRouterBackup(hostname, deviceConfig.Address, deviceConfig.User, password, keyFile, port)
// SSH connection methods are now in ssh.go
// Connect and backup
if err := backup.Connect(); err != nil {
fmt.Printf("%s: Failed to connect: %v\n", hostname, err)
return false
}
// YAML processing is now handled by the config package
err := backup.BackupCommands(commands, excludePatterns, outputDir)
backup.Disconnect()
// SSH helper functions are now in ssh.go
if err != nil {
fmt.Printf("%s: Backup failed: %v\n", hostname, err)
return false
} else {
fmt.Printf("%s: Backup completed\n", hostname)
return true
}
}
func main() {
var yamlFiles []string
@@ -27,6 +43,7 @@ func main() {
var port int
var outputDir string
var hostFilter []string
var parallel int
var rootCmd = &cobra.Command{
Use: "ipng-router-backup",
@@ -36,22 +53,47 @@ func main() {
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("IPng Networks Router Backup v%s\n", Version)
// Expand glob patterns in YAML files
var expandedYamlFiles []string
for _, pattern := range yamlFiles {
matches, err := filepath.Glob(pattern)
if err != nil {
log.Fatalf("Invalid glob pattern '%s': %v", pattern, err)
}
if len(matches) == 0 {
log.Fatalf("No files matched pattern '%s'", pattern)
}
expandedYamlFiles = append(expandedYamlFiles, matches...)
}
// Load configuration
cfg, err := ConfigRead(yamlFiles)
cfg, err := ConfigRead(expandedYamlFiles)
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
// Check authentication setup
if password == "" && keyFile == "" {
if os.Getenv("SSH_AUTH_SOCK") != "" {
fmt.Println("Using SSH agent for authentication")
} else {
keyFile = findDefaultSSHKey()
if keyFile == "" {
log.Fatal("No SSH key found and no password provided")
}
hasAuth := 0
if os.Getenv("SSH_AUTH_SOCK") != "" {
fmt.Println("Using SSH agent for authentication")
hasAuth++
}
if keyFile == "" {
keyFile = findDefaultSSHKey()
if keyFile != "" {
fmt.Printf("Using SSH key: %s\n", keyFile)
hasAuth++
}
} else {
fmt.Printf("Using specified SSH key: %s\n", keyFile)
hasAuth++
}
if password != "" {
fmt.Println("Using --password for authentication")
hasAuth++
}
if hasAuth == 0 {
log.Fatal("No authentication mechanisms found.")
}
// Process devices
@@ -63,63 +105,110 @@ func main() {
devicesToProcess := cfg.Devices
if len(hostFilter) > 0 {
devicesToProcess = make(map[string]Device)
for _, hostname := range hostFilter {
if deviceConfig, exists := cfg.Devices[hostname]; exists {
devicesToProcess[hostname] = deviceConfig
} else {
fmt.Printf("Warning: Host '%s' not found in config file\n", hostname)
for _, pattern := range hostFilter {
patternMatched := false
for hostname, deviceConfig := range cfg.Devices {
if matched, _ := filepath.Match(pattern, hostname); matched {
devicesToProcess[hostname] = deviceConfig
patternMatched = true
}
}
if !patternMatched {
fmt.Printf("Warning: Host pattern '%s' did not match any devices\n", pattern)
}
}
}
successCount := 0
totalCount := len(devicesToProcess)
for hostname, deviceConfig := range devicesToProcess {
fmt.Printf("\nProcessing device: %s (type: %s)\n", hostname, deviceConfig.Type)
// Create channels for work distribution and result collection
type DeviceWork struct {
hostname string
deviceConfig Device
commands []string
excludePatterns []string
}
type DeviceResult struct {
hostname string
success bool
}
workChan := make(chan DeviceWork, totalCount)
resultChan := make(chan DeviceResult, totalCount)
// Start worker pool
var wg sync.WaitGroup
for i := 0; i < parallel; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for work := range workChan {
fmt.Printf("%s: Processing device (type: %s)\n", work.hostname, work.deviceConfig.Type)
success := processDevice(work.hostname, work.deviceConfig, work.commands, work.excludePatterns, password, keyFile, port, outputDir)
resultChan <- DeviceResult{hostname: work.hostname, success: success}
}
}()
}
// Queue all work
for hostname, deviceConfig := range devicesToProcess {
user := deviceConfig.User
commands := deviceConfig.Commands
deviceType := deviceConfig.Type
var excludePatterns []string
// If device has a type, get commands from types section
// If device has a type, get commands and exclude patterns from types section
if deviceType != "" {
if typeConfig, exists := cfg.Types[deviceType]; exists {
commands = typeConfig.Commands
excludePatterns = typeConfig.Exclude
}
}
if user == "" {
fmt.Printf("No user specified for %s, skipping\n", hostname)
fmt.Printf("%s: No user specified, skipping\n", hostname)
continue
}
if len(commands) == 0 {
fmt.Printf("No commands specified for %s, skipping\n", hostname)
fmt.Printf("%s: No commands specified, skipping\n", hostname)
continue
}
// Create backup instance
backup := NewRouterBackup(hostname, user, password, keyFile, port)
// Connect and backup
if err := backup.Connect(); err != nil {
fmt.Printf("Failed to connect to %s: %v\n", hostname, err)
continue
workChan <- DeviceWork{
hostname: hostname,
deviceConfig: deviceConfig,
commands: commands,
excludePatterns: excludePatterns,
}
}
close(workChan)
err = backup.BackupCommands(commands, outputDir)
backup.Disconnect()
// Wait for all workers to finish
go func() {
wg.Wait()
close(resultChan)
}()
if err != nil {
fmt.Printf("Backup failed for %s: %v\n", hostname, err)
} else {
fmt.Printf("Backup completed for %s\n", hostname)
// Collect results
successCount := 0
for result := range resultChan {
if result.success {
successCount++
}
}
fmt.Printf("\nOverall summary: %d/%d devices processed successfully\n", successCount, totalCount)
fmt.Printf("Overall summary: %d/%d devices processed successfully\n", successCount, totalCount)
// Set exit code based on results
if successCount == 0 {
os.Exit(11) // All devices failed
} else if successCount < totalCount {
os.Exit(10) // Some devices failed
}
// Exit code 0 (success) when all devices succeeded
},
}
@@ -129,8 +218,11 @@ func main() {
rootCmd.Flags().IntVar(&port, "port", 22, "SSH port")
rootCmd.Flags().StringVar(&outputDir, "output-dir", "/tmp", "Output directory for command output files")
rootCmd.Flags().StringSliceVar(&hostFilter, "host", []string{}, "Specific host(s) to process (can be repeated, processes all if not specified)")
rootCmd.Flags().IntVar(&parallel, "parallel", 10, "Maximum number of devices to process in parallel")
rootCmd.MarkFlagRequired("yaml")
if err := rootCmd.MarkFlagRequired("yaml"); err != nil {
log.Fatal(err)
}
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)

View File

@@ -4,10 +4,10 @@ package main
import (
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
@@ -20,6 +20,7 @@ import (
// RouterBackup handles SSH connections and command execution
type RouterBackup struct {
hostname string
address string
username string
password string
keyFile string
@@ -28,9 +29,10 @@ type RouterBackup struct {
}
// NewRouterBackup creates a new RouterBackup instance
func NewRouterBackup(hostname, username, password, keyFile string, port int) *RouterBackup {
func NewRouterBackup(hostname, address, username, password, keyFile string, port int) *RouterBackup {
return &RouterBackup{
hostname: hostname,
address: address,
username: username,
password: password,
keyFile: keyFile,
@@ -38,12 +40,32 @@ func NewRouterBackup(hostname, username, password, keyFile string, port int) *Ro
}
}
// isIPv6 checks if the given address is an IPv6 address
func isIPv6(address string) bool {
ip := net.ParseIP(address)
return ip != nil && ip.To4() == nil
}
// getNetworkType determines the appropriate network type based on the target address
func getNetworkType(address string) string {
if isIPv6(address) {
return "tcp6"
}
return "tcp4"
}
// Connect establishes SSH connection to the router
func (rb *RouterBackup) Connect() error {
// Get SSH config values for this host
hostname := ssh_config.Get(rb.hostname, "Hostname")
if hostname == "" {
hostname = rb.hostname
// Determine the target address - use explicit address if provided, otherwise use hostname
var targetHost string
if rb.address != "" {
targetHost = rb.address
} else {
// Get SSH config values for this host
targetHost = ssh_config.Get(rb.hostname, "Hostname")
if targetHost == "" {
targetHost = rb.hostname
}
}
portStr := ssh_config.Get(rb.hostname, "Port")
@@ -81,11 +103,6 @@ func (rb *RouterBackup) Connect() error {
config.KeyExchanges = finalAlgorithms
}
// Note: Cipher overrides disabled - Go SSH library defaults work better
// if ciphers := ssh_config.Get(rb.hostname, "Ciphers"); ciphers != "" {
// config.Ciphers = ...
// }
if macs := ssh_config.Get(rb.hostname, "MACs"); macs != "" {
macList := strings.Split(macs, ",")
for i, mac := range macList {
@@ -104,16 +121,20 @@ func (rb *RouterBackup) Connect() error {
config.HostKeyAlgorithms = finalAlgorithms
}
// Try SSH agent first if available
// If explicit key file is provided, prioritize it over SSH agent
var keyFileAuth ssh.AuthMethod
var agentAuth ssh.AuthMethod
// Try SSH agent if available (but don't add to config.Auth yet)
if sshAuthSock := os.Getenv("SSH_AUTH_SOCK"); sshAuthSock != "" {
if conn, err := net.Dial("unix", sshAuthSock); err == nil {
agentClient := agent.NewClient(conn)
config.Auth = []ssh.AuthMethod{ssh.PublicKeysCallback(agentClient.Signers)}
agentAuth = ssh.PublicKeysCallback(agentClient.Signers)
}
}
// If SSH agent didn't work, try key file
if len(config.Auth) == 0 && keyFile != "" {
// Try key file
if keyFile != "" {
// Expand ~ in keyFile path
if strings.HasPrefix(keyFile, "~/") {
homeDir, err := os.UserHomeDir()
@@ -122,36 +143,51 @@ func (rb *RouterBackup) Connect() error {
}
}
key, err := ioutil.ReadFile(keyFile)
if err != nil {
return fmt.Errorf("unable to read private key: %v", err)
key, err := os.ReadFile(keyFile)
if err == nil {
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
fmt.Printf("%s: Unable to parse private key: %v\n", rb.hostname, err)
} else {
keyFileAuth = ssh.PublicKeys(signer)
}
}
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return fmt.Errorf("unable to parse private key: %v", err)
// Prioritize auth methods: explicit key file first, then SSH agent
if keyFileAuth != nil {
config.Auth = []ssh.AuthMethod{keyFileAuth}
if agentAuth != nil {
config.Auth = append(config.Auth, agentAuth)
}
config.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)}
} else if agentAuth != nil {
config.Auth = []ssh.AuthMethod{agentAuth}
}
// Fall back to password if available
if len(config.Auth) == 0 && rb.password != "" {
config.Auth = []ssh.AuthMethod{ssh.Password(rb.password)}
if rb.password != "" {
config.Auth = append(config.Auth, ssh.Password(rb.password))
}
if len(config.Auth) == 0 {
return fmt.Errorf("no authentication method available")
}
address := fmt.Sprintf("%s:%d", hostname, port)
client, err := ssh.Dial("tcp4", address, config)
// Format address properly for IPv6
var address string
if isIPv6(targetHost) {
address = fmt.Sprintf("[%s]:%d", targetHost, port)
} else {
address = fmt.Sprintf("%s:%d", targetHost, port)
}
networkType := getNetworkType(targetHost)
client, err := ssh.Dial(networkType, address, config)
if err != nil {
return fmt.Errorf("failed to connect to %s: %v", hostname, err)
return fmt.Errorf("failed to connect to %s: %v", targetHost, err)
}
rb.client = client
fmt.Printf("Successfully connected to %s\n", hostname)
fmt.Printf("%s: Successfully connected to %s\n", rb.hostname, targetHost)
return nil
}
@@ -175,48 +211,96 @@ func (rb *RouterBackup) RunCommand(command string) (string, error) {
return string(output), nil
}
// filterOutput removes lines matching exclude patterns from the output
func filterOutput(output string, excludePatterns []string) string {
if len(excludePatterns) == 0 {
return output
}
lines := strings.Split(output, "\n")
var filteredLines []string
for _, line := range lines {
exclude := false
for _, pattern := range excludePatterns {
if matched, _ := regexp.MatchString(pattern, line); matched {
exclude = true
break
}
}
if !exclude {
filteredLines = append(filteredLines, line)
}
}
return strings.Join(filteredLines, "\n")
}
// BackupCommands runs multiple commands and saves outputs to files
func (rb *RouterBackup) BackupCommands(commands []string, outputDir string) error {
func (rb *RouterBackup) BackupCommands(commands []string, excludePatterns []string, outputDir string) error {
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("failed to create directory %s: %v", outputDir, err)
}
filename := rb.hostname
filepath := filepath.Join(outputDir, filename)
finalPath := filepath.Join(outputDir, filename)
tempPath := finalPath + ".new"
// Truncate file at start
file, err := os.Create(filepath)
// Create temporary file
file, err := os.Create(tempPath)
if err != nil {
return fmt.Errorf("failed to create file %s: %v", filepath, err)
return fmt.Errorf("failed to create temporary file %s: %v", tempPath, err)
}
file.Close()
successCount := 0
hasErrors := false
for i, command := range commands {
fmt.Printf("Running command %d/%d: %s\n", i+1, len(commands), command)
fmt.Printf("%s: Running command %d/%d: %s\n", rb.hostname, i+1, len(commands), command)
output, err := rb.RunCommand(command)
if err != nil {
fmt.Printf("Error executing '%s': %v\n", command, err)
fmt.Printf("%s: Error executing '%s': %v\n", rb.hostname, command, err)
hasErrors = true
continue
}
// Append to file
file, err := os.OpenFile(filepath, os.O_APPEND|os.O_WRONLY, 0644)
// Append to temporary file
file, err := os.OpenFile(tempPath, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
fmt.Printf("Failed to open file for writing: %v\n", err)
fmt.Printf("%s: Failed to open file for writing: %v\n", rb.hostname, err)
hasErrors = true
continue
}
fmt.Fprintf(file, "## COMMAND: %s\n", command)
file.WriteString(output)
filteredOutput := filterOutput(output, excludePatterns)
if _, err := file.WriteString(filteredOutput); err != nil {
fmt.Printf("%s: Failed to write output: %v\n", rb.hostname, err)
hasErrors = true
}
file.Close()
fmt.Printf("Output saved to %s\n", filepath)
successCount++
}
fmt.Printf("Summary: %d/%d commands successful\n", successCount, len(commands))
fmt.Printf("%s: Summary: %d/%d commands successful\n", rb.hostname, successCount, len(commands))
if hasErrors || successCount == 0 {
// Remove .new suffix and log error
if err := os.Remove(tempPath); err != nil {
fmt.Printf("%s: Failed to remove temporary file %s: %v\n", rb.hostname, tempPath, err)
}
return fmt.Errorf("device backup incomplete due to command failures")
}
// All commands succeeded, move file into place atomically
if err := os.Rename(tempPath, finalPath); err != nil {
return fmt.Errorf("failed to move temporary file to final location: %v", err)
}
fmt.Printf("%s: Output saved to %s\n", rb.hostname, finalPath)
return nil
}
@@ -224,7 +308,7 @@ func (rb *RouterBackup) BackupCommands(commands []string, outputDir string) erro
func (rb *RouterBackup) Disconnect() {
if rb.client != nil {
rb.client.Close()
fmt.Printf("Disconnected from %s\n", rb.hostname)
fmt.Printf("%s: Disconnected\n", rb.hostname)
}
}
@@ -243,7 +327,7 @@ func findDefaultSSHKey() string {
for _, keyPath := range defaultKeys {
if _, err := os.Stat(keyPath); err == nil {
fmt.Printf("Using SSH key: %s\n", keyPath)
// Key discovery logging moved to main.go for hostname context
return keyPath
}
}

View File

@@ -9,7 +9,7 @@ import (
)
func TestNewRouterBackup(t *testing.T) {
rb := NewRouterBackup("testhost", "testuser", "testpass", "/path/to/key", 2222)
rb := NewRouterBackup("testhost", "", "testuser", "testpass", "/path/to/key", 2222)
if rb.hostname != "testhost" {
t.Errorf("Expected hostname 'testhost', got '%s'", rb.hostname)
@@ -37,7 +37,7 @@ func TestNewRouterBackup(t *testing.T) {
}
func TestRunCommandWithoutConnection(t *testing.T) {
rb := NewRouterBackup("testhost", "testuser", "testpass", "", 22)
rb := NewRouterBackup("testhost", "", "testuser", "testpass", "", 22)
_, err := rb.RunCommand("show version")
if err == nil {
@@ -53,43 +53,48 @@ func TestBackupCommandsDirectoryCreation(t *testing.T) {
tempDir := t.TempDir()
outputDir := filepath.Join(tempDir, "nonexistent", "backup")
rb := NewRouterBackup("testhost", "testuser", "testpass", "", 22)
rb := NewRouterBackup("testhost", "", "testuser", "testpass", "", 22)
// This should create the directory even without a connection
// and fail gracefully when trying to run commands
_ = rb.BackupCommands([]string{"show version"}, outputDir)
err := rb.BackupCommands([]string{"show version"}, []string{}, outputDir)
// Should not error on directory creation
if _, statErr := os.Stat(outputDir); os.IsNotExist(statErr) {
t.Error("Expected output directory to be created")
}
// Should create the output file even if commands fail
// Should return error when commands fail
if err == nil {
t.Error("Expected error when commands fail")
}
// Should NOT create the output file when commands fail (atomic behavior)
expectedFile := filepath.Join(outputDir, "testhost")
if _, statErr := os.Stat(expectedFile); os.IsNotExist(statErr) {
t.Error("Expected output file to be created")
if _, statErr := os.Stat(expectedFile); !os.IsNotExist(statErr) {
t.Error("Expected output file to NOT be created when commands fail")
}
}
func TestBackupCommandsEmptyCommands(t *testing.T) {
tempDir := t.TempDir()
rb := NewRouterBackup("testhost", "testuser", "testpass", "", 22)
rb := NewRouterBackup("testhost", "", "testuser", "testpass", "", 22)
err := rb.BackupCommands([]string{}, tempDir)
if err != nil {
t.Errorf("Expected no error for empty commands list, got %v", err)
err := rb.BackupCommands([]string{}, []string{}, tempDir)
if err == nil {
t.Error("Expected error for empty commands list (no successful commands)")
}
// Should still create the output file
// Should NOT create the output file when no commands succeed
expectedFile := filepath.Join(tempDir, "testhost")
if _, statErr := os.Stat(expectedFile); os.IsNotExist(statErr) {
t.Error("Expected output file to be created even for empty commands")
if _, statErr := os.Stat(expectedFile); !os.IsNotExist(statErr) {
t.Error("Expected output file to NOT be created when no commands succeed")
}
}
func TestDisconnectWithoutConnection(t *testing.T) {
rb := NewRouterBackup("testhost", "testuser", "testpass", "", 22)
rb := NewRouterBackup("testhost", "", "testuser", "testpass", "", 22)
// Should not panic or error when disconnecting without connection
rb.Disconnect()
@@ -155,29 +160,28 @@ func TestFindDefaultSSHKeyHomeError(t *testing.T) {
func TestBackupCommandsFileOperations(t *testing.T) {
tempDir := t.TempDir()
rb := NewRouterBackup("testhost", "testuser", "testpass", "", 22)
rb := NewRouterBackup("testhost", "", "testuser", "testpass", "", 22)
// Create some fake commands (they will fail but we can test file operations)
commands := []string{"show version", "show interfaces"}
err := rb.BackupCommands(commands, tempDir)
if err != nil {
t.Errorf("Unexpected error: %v", err)
err := rb.BackupCommands(commands, []string{}, tempDir)
if err == nil {
t.Error("Expected error when all commands fail")
}
// Check that output file was created
// Check that output file was NOT created (atomic behavior)
outputFile := filepath.Join(tempDir, "testhost")
_, err = os.ReadFile(outputFile)
if err != nil {
t.Fatalf("Failed to read output file: %v", err)
if err == nil {
t.Error("Expected output file to not exist when all commands fail")
}
// File should be created (it will be empty if all commands fail)
// This test just verifies the file creation works
// This test verifies that atomic file behavior works correctly
}
func TestRouterBackupConnectionState(t *testing.T) {
rb := NewRouterBackup("testhost", "testuser", "testpass", "", 22)
rb := NewRouterBackup("testhost", "", "testuser", "testpass", "", 22)
// Initially no client
if rb.client != nil {
@@ -190,3 +194,129 @@ func TestRouterBackupConnectionState(t *testing.T) {
t.Error("Expected client to remain nil after disconnect")
}
}
func TestNewRouterBackupWithAddress(t *testing.T) {
rb := NewRouterBackup("testhost", "192.168.1.100", "testuser", "testpass", "/path/to/key", 2222)
if rb.hostname != "testhost" {
t.Errorf("Expected hostname 'testhost', got '%s'", rb.hostname)
}
if rb.address != "192.168.1.100" {
t.Errorf("Expected address '192.168.1.100', got '%s'", rb.address)
}
}
func TestIsIPv6(t *testing.T) {
// Test IPv4 addresses
if isIPv6("192.168.1.1") {
t.Error("Expected '192.168.1.1' to be detected as IPv4, not IPv6")
}
if isIPv6("10.0.0.1") {
t.Error("Expected '10.0.0.1' to be detected as IPv4, not IPv6")
}
// Test IPv6 addresses
if !isIPv6("2001:678:d78:500::") {
t.Error("Expected '2001:678:d78:500::' to be detected as IPv6")
}
if !isIPv6("::1") {
t.Error("Expected '::1' to be detected as IPv6")
}
if !isIPv6("fe80::1") {
t.Error("Expected 'fe80::1' to be detected as IPv6")
}
// Test invalid addresses
if isIPv6("invalid.address") {
t.Error("Expected 'invalid.address' to not be detected as IPv6")
}
if isIPv6("hostname.example.com") {
t.Error("Expected 'hostname.example.com' to not be detected as IPv6")
}
}
func TestGetNetworkType(t *testing.T) {
// Test IPv4 addresses
if getNetworkType("192.168.1.1") != "tcp4" {
t.Errorf("Expected 'tcp4' for IPv4 address, got '%s'", getNetworkType("192.168.1.1"))
}
// Test IPv6 addresses
if getNetworkType("2001:678:d78:500::") != "tcp6" {
t.Errorf("Expected 'tcp6' for IPv6 address, got '%s'", getNetworkType("2001:678:d78:500::"))
}
if getNetworkType("::1") != "tcp6" {
t.Errorf("Expected 'tcp6' for IPv6 address, got '%s'", getNetworkType("::1"))
}
// Test hostnames (should default to tcp4)
if getNetworkType("hostname.example.com") != "tcp4" {
t.Errorf("Expected 'tcp4' for hostname, got '%s'", getNetworkType("hostname.example.com"))
}
}
func TestIPv6AddressFormatting(t *testing.T) {
// Test that we can create a RouterBackup with IPv6 address
// and that it stores the address correctly
rb := NewRouterBackup("testhost", "2001:678:d78:500::", "testuser", "testpass", "", 22)
if !isIPv6(rb.address) {
t.Error("Expected IPv6 address to be detected as IPv6")
}
if getNetworkType(rb.address) != "tcp6" {
t.Error("Expected IPv6 address to use tcp6 network type")
}
// Test IPv4 for comparison
rb4 := NewRouterBackup("testhost", "192.168.1.1", "testuser", "testpass", "", 22)
if isIPv6(rb4.address) {
t.Error("Expected IPv4 address to not be detected as IPv6")
}
if getNetworkType(rb4.address) != "tcp4" {
t.Error("Expected IPv4 address to use tcp4 network type")
}
}
func TestFilterOutput(t *testing.T) {
// Test with no exclude patterns
input := "line1\nline2\nline3"
result := filterOutput(input, []string{})
if result != input {
t.Errorf("Expected no filtering with empty patterns, got '%s'", result)
}
// Test with matching pattern
input = "# 2025-07-06 21:30:45 by RouterOS\nconfig line 1\nconfig line 2"
excludePatterns := []string{"^# ....-..-.. ..:..:.. by RouterOS"}
expected := "config line 1\nconfig line 2"
result = filterOutput(input, excludePatterns)
if result != expected {
t.Errorf("Expected '%s', got '%s'", expected, result)
}
// Test with multiple patterns
input = "line1\nDEBUG: debug info\nline2\nINFO: info message\nline3"
excludePatterns = []string{"^DEBUG:", "^INFO:"}
expected = "line1\nline2\nline3"
result = filterOutput(input, excludePatterns)
if result != expected {
t.Errorf("Expected '%s', got '%s'", expected, result)
}
// Test with no matches
input = "line1\nline2\nline3"
excludePatterns = []string{"nomatch"}
result = filterOutput(input, excludePatterns)
if result != input {
t.Errorf("Expected no filtering when patterns don't match, got '%s'", result)
}
}