1

I am trying to do SFTP between two servers using a Python script. At first, my attempt was to download the files to my local machine, it is failing with permission error, not sure why it is restricting to copy files to my local folder.

Any ideas will be appreciated. Below is the code snippet (Only half done)

import paramiko

host= <defined here>
user = <defined here>
pswd = <defined here>

ssh = paramiko.SSHClient()
# automatically add keys without requiring human intervention
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
ssh.connect(host, username=user, password=pswd)
ftp = ssh.open_sftp()

ftp.get(source_path,destination_path)

ftp.close()
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992

1 Answers1

2

EDIT:
Please read the legend himself, @Martin Prikryl's comment for a more in depth explanation and better solution.

Does this do the trick?

import paramiko

from_host = <defined here>
from_user = <defined here>
from_pass = <defined here>

to_host = <defined here>
to_user = <defined here>
to_pass = <defined here>

from_client = paramiko.SSHClient()
# automatically add keys without requiring human intervention
from_client.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
from_client.connect(from_host, username=from_user, password=from_password)

to_client = paramiko.SSHClient()
# automatically add keys without requiring human intervention
to_client.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
to_client.connect(to_host, username=to_user, password=to_password)

# Open an sftp client for both servers
from_ftp = from_client.open_sftp()
to_ftp = to_client.open_sftp()

# Open the file on the from server. Returns a file like object
with from_ftp.open(source_path) as f:
    # putfo takes an open file object and creates it at the specifies path
    to_ftp.putfo(f, path_where_you_want_the_file_on_to_server)  # need filename

from_ftp.close()
to_ftp.close()

SFTPClient documentation

phil
  • 403
  • 2
  • 7
  • 1
    +1 – Though see [Reading file opened with Python Paramiko SFTPClient.open method is slow](https://stackoverflow.com/q/58433996/850848). + `AutoAddPolicy` used this way does not *"automatically add keys without requiring human intervention"*. Instead it always blindly allow any host key, what is a security flaw (I know that you copied the code from the questions). For a correct solution, see [Paramiko "Unknown Server"](https://stackoverflow.com/q/10670217/850848#43093883). – Martin Prikryl Nov 13 '21 at 06:30