SSH-remote-execution-and-SCP-with-Paramiko

files Lang: en Status: draft

This example shows how one can run a script on a remote host.

Probably this is not the best way, since I just needed it once and that was already some time ago.

I'm using paramiko. In this example the remote host we want to connect to is called REMOTE_HOST and may be something like 8.8.8.8---if you are Google and want to work on your DNS servers.

Run remote commands via SSH

SSHClient.exec_command() returns the tuple (stdin, stdout, stderr)

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(REMOTE_HOST)

stdin, stdout, stderr = client.exec_command('echo "I am running on the remote host $HOST"')

would therefore give us

>>> print(stdoutput)
I am running on the remote host 8.8.8.8

Copy files from and to a remote host

Connect to remote host

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(REMOTE_HOST)

Copy to the remote host

Setup sftp connection and transmit your file.

sftp = client.open_sftp()
sftp.put('local_file', 'remote_file')
sftp.close()

Copy/Move from the remote to us

sftp = client.open_sftp()
sftp.get(
    'remote_file',
    'local_file',
)

Maybe delete the remote file with

sftp.unlink('remote_file')
sftp.close()

After we have done everything we need to close the connection again

client.close()

Not tested, but might work as well

with Paramiko.SSHClient() as client:
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    with client.open_sftp() as sftp:
        sftp.put("local", "remote")
        sftp.get("remote", "local")
        sftp.unlink("remote")

links

social