I'm attempting to download a set of files from an SFTP server. I can download the files successfully, but now I want to change the script so that as the files download, they go to a specified directory on my local server.
I attempted doing this with the sftp.getfo()
command, but am getting an error:
getfo() got an unexpected keyword argument 'fl'
#SET LOCAL DIRECTORY
directory1 = r'C:\Users\Me\Documents\test sftp'
#CONNECT TO SFTP
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp = pysftp.Connection(host = hostname, username = usereu, password = passeu, cnopts = cnopts)
print("Connection successfully established ... ")
#DOWNLOAD ALL FILES IN FOLDER
files = sftp.listdir()
for file in files:
sftp.getfo(remotepath = file, fl = directory1)
print(file,' downloaded successfully ')
Am I using the right command here or is there a better way to do this?
Thanks!
To download a file to local path, use Connection.get
(not getfo
):
sftp.get(remotepath=file, localpath=os.path.join(directory1, file))
Some notes:
remotepath
takes path to the remote file, not just filename. Your code (which passes filename only) works only because you are downloading from the home folder.
The pysftp is dead. Do not use it. Use Paramiko. See pysftp vs. Paramiko
For an example, see Download file from SFTP server in Python Paramiko
Do not set cnopts.hostkeys = None
, unless you do not care about security. For the correct solution see Verify host key with pysftp.