Skip to content

Instantly share code, notes, and snippets.

@dangtrinhnt
Last active August 29, 2015 14:00
Show Gist options
  • Save dangtrinhnt/11246600 to your computer and use it in GitHub Desktop.
Save dangtrinhnt/11246600 to your computer and use it in GitHub Desktop.
SSH utils with connection fail-overs
import paramiko
import sys
SERVERS = ['<my first ssh server ip>', '<my second ssh server ip>', '<my third ssh server ip>']
USER = 'genius'
PASSWORD = 'mygeniuspassword'
class MySSHClient():
def __init__(self, domains=SERVERS, username=USER, password=PASSWORD):
self.domains = domains
self.username = username
self.password = password
self.return_str = ''
self.has_error = False
def do_connect(self):
for domain in self.domains:
print "Trying to connect to %s" % domain
try:
self.connection = paramiko.SSHClient()
self.connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.connection.connect(domain, username=self.username, password=self.password)
print "Connected to %s" % domain
break
except paramiko.AuthenticationException as e:
print "Authentication failed when connecting to %s\n" % domain
print "Error details: %s" % e
sys.exit(1)
except:
print "Could not connect to %s. Try another host." % domain
if self.domains.index(domain) >= (len(self.domains) -1):
print "Could not connect to all hosts. Giving up!"
sys.exit(1)
def execute_command(self, command):
if command:
stdin, stdout, stderr = self.connection.exec_command(command)
stdin.close()
error = str(stderr.read())
if error:
self.has_error = True
self.return_str = error
print 'has error'
else:
# reset has_error to the default value
self.has_error = False
self.return_str = str(stdout.read())
print 'no error'
print self.return_str
else:
print "no command to execute"
def do_close(self):
self.connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment