[Python] Execute commands over nested ssh connection

Discussão em 'Python' iniciado por Stack, Setembro 2, 2025.

  1. Stack

    Stack Membro Participativo

    This is a followup of my previous post. I updated my code as per this post. but getting an exception when connecting to hostC

    import os
    import paramiko

    def main():
    try:
    private_key = paramiko.RSAKey(filename="/home/hostA/.ssh/id_rsa")
    ssh_client_b = connect_to_host("100.100.100.100", "hostB", private_key)
    execute_command_over_ssh(ssh_client_b,
    "uname")
    execute_command_over_ssh(ssh_client,
    "ls /home/hostB/")

    # hostC is network reachable only from hostB
    # below is where I'm stuck where I need to login to remote host hostC via SSH from hostB
    # and transfer the same file/directory transferred previously to hostB from hostA
    # Also, I would like to know how to issue command to execute in hostC and get back the result of it

    ssh_client_c = connect_to_host_using_channel(ssh_client_b, "200.200.200.200", "100.100.100.100", "hostB", hostC")
    execute_command_over_ssh(ssh_client_c,
    "uname")
    execute_command_over_ssh(ssh_client_c,
    "ls /home/hostC/")

    finally:
    print("closing ssh client connection")
    ssh_client_b.close()
    ssh_client_c.close()

    def connect_to_host(host_name, user_name, private_key):
    try:
    # Create object of SSHClient and
    # connecting to SSH
    ssh_client = paramiko.SSHClient()

    # Adding new host key to the local
    # HostKeys object(in case of missing)
    # AutoAddPolicy for missing host key to be set before connection setup.
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    ssh_client.connect(host_name,
    port = 22,
    username = user_name,
    pkey = private_key)
    except:
    ssh_client.close()

    return ssh_client

    def execute_command_over_ssh(ssh_client, command):
    # below line command will actually
    # execute in your remote machine
    (stdin, stdout, stderr) = ssh_client.exec_command(command)

    # redirecting all the output in cmd_output
    # variable
    cmd_output = stdout.read()
    print('log printing: ', command, cmd_output)

    def connect_to_host_using_channel(vm, dest_ip, channel_ip, channel_user_name, dest_user_name):
    try:
    vm_transport = vm.get_transport()
    dest_addr = (dest_ip, 22)
    local_addr = (channel_ip, 22)
    vm_channel = vm_transport.open_channel("direct-tcpip", dest_addr, local_addr)

    jhost = paramiko.SSHClient()
    jhost.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    private_key = paramiko.RSAKey(filename = f"{channel_user_name}@{channel_ip}:/home/{channel_user_name}/.ssh/id_rsa")
    jhost.connect(dest_ip, username = dest_user_name, pkey = private_key, sock = vm_channel)
    except:
    print(f"Error while connecting to {dest_user_name}")
    jhost.close()

    return jhost


    Error

    Traceback (most recent call last):
    File "/home/hostA/test-repos/.venv/bin/test-framework", line 10, in <module>
    sys.exit(main())
    ^^^^^^
    File "/home/hostA/test-repos/src/test_framework/__init__.py", line 19, in main
    execute_command_over_ssh(ssh_client_c,
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/hostA/test-repos/src/test_framework/__init__.py", line 52, in execute_command_over_ssh
    (stdin, stdout, stderr) = ssh_client_c.exec_command(command)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/home/hostA/test-framework/.venv/lib/python3.12/site-packages/paramiko/client.py", line 558, in exec_command
    chan = self._transport.open_session(timeout=timeout)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    AttributeError: 'NoneType' object has no attribute 'open_session'

    Continue reading...

Compartilhe esta Página