I want to connect to a router via jumphost. I am using python. I already got router prompt but my command such as ‘show interface’ not submitted to the router. When I try manually using Putty, everything works fine.

— My Notebook —–> Jumphost —–> Router

Below is my code. Please help me guys. Thanks a lot.


import paramiko
import time

def run_ssh_commands(hostname, port, username, password, command_file_path, output_file_path, delay=2):
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        ssh_client.connect(hostname, port, username, password)

        with open(command_file_path, 'r') as file, open(output_file_path, 'w') as output:
            commands = file.readlines()

            for command in commands:
                # putty terminal emmulation
                stdin, stdout, stderr = ssh_client.exec_command(command, get_pty=True)

                # waiting output
                time.sleep(10)

                # read output 
                while True:
                    if stdout.channel.exit_status_ready():
                        break
                    if stdout.channel.recv_ready():
                        output_line = stdout.channel.recv(1024).decode('utf-8')
                        output.write(output_line)
                        print(output_line, end='')

    except Exception as e:
        print(f"Error happen: {e}")
    finally:
        ssh_client.close()

How to run

run_ssh_commands(‘xxx.xxx.xx.xxx’, xxxx, ‘xxxx’, ‘xxxx’, ‘C:p_input.txt’, ‘C:p_output.txt’)

I expect to connect the router and the command (such as ‘show interface’) submitted to router.

New contributor

yance dolly is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1