如何在Python中删除远程SFTP服务器上目录中的所有文件?

发布于 2021-01-29 16:58:57

我想删除使用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()

知道我该如何实现吗?

关注者
0
被浏览
165
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看