def login_ssh(login_args={}, max_login_attempts=5): r""" Login on the latest open SSH connection. Retry on failure up to max_login_attempts. The caller is responsible for making sure there is an open SSH connection. Description of argument(s): login_args A dictionary containing the key/value pairs which are acceptable to the SSHLibrary login function as parms/args. At a minimum, this should contain a 'username' and a 'password' entry. max_login_attempts The max number of times to try logging in (in the event of login failures). """ gp.lprint_executing() global sshlib # Get connection data for debug output. connection = sshlib.get_connection() gp.lprintn(sprint_connection(connection)) for login_attempt_num in range(1, max_login_attempts + 1): gp.lprint_timen("Logging in to " + connection.host + ".") gp.lprint_var(login_attempt_num) try: out_buf = sshlib.login(**login_args) except Exception as login_exception: # Login will sometimes fail if the connection is new. except_type, except_value, except_traceback = sys.exc_info() gp.lprint_var(except_type) gp.lprint_varx("except_value", str(except_value)) if except_type is paramiko.ssh_exception.SSHException and\ re.match(r"No existing session", str(except_value)): continue else: # We don't tolerate any other error so break from loop and # re-raise exception. break # If we get to this point, the login has worked and we can return. gp.lpvar(out_buf) return # If we get to this point, the login has failed on all attempts so the # exception will be raised again. raise(login_exception)