[Python] How to make a ssh connection from another ssh connected machine

Discussão em 'Python' iniciado por Stack, Agosto 30, 2025.

  1. Stack

    Stack Membro Participativo

    I have 3 linux machines (hostA, hostB, hostC), from hostA I will remote login into hostB via ssh and transfer some file/directory from hostA to hostB. Once transfer is done from hostA to hostB, I would like to login and transfer the same files from hostB to hostC. hostA can only communicate with hostB and only hostB can communicate with hostC. I am trying to achieve this using the below python code, but I'm not getting how to make SSH login from hostB onto hostC and also transfer the file/directory transferred from (hostA to hostB) to hostC.

    main.py

    import os
    import paramiko

    def main():
    try:
    ssh_client_b = connect_to_host("100.100.100.100", "hostB", "hostB123")
    execute_command_over_ssh(ssh_client_b,
    "uname")
    execute_command_over_ssh(ssh_client,
    "ls /home/hostB/")
    transfer_file_or_directory(ssh_client_b,
    "/home/hostA/repos/repo1/",
    "/home/hostB/repos/")

    # 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("200.200.200.200", "hostC", "hostC123")
    # execute_command_over_ssh(ssh_client_c,
    # "uname")
    # execute_command_over_ssh(ssh_client_c,
    # "ls /home/hostC/")
    # transfer_file_or_directory(ssh_client,
    # "/home/hostB/repos/repo1/",
    # "/home/hostC/repos/")

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

    def connect_to_host(host_name, user_name, password):
    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,
    password = password)
    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 transfer_file_or_directory(ssh_client, local_path, remote_path):
    sftp = ssh_client.open_sftp()

    if os.path.isfile(local_path):
    transfer_file(sftp, local_path, remote_path)
    print("file transfer done")
    elif os.path.isdir(local_path):
    dir_name = os.path.basename(os.path.dirname(local_path))
    mkdir(sftp, '%s/%s' % (remote_path, dir_name), ignore_existing=True)
    transfer_directory(sftp, local_path, os.path.join(remote_path, dir_name))
    print("directory transfer done")
    else:
    print("invalid localpath: {local_path}")

    sftp.close()

    def transfer_file(sftp, local_path, remote_path):
    sftp.put(local_path, remote_path)

    def transfer_directory(sftp, local_path, remote_path):
    for item in os.listdir(local_path):
    if os.path.isfile(os.path.join(local_path, item)):
    sftp.put(os.path.join(local_path, item), '%s/%s' % (remote_path, item))
    else:
    mkdir(sftp, '%s/%s' % (remote_path, item), ignore_existing=True)
    transfer_directory(sftp, os.path.join(local_path, item), '%s/%s' % (remote_path, item))

    def mkdir(sftp, path, mode=511, ignore_existing=False):
    ''' Augments mkdir by adding an option to not fail if the folder exists '''
    try:
    sftp.mkdir(path, mode)
    except IOError:
    if ignore_existing:
    pass
    else:
    raise

    Continue reading...

Compartilhe esta Página