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

ファブリックルーチンは、次のように単純にすることができます。

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

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 espur0.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 に答える