如何在Python中删除远程SFTP服务器上目录中的所有文件?
我想删除已使用 Paramiko 连接到的远程服务器上给定目录中的所有文件。不过,我无法明确给出文件名,因为这些文件名会根据我之前放在那里的文件版本而有所不同。
这就是我想要做的... #TODO 下面的行是我正在尝试的调用,其中 remoteArtifactPath
类似于 /opt/foo/*
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()
# TODO: Need to somehow delete all files in remoteArtifactPath remotely
sftp.remove(remoteArtifactPath+"*")
# Close to end
sftp.close()
ssh.close()
Any知道我怎样才能实现这个目标吗?
I'd like to delete all the files in a given directory on a remote server that I'm already connected to using Paramiko. I cannot explicitly give the file names, though, because these will vary depending on which version of file I had previously put there.
Here's what I'm trying to do... the line below the #TODO is the call I'm trying where remoteArtifactPath
is something like /opt/foo/*
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, pkey=mykey)
sftp = ssh.open_sftp()
# TODO: Need to somehow delete all files in remoteArtifactPath remotely
sftp.remove(remoteArtifactPath+"*")
# Close to end
sftp.close()
ssh.close()
Any idea how I can achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我找到了一个解决方案:迭代远程位置中的所有文件,然后对每个文件调用
remove
:I found a solution: Iterate over all the files in the remote location, then call
remove
on each of them:您需要一个递归例程,因为您的远程目录可能有子目录。
You need a recursive routine since your remote directory may have subdirectories.
Fabric 例程可以像这样简单:
Fabric 非常适合在远程服务器上执行 shell 命令。 Fabric 实际上在底层使用了 Paramiko,所以如果需要的话可以同时使用两者。
A Fabric routine could be as simple as this:
Fabric is great for executing shell commands on remote servers. Fabric actually uses Paramiko underneath, so you can use both if you need to.
对于 @markolopa 的答案,您需要 2 次导入才能使其正常工作:
For @markolopa answer, you need 2 imports to get it working:
我找到了一个解决方案,使用python3.7和spur 0.3.20。很可能也适用于其他版本。
I found a solution, using python3.7 e spur 0.3.20. It is very possible that works with others versions as well.
所以我知道这是一篇较旧的帖子,但我仍然想给出一个简短的答案,我发现它比我发现的其他内容更有用。此外,这还使用 paramikos 内置函数,因此它应该适用于所有设备
So I know this is an older post but I would still like to give a short answer that I found to be more usefull than the rest I found. Also this uses paramikos in-built functions so it should work on all devices