|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import yaml |
| 4 | +import sys |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +from netmiko.encryption_handling import encrypt_value, get_encryption_key |
| 8 | + |
| 9 | + |
| 10 | +def encrypt_netmiko_yml( |
| 11 | + input_file: str, output_file: str | None, encryption_type: str |
| 12 | +) -> None: |
| 13 | + # Read the input YAML file |
| 14 | + input_path = Path(input_file).expanduser() |
| 15 | + with input_path.open("r") as f: |
| 16 | + config = yaml.safe_load(f) |
| 17 | + |
| 18 | + # Get the encryption key |
| 19 | + key = get_encryption_key() |
| 20 | + |
| 21 | + # Encrypt password and secret for each device |
| 22 | + for device, params in config.items(): |
| 23 | + if isinstance(params, dict): |
| 24 | + if "password" in params: |
| 25 | + encrypted_value = encrypt_value( |
| 26 | + params["password"], key, encryption_type |
| 27 | + ) |
| 28 | + params["password"] = encrypted_value |
| 29 | + if "secret" in params: |
| 30 | + # Use the same encrypted value for secret if it's identical to password |
| 31 | + params["secret"] = encrypted_value |
| 32 | + |
| 33 | + # Write the updated config to the output file or stdout |
| 34 | + if output_file: |
| 35 | + output_path = Path(output_file) |
| 36 | + with output_path.open("w") as f: |
| 37 | + yaml.dump(config, f) |
| 38 | + else: |
| 39 | + yaml.dump(config, sys.stdout) |
| 40 | + |
| 41 | + |
| 42 | +def main(): |
| 43 | + parser = argparse.ArgumentParser( |
| 44 | + description="Encrypt passwords in .netmiko.yml file" |
| 45 | + ) |
| 46 | + parser.add_argument( |
| 47 | + "--input_file", |
| 48 | + default="~/.netmiko.yml", |
| 49 | + help="Input .netmiko.yml file (default: ~/.netmiko.yml)", |
| 50 | + ) |
| 51 | + parser.add_argument( |
| 52 | + "--output_file", |
| 53 | + help="Output .netmiko.yml file with encrypted passwords (default: stdout)", |
| 54 | + ) |
| 55 | + parser.add_argument( |
| 56 | + "--encryption-type", |
| 57 | + choices=["fernet", "aes128"], |
| 58 | + default="fernet", |
| 59 | + help="Encryption type to use (default: fernet)", |
| 60 | + ) |
| 61 | + |
| 62 | + args = parser.parse_args() |
| 63 | + |
| 64 | + encrypt_netmiko_yml(args.input_file, args.output_file, args.encryption_type) |
| 65 | + |
| 66 | + if args.output_file: |
| 67 | + print( |
| 68 | + f"Encrypted .netmiko.yml file has been written to {Path(args.output_file).resolve()}", |
| 69 | + file=sys.stderr, |
| 70 | + ) |
| 71 | + |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + main() |
0 commit comments