Skip to content

Instantly share code, notes, and snippets.

@89465127
Forked from batok/paramiko_example.py
Last active December 17, 2015 15:39
Show Gist options
  • Save 89465127/5632832 to your computer and use it in GitHub Desktop.
Save 89465127/5632832 to your computer and use it in GitHub Desktop.
import paramiko
class SSH():
def __init__(self, host, key_file, user="root"):
''' Open up a SSH connection using paramiko '''
key = paramiko.RSAKey.from_private_key_file(key_file)
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(hostname=host, username=user, pkey=key)
self.hostname = host # for helpful debug messages
self.key_file = key_file
# Clear the logfile
with open('remote_commands.log', 'w') as f:
f.write('')
def execute(self, command, stop_on_error=True):
''' Execute a remote command and print stdout and stderr as a consolidated output stream '''
with open('remote_commands.log', 'a') as f:
f.write(command + '\n')
stdin, stdout, stderr = self.client.exec_command(command + " 2>&1") # we will combine stderr onto stdout at the sender
for line in stdout: # and now we can print them as a consolidated stream without blocking
print line,
if stop_on_error and stdout.channel.recv_exit_status(): # Only stop if non-zero exit code
print_banner("Failed Command:\n{}\n\nTo debug this error, try ssh'ing in with:\nssh -i {} root@{}\n".format(command, self.key_file, self.hostname))
raise RuntimeError("An error occurred (see output above), and stop_on_error was set to True.")
def close(self):
self.client.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment