gpt4 book ai didi

Python将SFTP服务器上的文件移动到另一个文件夹

转载 作者:行者123 更新时间:2023-12-03 16:22:22 35 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Rename file on remote server on Python

(2 个回答)


10 个月前关闭。




我编写了这个脚本来将文件从 SFTP 远程文件夹保存到本地文件夹。然后它从 SFTP 中删除该文件。我想更改它,以便它停止删除文件,而是将它们保存到 SFTP 上的备份文件夹中。我如何在 pysftp 中做到这一点?我找不到任何关于它的文档...

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)

不要担心我没有主机 key 或密码。一旦我让脚本工作,我就不会保持这种状态:)

最佳答案

使用 Connection.rename :

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

强制性警告:请勿设置 cnopts.hostkeys = None ,除非你不关心安全。有关正确的解决方案,请参阅 Verify host key with pysftp .

关于Python将SFTP服务器上的文件移动到另一个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59645430/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com