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

2024-04-18 17:05:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想删除远程服务器上已使用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()

你知道我怎样才能做到这一点吗?


Tags: 文件topath服务器目录paramikoclose远程
3条回答

我找到了一个解决方案:遍历远程位置的所有文件,然后对每个文件调用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()

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

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

一个Fabric例程可以如此简单:

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

Fabric非常适合在远程服务器上执行shell命令。织物下面实际上使用了Paramiko,所以如果需要的话可以同时使用。

相关问题 更多 >