14

我想删除我已经使用 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()

知道如何实现这一目标吗?

4

5 回答 5

18

我找到了一个解决方案:遍历远程位置的所有文件,然后调用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()
于 2010-08-04T15:00:37.500 回答
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()
于 2014-02-27T16:20:38.767 回答
8

Fabric例程可以像这样简单:

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

Fabric 非常适合在远程服务器上执行 shell 命令。Fabric 实际上在下面使用 Paramiko,因此如果需要,您可以同时使用两者。

于 2010-08-04T16:43:38.223 回答
2

对于@markolopa 答案,您需要 2 个导入才能使其正常工作:

import posixpath
from stat import S_ISDIR
于 2018-12-18T13:51:25.440 回答
2

我找到了一个解决方案,使用python3.7 e spark 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()
于 2019-04-18T18:34:25.567 回答