How to delete all files in a directory on a remote server in python?

I want to delete all files in a given directory on a remote server that I am already connected to using paramiko. However, I cannot explicitly specify the file names, because they will change depending on which version of the file I previously posted there.

Here is what I'm trying to do ... the line under #TODO is the call I'm trying to use when remoteArtifactPath is something like "/ 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()

Any idea how I can achieve this?

thank

+6
source share
5 answers

I found a solution: Iterate over all files in a remote location, then call removefor each of them:

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()
+9
source

A :

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

. Paramiko , , .

+8

You need a recursive routine, since your remote directory may have subdirectories.

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()
+5
source

For @markolopa's answer you need 2 imports to make it work:

import posixpath
from stat import S_ISDIR
+1
source

I found a solution using python3.7 e spur 0.3.20 . It is possible that it works with other versions.

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

All Articles