Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python moving file on SFTP server to another folder [duplicate]

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 :)

like image 894
KristianB Avatar asked Jan 08 '20 12:01

KristianB


People also ask

How do I transfer files using SFTP in Python?

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.

How do I move a folder to another folder in Python?

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.


1 Answers

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.

like image 183
Martin Prikryl Avatar answered Nov 15 '22 00:11

Martin Prikryl