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

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) sftp.close() ssh.close() (You would probably want to deal with unknown hosts, errors, creating any … Read more

How to pass password to scp?

Use sshpass: sshpass -p “password” scp -r [email protected]:/some/remote/path /some/local/path or so the password does not show in the bash history sshpass -f “/path/to/passwordfile” scp -r [email protected]:/some/remote/path /some/local/path The above copies contents of path from the remote host to your local. Install : ubuntu/debian apt install sshpass centos/fedora yum install sshpass mac w/ macports port install … Read more

How to scp in Python?

Try the Python scp module for Paramiko. It’s very easy to use. See the following example: import paramiko from scp import SCPClient def createSSHClient(server, port, user, password): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, port, user, password) return client ssh = createSSHClient(server, port, user, password) scp = SCPClient(ssh.get_transport()) Then call scp.get() or scp.put() to do SCP … Read more