如何在 Python 中删除远程 SFTP 服务器上目录中的所有文件? [英] How to delete all files in directory on remote SFTP server in Python?

查看:125
本文介绍了如何在 Python 中删除远程 SFTP 服务器上目录中的所有文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除我已经使用 Paramiko 连接到的远程服务器上给定目录中的所有文件.不过,我无法明确给出文件名,因为这些名称会因我之前放置在那里的文件版本而异.

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.

这是我正在尝试做的...#TODO 下面的行是我正在尝试的调用,其中 remoteArtifactPath 类似于 /opt/foo/*

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?

推荐答案

我找到了一个解决方案:遍历远程位置的所有文件,然后对每个文件调用 remove:

I found a solution: Iterate over all the files in the remote location, then call remove on each of them:

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

# Updated code below:
filesInRemoteArtifacts = sftp.listdir(path=remoteArtifactPath)
for file in filesInRemoteArtifacts:
    sftp.remove(remoteArtifactPath+file)

# Close to end
sftp.close()
ssh.close()

这篇关于如何在 Python 中删除远程 SFTP 服务器上目录中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆