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

1

10

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

Theo answered 8/1, 2020 at 12:0 Comment(0)
G
11

Use Connection.rename:

sftp.rename(remote_dir + file, remote_backup_dir + file)

Obligatory warnings:

Gentian answered 8/1, 2020 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.