如何在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()
有没有什么办法可以实现这个?
6 个回答
7
一个Fabric的例子可以简单到这个程度:
with cd(remoteArtifactPath):
run("rm *")
Fabric非常适合在远程服务器上执行命令。实际上,Fabric是基于Paramiko这个工具的,所以如果你需要的话,可以同时使用这两个工具。
12
你需要一个递归的程序,因为你的远程目录可能还有子目录。
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()
21
我找到了解决办法:遍历远程位置的所有文件,然后对每个文件调用 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()