Paramiko's SSHClient with SFTP
Sample Usage:
import paramikoparamiko.util.log_to_file("paramiko.log")# Open a transporthost,port = "example.com",22transport = paramiko.Transport((host,port))# Auth username,password = "bar","foo"transport.connect(None,username,password)# Go! sftp = paramiko.SFTPClient.from_transport(transport)# Downloadfilepath = "/etc/passwd"localpath = "/home/remotepasswd"sftp.get(filepath,localpath)# Uploadfilepath = "/home/foo.jpg"localpath = "/home/pony.jpg"sftp.put(localpath,filepath)# Closeif sftp: sftp.close()if transport: transport.close()
The accepted answer works. But with its use of the low-level Transport
class, it bypasses a host key verification, what is a security flaw, as it makes the code susceptible to Man-in-the-middle attacks.
Better is to use the right Paramiko SSH API, the SSHClient
, which does verify the host key:
import paramikoparamiko.util.log_to_file("paramiko.log")ssh = paramiko.SSHClient()ssh.connect(host, username='user', password='password')# or # key = paramiko.RSAKey.from_private_key_file('id_rsa')# ssh.connect(host, username='user', pkey=key)sftp = ssh.open_sftp()sftp.get(remotepath, localpath)# orsftp.put(localpath, remotepath2)
For details about verifying the host key, see:
Paramiko "Unknown Server"