Search code examples
pythonsshautomationscp

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.


Solution

  • You can call the scp bash command (it copies files over SSH) with subprocess.run:

    import subprocess
    subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
    #e.g. subprocess.run(["scp", "foo.bar", "joe@srvr.net:/path/to/foo.bar"])
    

    If you're creating the file that you want to send in the same Python program, you'll want to call subprocess.run command outside the with block you're using to open the file (or call .close() on the file first if you're not using a with block), so you know it's flushed to disk from Python.

    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).