Fabric is great, but isn't 100% compatible with Python 3. There is Fabric3, which does work, but sometimes you don't want to have to issue `fab <something>` but instead want to issue a command as part of a larger bit of Python.
I ran into this situation today where I wanted to issue a few commands over ssh to a remote host as part of a Click command I'm building to do some ops automation here at REVSYS.
It's probably not perfect in terms of error handling, but it sure is simple! Here is all you need to do:
from fabric.api import env from fabric.operations import run as fabric_run from fabric.context_managers import settings, hide def run(user, host, command): """ Run a command on the host. Assumes user has SSH keys setup """ env.user = user env.use_ssh_config = True with settings(hide('everything'), host_string=host): results = fabric_run(command) return results
You'll need to install the Fabric3 library with a simple:
pip install Fabric3
And away you go! All this is doing is re-using Fabric3's run() function while silencing all of the normal Fabric style output and forcing the user, host, and to use the calling environment's ssh configuration settings (like your ~/.ssh/config).
We could accomplish this more directly with Paramiko or work some subprocess magic to call our ssh, but this was the simplest and fastest way I solved the ssh problem today.
Hope you find this little trick useful! Happy Hacking!