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

如何在Python中删除远程SFTP服务器上目录中的所有文件?,python,sftp,paramiko,Python,Sftp,Paramiko,我想删除远程服务器上给定目录中的所有文件,我已使用Paramiko连接到该服务器。不过,我无法明确给出文件名,因为这些文件名会因我之前放置的文件版本而异 这就是我想做的。。。#TODO下面的一行是我正在尝试的调用,remoteArtifactPath类似于/opt/foo/* ssh = paramiko.SSHClient() ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) ssh

我想删除远程服务器上给定目录中的所有文件,我已使用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()

我找到了一个解决方案:迭代远程位置中的所有文件,然后对每个文件调用
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()
例行程序可以如此简单:

with cd(remoteArtifactPath):
    run("rm *")

Fabric非常适合在远程服务器上执行shell命令。Fabric实际上在下面使用了Paramiko,所以如果需要,您可以同时使用这两个函数。

您需要一个递归例程,因为您的远程目录可能有子目录

def rmtree(sftp, remotepath, level=0):
    for f in sftp.listdir_attr(remotepath):
        rpath = posixpath.join(remotepath, f.filename)
        if stat.S_ISDIR(f.st_mode):
            rmtree(sftp, rpath, level=(level + 1))
        else:
            rpath = posixpath.join(remotepath, f.filename)
            print('removing %s%s' % ('    ' * level, rpath))
            sftp.remove(rpath)
    print('removing %s%s' % ('    ' * level, remotepath))
    sftp.rmdir(remotepath)

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()
rmtree(sftp, remoteArtifactPath)

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

对于@markolopa answer,您需要两次导入才能使其正常工作:

import posixpath
from stat import S_ISDIR

我找到了一个解决方案,使用python3.7espur0.3.20。这很可能也适用于其他版本

import spur

shell = spur.SshShell( hostname="ssh_host", username="ssh_usr", password="ssh_pwd")
ssh_session = shell._connect_ssh()

ssh_session.exec_command('rm -rf  /dir1/dir2/dir3')

ssh_session.close()

我建议使用
os.path.join(remoteArtifactPath,file)
而不是
sftp.remove(remoteArtifactPath+file)
,因为
os.path.join()与平台无关。行分隔符可能因平台而异,使用os.path.join可确保正确生成路径,而不考虑平台。这是否也会删除隐藏文件?+1,因为在EC2中,我们的操作系统映像默认禁用sftp。(我不确定这是亚马逊的默认设置还是我的公司的默认设置,但这个问题无关紧要,因为我无法更改它。不过,我还是需要删除该文件。