Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all files in directory on remote SFTP server in Python?

I'd like to delete all the files in a given directory on a remote server that I'm already connected to using Paramiko. I cannot explicitly give the file names, though, because these will vary depending on which version of file I had previously put there.

Here's what I'm trying to do... the line below the #TODO is the call I'm trying where 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?

like image 652
Cuga Avatar asked Aug 04 '10 14:08

Cuga


People also ask

How do I delete files from remote SFTP server?

To delete a file on the server, type "rm" and then the filename. Syntax: psftp> rm filename.

How do I delete multiple files in a directory in Python?

To delete multiple files, just loop over your list of files and use the above os. rmdir() function. To delete a folder containing all files you want to remove have to import shutil package. Then you can remove the folder as follows.


2 Answers

I found a solution: Iterate over all the files in the remote location, then call remove on 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()
like image 182
Cuga Avatar answered Sep 16 '22 13:09

Cuga


For @markolopa answer, you need 2 imports to get it working:

import posixpath
from stat import S_ISDIR
like image 21
broferek Avatar answered Sep 17 '22 13:09

broferek