Last active
January 31, 2018 07:08
-
-
Save gnilchee/86352a9484af977acc6329e72ccc15e3 to your computer and use it in GitHub Desktop.
Simple example executing commands via ssh with Paramiko
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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