views:

59

answers:

2

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?

Thanks

+1  A: 

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()
Cuga
+1  A: 

A Fabric routine could be as simple as this:

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

Fabric is great for executing shell commands on remote servers. Fabric actually uses Paramiko underneath, so you can use both if you need to.

ianmclaury
thanks, i'll look into that
Cuga