Using Fabric with an SSH public key

Inspired by this tweet by Mike Driscoll I decided to try using Fabric to run commands over SSH from a Python script, using a public key for authentication.

This worked:

from fabric import Connection

c = Connection(
    host="my-server.simonwillison.net",
    user="root",
    connect_kwargs={
        "key_filename": "/path/to/id_rsa.pub",
    },
)
output = c.run("pwd && ls -lah")
# This outputs to the console but also lets me retrieve the result like so:
string_output = output.stdout

Mike's Tweet recipe looks like this:

with Connection(f"{username}@{host}:{port}", connect_kwargs={"password: "pw"}) as conn:
    output = conn.run("docker images")
    print(output.stdout)

Created 2021-10-06T11:22:47-07:00 · Edit