Skip to content

Bug: Need to add support for ssh reconnect function. #181

@jfreeda

Description

@jfreeda

Problem/Opportunity

Propose adding a reconnect() method to the SSH session management module to improve resilience after device reboots or network service interruptions.

Why It’s Needed
When devices reboot, network services may take several seconds to come back online. This method provides a robust retry mechanism to re-establish SSH connections automatically, reducing manual intervention and improving test automation reliability.

Use Case This is especially useful in automated test environments where devices reboot frequently and SSH availability is delayed due to network stack initialization.

Steps to reproduce

No response

Expected Behavior

  • Any existing shell or console connections should be safely closed.
  • The session state should be reset to prepare for a fresh connection.
  • The method should attempt to reconnect up to retries times (default: 20), with a delay (default: 1 second) between each attempt.
  • On each attempt:
  • A new SSH client should be initialized.
  • The session should try to open a connection and launch an interactive shell.
  • If successful, the method should return True immediately.
  • If all attempts fail, the method should log an error and return False.
    This behavior ensures that the system can recover from device reboots or temporary network outages without manual intervention, making it ideal for automated environments.

Actual Behavior

def reconnect(self, retries=20, delay=1):
    """Attempt to reconnect the SSH session with retries and delay."""
    try:
        if self.shell:
            self.shell.close()
    except Exception:
        pass
    try:
        if self.console:
            self.console.close()
    except Exception:
        pass

    self.shell = None
    self.console = None
    self.is_open = False

    for attempt in range(retries):
        self.log.info(f"Reconnect attempt {attempt + 1}...")
        try:
            self.console = SSHClient()
            self.console.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
            if self.open():
                self.open_interactive_shell()
                return True
        except Exception as e:
            self.log.step(f"Reconnect attempt {attempt + 1} failed: {e}")
        time.sleep(delay)

    self.log.error("Failed to reconnect after multiple attempts.")
    return False

Notes (Optional)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions