2010-08-04 41 views
5

我想删除已使用paramiko连接到的远程服务器上给定目录中的所有文件。不过,我不能明确地提供文件名,因为这些会根据我以前放在那里的文件版本而有所不同。如何删除python中的远程服务器上目录中的所有文件?

这里就是我试图做...的#TODO下面的一行是我试图调用其中remoteArtifactPath是一样的东西“的/ opt /富/ *”

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

任何想法我怎么能做到这一点?

感谢

回答

7

我找到了解决办法:遍历所有的文件,在远程位置,然后调用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() 
+3

我建议使用'''os.path.join而不是'''sftp.remove(remoteArtifactPath +文件)'''(remoteArtifactPath,文件)''',因为'''os.path中。 join()'''是平台独立的。行分隔符可能因平台而异,使用os.path.join可确保无论平台如何,均可正确生成路径。 – 9monkeys 2012-07-17 14:23:23

8

一个Fabric计划也可能是这样简单:

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

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

+0

谢谢,我会研究一下 – Cuga 2010-08-04 17:03:16

+0

+1,因为在EC2中我们的操作系统映像默认禁用了sftp。 (我不确定这是亚马逊的默认还是我的公司,但这个问题是无关紧要的,因为我无法改变,但我仍然需要删除文件。 – 2015-06-26 19:14:48

2

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

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() 
相关问题