Skip to content

Instantly share code, notes, and snippets.

@gnilchee
Last active January 31, 2018 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnilchee/86352a9484af977acc6329e72ccc15e3 to your computer and use it in GitHub Desktop.
Save gnilchee/86352a9484af977acc6329e72ccc15e3 to your computer and use it in GitHub Desktop.
Simple example executing commands via ssh with Paramiko
#!/usr/bin/env python
import paramiko
SSH_HOST='host.example.com'
SSH_USER='admin_user'
SSH_KEY='/home/user/.ssh/id_rsa'
def do_ssh_command(command):
try:
with paramiko.SSHClient() as client:
client.load_system_host_keys()
client.connect(SSH_HOST, username=SSH_USER, key_filename=SSH_KEY)
_stdin, stdout, _stderr = client.exec_command(command)
for line in iter(lambda: stdout.readline(2048).rstrip(), ""):
print(line)
stderr = _stderr.read()
if len(stderr) > 0:
raise SystemExit(stderr)
except Exception as err:
raise SystemExit("There was an issue with ssh command: {}".format(err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment