I wrote this script to save a file from an SFTP remote folder to a local folder. It then removes the file from the SFTP. I want to change it so it stops removing files and instead saves them to a backup folder on the SFTP. How do I do that in pysftp? I cant find any documentation regarding it...
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
myHostname = "123"
myUsername = "456"
myPassword = "789"
with pysftp.Connection(host=myHostname, username=myUsername, password="789", cnopts=cnopts) as sftp:
sftp.cwd("/Production/In/")
directory_structure = sftp.listdir_attr()
local_dir= "D:/"
remote_dir = "/Production/"
remote_backup_dir = "/Production/Backup/"
for attr in directory_structure:
if attr.filename.endswith(".xml"):
file = attr.filename
sftp.get(remote_dir + file, local_dir + file)
print("Moved " + file + " to " + local_dir)
sftp.remove(remote_dir + file)
Don't worry about my no hostkey or the password in plain. I'm not keeping it that way once i get the script working :)
To run the file transferring program over a secure shell, you need to use the pysftp module in your Python program. This module is wrapped around paramiko and utilizes pycrypto libraries to perform the secure transferring of data. Pysftp is easy to implement.
Firstly import shutil module, and store the path of the source directory and path of the destination directory. Make a list of all files in the source directory using listdir() method in the os module. Now move all the files from the list one by one using shutil. move() method.
Use Connection.rename
:
sftp.rename(remote_dir + file, remote_backup_dir + file)
Obligatory warning: Do not set cnopts.hostkeys = None
, unless you do not care about security. For the correct solution see Verify host key with pysftp.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With