Python Forum

Full Version: Using Python to SSH and Run commands in a switch
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I had ChatGPT write me some code for being able to SSH into a list of switches and run a text file with a list of commands for a Juniper switch. When I run the code I am able to establish a SSH connection, and enter configuration mode, but I keep getting a syntacs error on my other commands that I know are correct. I know that they are correct, because when I SSH into the switch and paste the cli in manually it takes the commands. Please see code below.

import paramiko
import getpass
import time

def run_commands_on_juniper(host, commands, username, password):
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(host, username=username, password=password, timeout=10)

        for command in commands:
            stdin, stdout, stderr = client.exec_command(command)
            time.sleep(1)  # Delay added to ensure command execution stability
            print(f"\n[Running command on {host}]: {command}")
            print(stdout.read().decode())
            error_output = stderr.read().decode()
            if error_output:
                print(f"[Error]: {error_output}")

    except Exception as e:
        print(f"Connection to {host} failed: {e}")

    finally:
        client.close()

def read_file(file_path):
    with open(file_path, 'r') as file:
        return [line.strip() for line in file.readlines() if line.strip()]

if __name__ == "__main__":
    switch_file = "filepath" #Changed for Security
    command_file = "filepath" #Changed for Security

    switches = read_file(switch_file)
    commands = read_file(command_file)

    username = input("Enter your username: ")
    password = getpass.getpass("Enter your password: ")

    for switch_ip in switches:
        run_commands_on_juniper(switch_ip, commands, username, password)