Cug*_*uga 9 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.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()
Run Code Online (Sandbox Code Playgroud)
知道我怎么能做到这一点?
谢谢
Cug*_*uga 11
我找到了一个解决方案:迭代远程位置的所有文件,然后调用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()
Run Code Online (Sandbox Code Playgroud)
一个面料计划也可能是如此简单:
with cd(remoteArtifactPath):
run("rm *")
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20909 次 |
| 最近记录: |