Skip to content
The Chat Archive
o4-mini-2025-04-16· OpenAI LMArena Human Preference 140K

send file over ssh with key from within python

  1. User

    send file over ssh with key from within python

  2. Assistant

    Here are three common ways to push a local file to a remote host over SSH (using a private‐key) from within Python:

    1. Using subprocess + scp
    2. Using Paramiko + SFTP
    3. Using Paramiko + SCP (via the scp module)

    1) subprocess + scp

    Pros: No extra deps beyond Python’s standard library and system scp
    Cons: Less control/error‐handling than a native library

    import subprocess
    import shlex
    
    def scp_send(local_path, remote_user, remote_host, remote_path, key_path, port=22):
        """
        Copies local_path to remote_user@remote_host:remote_path using scp -i key_path.
        Raises CalledProcessError on failure.
        """
        scp_cmd = f"scp -i {shlex.quote(key_path)} -P {port} " \
                  f"{shlex.quote(local_path)} " \
                  f"{shlex.quote(remote_user)}@{shlex.quote(remote_host)}:{shlex.quote(remote_path)}"
    
        # run and raise if nonzero exit
        subprocess.run(shlex.split(scp_cmd), check=True)
    
    if __name__ == "__main__":
        scp_send(
            local_path="myfile.txt",
            remote_user="ubuntu",
            remote_host="1.2.3.4",
            remote_path="/home/ubuntu/myfile.txt",
            key_path="~/.ssh/id_rsa"
        )
    

    2) Paramiko + SFTP

    Pros: Pure-Python, fine-grained control, better error handling
    Cons: You must manage host‐key policies yourself

    1. Install:
    pip install paramiko
    
    1. Example:
    import os
    import paramiko
    
    def sftp_send(local_path, remote_user, remote_host, remote_path, key_path, port=22):
        # Load private key from file (unencrypted or passphrase-protected)
        key = paramiko.RSAKey.from_private_key_file(os.path.expanduser(key_path))
        
        # Set up SSH client
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=remote_host,
                    port=port,
                    username=remote_user,
                    pkey=key)
        
        # Open SFTP session and push file
        sftp = ssh.open_sftp()
        sftp.put(local_path, remote_path)
        sftp.close()
        ssh.close()
    
    if __name__ == "__main__":
        sftp_send(
            local_path="myfile.txt",
            remote_user="ubuntu",
            remote_host="1.2.3.4",
            remote_path="/home/ubuntu/myfile.txt",
            key_path="~/.ssh/id_rsa"
        )
    

    3) Paramiko + SCP (scp module)

    Pros: Sits on top of Paramiko but mimics the scp interface
    Cons: Another dependency

    1. Install:
    pip install paramiko scp
    
    1. Example:
    import os
    import paramiko
    from scp import SCPClient
    
    def scp_via_paramiko(local_path, remote_user, remote_host, remote_path, key_path, port=22):
        key = paramiko.RSAKey.from_private_key_file(os.path.expanduser(key_path))
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=remote_host,
                    port=port,
                    username=remote_user,
                    pkey=key)
    
        # Instantiate SCP client over the existing Paramiko transport
        with SCPClient(ssh.get_transport()) as scp:
            scp.put(local_path, remote_path)
    
        ssh.close()
    
    if __name__ == "__main__":
        scp_via_paramiko(
            local_path="myfile.txt",
            remote_user="ubuntu",
            remote_host="1.2.3.4",
            remote_path="/home/ubuntu/myfile.txt",
            key_path="~/.ssh/id_rsa"
        )
    

    Choose whichever fits your needs:

    • For a quick drop-in, the scp + subprocess approach is simplest.
    • For advanced scenarios (progress callbacks, directory walks, robust error reporting), go with Paramiko + SFTP.
    • If you really like the SCP semantics but want a pure-Python stack, use Paramiko + the scp module.