How to copy a file to a remote server in Python using SCP or SSH?


I have a text file on my local machine that is generated by a daily Python script run in cron.

I would like to add a bit of code to have that file sent securely to my server over SSH.

8/7/2016 9:05:30 AM

Accepted Answer

If you want the simple approach, this should work.

You'll want to ".close()" the file first so you know it's flushed to disk from Python.

import os
os.system("scp FILE USER@SERVER:PATH")
#e.g. os.system("scp")

You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).

ssh-keygen example

9/16/2008 1:01:43 AM

To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the Paramiko library, you would do something like this:

import os
import paramiko

ssh = paramiko.SSHClient() 
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)

(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow