Search code examples
pythonsshparamikoscpopenssh

SSH to server and from there SCP to another server


I want to SSH to a Linux server and from there, do a SCP copy to one ESXI server. Both need username and password.

  1. Connect to Linux box:

    ssh_linux = paramiko.SSHClient()
    ssh_linux.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_linux.connect(linux_host, username=linux_user, password=linux_password)
    
  2. SCP:

    scp_command = f"scp -o StrictHostKeyChecking=no {local_file_path} {esxi_user}@{esxi_host}:{remote_file_path}"
    logging.info(f"{scp_command}")
    stdin, stdout, stderr = ssh_linux.exec_command(scp_command)
    scp_exit_status = stdout.channel.recv_exit_status()
    
    if scp_exit_status == 0:
        logging.info(f"File {file} copied successfully.")
    else:
        logging.error(f"Error copying. SCP command failed with exit code {scp_exit_status}")
        logging.error(f"SCP STDOUT: {stdout.read().decode()}")
        logging.error(f"SCP STDERR: {stderr.read().decode()}")
        ssh_linux.close()
    

How to send password of the ESXI host to the scp command?


Solution

  • See Pass input/variables to command/script over SSH using Python Paramiko

    Though OpenSSH tools do not accept password from stdin. You have to fake terminal by passing get_pty=True to SSHClient.exec_command.


    Overal, I do not think this is the right approach.

    Instead, I'd use port forwarding. See Nested SSH using Python Paramiko.


    Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

    And for the same reason, do not use StrictHostKeyChecking=no.