|
| 1 | +#!/usr/bin/env python |
| 2 | +# For SSH create user with privilege level 15 |
| 3 | +import getpass |
| 4 | +from pexpect import pxssh |
| 5 | + |
| 6 | +# Define devices and their details |
| 7 | +devices = { |
| 8 | + "S1": {"ip": "172.16.141.11"}, |
| 9 | + "R1": {"ip": "172.16.141.12"}, |
| 10 | +} |
| 11 | + |
| 12 | +# Commands to execute on each device |
| 13 | +commands = ["term length 0", "show run"] |
| 14 | + |
| 15 | +# Get credentials from the user |
| 16 | +username = input("Username: ") |
| 17 | +password = getpass.getpass("Password: ") |
| 18 | + |
| 19 | +# Loop through devices and backup configurations |
| 20 | +for device in devices.keys(): |
| 21 | + outputFileName = device + "_output.cfg" |
| 22 | + device_ip = devices[device]["ip"] |
| 23 | + |
| 24 | + # Initialize the SSH session |
| 25 | + child = pxssh.pxssh() |
| 26 | + # Manually specify the prompt to expect from the device (e.g., "#") |
| 27 | + child.PROMPT = r"[#>]" |
| 28 | + |
| 29 | + # Attempt to login with the specified prompt pattern |
| 30 | + child.login( |
| 31 | + device_ip, |
| 32 | + username.strip(), |
| 33 | + password.strip(), |
| 34 | + auto_prompt_reset=False, # Do not attempt to auto-set the prompt |
| 35 | + ) |
| 36 | + print(f"Backing up configuration for device: {device}") |
| 37 | + |
| 38 | + # Open the output file for writing |
| 39 | + with open(outputFileName, "wb") as f: |
| 40 | + # Loop through each command and write the output |
| 41 | + for command in commands: |
| 42 | + child.sendline(command) |
| 43 | + # Wait for the specified prompt to appear again |
| 44 | + child.expect(child.PROMPT) |
| 45 | + f.write(child.before) # Write the command output to the file |
| 46 | + |
| 47 | + # Logout from the device |
| 48 | + child.logout() |
| 49 | + |
| 50 | +print("Backup process complete.") |
0 commit comments