Python Forum
Using Python to SSH and Run commands in a switch
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Python to SSH and Run commands in a switch
#1
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)
buran write Mar-19-2025, 08:46 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Threading with python in sending multiple commands? searching1 0 4,661 Jun-12-2019, 09:13 PM
Last Post: searching1
  Python script for show commands-CISCO Devices babbarsher 1 15,175 Dec-13-2017, 11:44 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020