how to delete my file if exits in the remote server with paramiko?

Roy Smith roy at panix.com
Sun Dec 14 10:58:55 EST 2014


In article <mailman.16944.1418561416.18130.python-list at python.org>,
 "????" <1248283536 at qq.com> wrote:

> I want to delete the file "names.txt" if it exits in "/home/names.txt" in my 
> remote vps server.
>  import paramiko
> host = "vps ip"
> port = 22
> transport = paramiko.Transport((host, port))
> password = "key"
> username = "root"
> transport.connect(username = username, password = password)
> sftp = paramiko.SFTPClient.from_transport(transport)
> if "names.txt" in sftp.listdir("/home") : sftp.remove("/home/names.txt")
>   
>   
>  Is there more elegant way to do the same work?

I generally try to avoid using raw paramiko.  Fabric gives you a much 
nicer interface to the same basic functionality (and is indeed layered 
on top of paramiko).  The above functionality can be expressed in fabric 
as simply as:


---------------------------------------------
from fabric.api import env, run

env.host_string = "my-remote-hostname"
run("rm -f /tmp/roy-temp")
---------------------------------------------

Of course, I cheated a little bit.  I'm assuming you have ssh access to 
your remote host; the above code depends on that.  Going through sftp 
makes everything more difficult.  You can drive sftp through fabric, but 
it's a lot more painful.  I also assume that you can use ssh key 
authentication, which simplifies everything compared to passing 
usernames and passwords around.



More information about the Python-list mailing list