代码之家  ›  专栏  ›  技术社区  ›  Cuga

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

  •  6
  • Cuga  · 技术社区  · 14 年前

    我想删除远程服务器上给定目录中的所有文件,我已使用Paramiko连接到该服务器。不过,我不能明确给出文件名,因为这些文件名会因我之前放在那里的文件版本而异。

    这就是我想做的。。。“待办事项”下面的那行是我要打的电话 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()
    

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

    4 回复  |  直到 5 年前
        1
  •  13
  •   Cuga    14 年前

    我找到了一个解决方案:迭代远程位置中的所有文件,然后调用 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()
    
        2
  •  9
  •   markolopa    10 年前

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

    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()
    
        3
  •  8
  •   ianmclaury    14 年前

    A Fabric

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

    Fabric非常适合在远程服务器上执行shell命令。面料实际上使用帕拉米科下面,所以你可以使用两者如果你需要。

        4
  •  2
  •   Allan Santos    5 年前

    我找到了一个解决方案,使用 丁坝0.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()
    
        5
  •  1
  •   broferek    6 年前

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

    import posixpath
    from stat import S_ISDIR