# Python SSH libraries

Python SSH libraries open encrypted connections to remote machines to run commands, transfer files, and forward ports. A native client implements the SSH protocol in Python or binds a C library rather than driving the system ssh command. These libraries let deployment scripts, network automation tools, and AI agents operate servers and devices remotely.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Pexpect](#pexpect) | 137.7M | 2.9K | Nov 2023 | ISC license |
| [Paramiko](#paramiko) | 111.1M | 9.9K | Oct 2026 | LGPL-2.1 |
| [AsyncSSH](#asyncssh) | 16.3M | 1.8K | Oct 2026 | EPL-2.0 OR GPL-2.0-or-later |
| [sshtunnel](#sshtunnel) | 14.7M | 1.3K | Oct 2026 | MIT |
| [Fabric](#fabric) | 7.9M | 15.5K | Apr 2026 | BSD-2-Clause |
| [Netmiko](#netmiko) | 967.5K | 4.3K | Sep 2026 | MIT |
| [ssh2-python](#sshtwo-python) | 297.4K | 237 | Oct 2025 | LGPL-2.1-only |
| [ssh-python](#ssh-python) | 237.5K | 48 | Oct 2025 | LGPL-2.1-only |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Pexpect](#pexpect) has the most monthly downloads in this comparison, at 137.7M, a count that includes many non-SSH tasks.

## Capabilities

| Library | Asyncio SSH sessions | SFTP file API |
| --- | --- | --- |
| [Pexpect](#pexpect) | No | No |
| [Paramiko](#paramiko) | No | Yes |
| [AsyncSSH](#asyncssh) | Yes | Yes |
| [sshtunnel](#sshtunnel) | No | No |
| [Fabric](#fabric) | No | Yes |
| [Netmiko](#netmiko) | No | No |
| [ssh2-python](#sshtwo-python) | No | Yes |
| [ssh-python](#ssh-python) | No | Yes |

## Libraries

### Pexpect

[GitHub](https://github.com/pexpect/pexpect) · [PyPI](https://pypi.org/project/pexpect) · [Docs](https://pexpect.readthedocs.io/en/stable/api/pxssh.html)

Controls interactive console applications.

- Downloads / mo: 137.7M
- Stars: 2.9K
- Last release: 4.9.0
- License: ISC license
- Capabilities: [From the Pexpect docs](https://pexpect.readthedocs.io/en/stable/api/pxssh.html)

```sh
pip install pexpect
```

**home-assistant/core** (92.3K stars)

[home-assistant/core](https://github.com/home-assistant/core) 

```python
def _get_arp_data(self) -> str | None:
    """Open connection to the router and get arp entries."""

    try:
        cisco_ssh: pxssh.pxssh[str] = pxssh.pxssh(encoding="utf-8")
        cisco_ssh.login(
            self.host,
            self.username,
            self.password,
            port=self.port,
            auto_prompt_reset=False,
        )

        # Find the hostname
        initial_line = (cisco_ssh.before or "").splitlines()
        router_hostname = initial_line[len(initial_line) - 1]
        router_hostname += "#"
        # Set the discovered hostname as prompt
        cisco_ssh.PROMPT = f"(?i)^{router_hostname}"
        # Allow full arp table to print at once
        cisco_ssh.sendline("terminal length 0")
        cisco_ssh.prompt(1)

        cisco_ssh.sendline("show ip arp")
        cisco_ssh.prompt(1)

    except pxssh.ExceptionPxssh as px_e:
        _LOGGER.error("Failed to login via pxssh: %s", px_e)
        return None

    return cisco_ssh.before

```

[homeassistant/components/cisco_ios/device_tracker.py](https://github.com/home-assistant/core/blob/e94d23e5e9906a8bcb03f25f1dc75aeac2c27b68/homeassistant/components/cisco_ios/device_tracker.py#L104-L134) · [More projects using Pexpect →](https://dashboard.exa.ai/playground/search?q=pexpect%20GitHub%20projects)

**Quickstart**

```python
from pexpect import pxssh
s = pxssh.pxssh()
s.login(hostname, username, password)
s.sendline('uptime')   # run a command
s.prompt()             # match the prompt
print(s.before)        # print everything before the prompt.
s.logout()

```

From [pxssh.py](https://pexpect.readthedocs.io/en/stable/api/pxssh.html)

### Paramiko

[GitHub](https://github.com/paramiko/paramiko) · [PyPI](https://pypi.org/project/paramiko) · [Docs](https://docs.paramiko.org/en/stable/api/client.html)

Provides an SSH client for authentication, commands, and SFTP sessions.

- Downloads / mo: 111.1M
- Stars: 9.9K
- Last release: 5.1.0
- License: LGPL-2.1
- Capabilities: [From the Paramiko docs](https://docs.paramiko.org/en/stable/api/client.html)

**Strengths**

- **Runs remote SSH commands.** Execute a command and access its standard input, output and error streams.
- **Exposes an SFTP client.** Open an SFTP session over the established SSH connection.

**Watch out for**

- **Unknown hosts need trusted keys.** Load trusted host keys before connecting to a new SSH server.
- **Channel operations need explicit timeouts.** Set timeout to bound blocking channel reads and writes.

```sh
pip install paramiko
```

**fabric/fabric** (15.5K stars)

[fabric/fabric](https://github.com/fabric/fabric) 

```python
def get(self, remote, local=None, preserve_mode=True):
    """
    Copy a file from wrapped connection's host to the local filesystem.

    :param str remote:
        Remote file to download.

        May be absolute, or relative to the remote working directory.

        .. note::
            Most SFTP servers set the remote working directory to the
            connecting user's home directory, and (unlike most shells) do
            *not* expand tildes (``~``).

            For example, instead of saying ``get("~/tmp/archive.tgz")``,
            say ``get("tmp/archive.tgz")``.

    :param local:
        Local path to store downloaded file in, or a file-like object.

        **If None or another 'falsey'/empty value is given** (the default),
        the remote file is downloaded to the current working directory (as
        seen by `os.getcwd`) using its remote filename. (This is equivalent
        to giving ``"{basename}"``; see the below subsection on
        interpolation.)

        **If a string is given**, it should be a path to a local directory
        or file and is subject to similar behavior as that seen by common
        Unix utilities or OpenSSH's ``sftp`` or ``scp`` tools.

        For example, if the local path is a directory, the remote path's
        base filename will be added onto it (so ``get('foo/bar/file.txt',
        '/tmp/')`` would result in creation or overwriting of
        ``/tmp/file.txt``).

        This path will be **interpolated** with some useful parameters,
        using `str.format`:

        - The `.Connection` object's ``host``, ``user`` and ``port``
          attributes.
        - The ``basename`` and ``dirname`` of the ``remote`` path, as
          derived by `os.path` (specifically, its ``posixpath`` flavor, so
          that the resulting values are useful on remote POSIX-compatible
          SFTP servers even if the local client is Windows).
        - Thus, for example, ``"/some/path/{user}@{host}/{basename}"`` will
          yield different local paths depending on the properties of both
          the connection and the remote path.

        .. note::
            If nonexistent directories are present in this path (including
            the final path component, if it ends in `os.sep`) they will be
            created automatically using `os.makedirs`.

        **If a file-like object is given**, the contents of the remote file
        are simply written into it.

    :param bool preserve_mode:
        Whether to `os.chmod` the local file so it matches the remote
        file's mode (default: ``True``).

    :returns: A `.Result` object.

    .. versionadded:: 2.0
    .. versionchanged:: 2.6
        Added ``local`` path interpolation of connection & remote file
        attributes.
    .. versionchanged:: 2.6
        Create missing ``local`` directories automatically.
    """
    # TODO: how does this API change if we want to implement
    # remote-to-remote file transfer? (Is that even realistic?)
    # TODO: callback support
    # TODO: how best to allow changing the behavior/semantics of
    # remote/local (e.g. users might want 'safer' behavior that complains
    # instead of overwriting existing files) - this likely ties into the
    # "how to handle recursive/rsync" and "how to handle scp" questions

    # Massage remote path
    if not remote:
        raise ValueError("Remote path must not be empty!")
    orig_remote = remote
    remote = posixpath.join(
        self.sftp.getcwd() or self.sftp.normalize("."), remote
    )

    # Massage local path
    orig_local = local
    is_file_like = hasattr(local, "write") and callable(local.write)
    remote_filename = posixpath.basename(remote)
    if not local:
        local = remote_filename
    # Path-driven local downloads need interpolation, abspath'ing &
    # directory creation
    if not is_file_like:
        local = local.format(
            host=self.connection.host,
            user=self.connection.user,
            port=self.connection.port,
            dirname=posixpath.dirname(remote),
            basename=remote_filename,
        )
        # Must treat dir vs file paths differently, lest we erroneously
        # mkdir what was intended as a filename, and so that non-empty
        # dir-like paths still get remote filename tacked on.
        if local.endswith(os.sep):
            dir_path = local
            local = os.path.join(local, remote_filename)
        else:
            dir_path, _ = os.path.split(local)
        local = os.path.abspath(local)
        Path(dir_path).mkdir(parents=True, exist_ok=True)
        # TODO: reimplement mkdir (or otherwise write a testing function)
        # allowing us to track what was created so we can revert if
        # transfer fails.
        # TODO: Alternately, transfer to temp location and then move, but
        # that's basically inverse of v1's sudo-put which gets messy

    # Run Paramiko-level .get() (side-effects only. womp.)
    # TODO: push some of the path handling into Paramiko; it should be
    # responsible for dealing with path cleaning etc.
    # TODO: probably preserve warning message from v1 when overwriting
    # existing files. Use logging for that obviously.
    #
    # If local appears to be a file-like object, use sftp.getfo, not get
    if is_file_like:
        self.sftp.getfo(remotepath=remote, fl=local)
    else:
        self.sftp.get(remotepath=remote, localpath=local)
        # Set mode to same as remote end
        # TODO: Push this down into SFTPClient sometime (requires backwards
        # incompat release.)
        if preserve_mode:
            remote_mode = self.sftp.stat(remote).st_mode
            mode = stat.S_IMODE(remote_mode)
            os.chmod(local, mode)
    # Return something useful
    return Result(
        orig_remote=orig_remote,
        remote=remote,
        orig_local=orig_local,
        local=local,
        connection=self.connection,
    )

```

[fabric/transfer.py](https://github.com/fabric/fabric/blob/ded51893f02c33d2bc7c157624c44a039a952037/fabric/transfer.py#L43-L185) · [More projects using Paramiko →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20paramiko%20for%20SSH%20file%20transfers%2C%20remote%20worker%20startup%20and%20network%20configuration%20commands&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from paramiko.client import (
    AutoAddPolicy,
    MissingHostKeyPolicy,
    RejectPolicy,
    SSHClient,
    WarningPolicy,
)

client = SSHClient()
client.load_system_host_keys()
client.connect('ssh.example.com')
stdin, stdout, stderr = client.exec_command('ls -l')

```

From [__init__.py](https://docs.paramiko.org/en/stable/api/client.html)

### AsyncSSH

[GitHub](https://github.com/ronf/asyncssh) · [PyPI](https://pypi.org/project/asyncssh) · [Docs](https://asyncssh.readthedocs.io/en/latest/)

Implements asynchronous SSH clients and servers on asyncio.

- Downloads / mo: 16.3M
- Stars: 1.8K
- Last release: 2.24.1
- License: EPL-2.0 OR GPL-2.0-or-later
- Capabilities: [From the AsyncSSH docs](https://asyncssh.readthedocs.io/en/latest/)

**Strengths**

- **Fits asyncio applications.** Await SSH operations within an existing asyncio application.
- **Connects through existing SSH sessions.** Use a connection tunnel to reach hosts behind an SSH gateway.

**Watch out for**

- **Hardware keys need another package.** Install fido2 for compatible hardware security-key authentication.

```sh
pip install asyncssh
```

**dask/distributed** (1.7K stars)

[dask/distributed](https://github.com/dask/distributed) 

```python
async def start(self):
    try:
        import asyncssh  # import now to avoid adding to module startup time
    except ImportError:
        raise ImportError(
            "Dask's SSHCluster requires the `asyncssh` package to be installed. "
            "Please install it using pip or conda."
        )

    self.connection = await asyncssh.connect(self.address, **self.connect_options)

    result = await self.connection.run("uname")
    if result.exit_status == 0:
        set_env = f'env DASK_INTERNAL_INHERIT_CONFIG="{dask.config.serialize(dask.config.global_config)}"'
    else:
        result = await self.connection.run("cmd /c ver")
        if result.exit_status == 0:
            set_env = f"set DASK_INTERNAL_INHERIT_CONFIG={dask.config.serialize(dask.config.global_config)} &&"
        else:
            raise Exception(
                "Worker failed to set DASK_INTERNAL_INHERIT_CONFIG variable "
            )

    if not self.remote_python:
        self.remote_python = sys.executable

    cmd = " ".join(
        [
            set_env,
            self.remote_python,
            "-m",
            "distributed.cli.dask_spec",
            self.scheduler,
            "--spec",
            "'{}'".format(
                dumps(
                    {
                        i: {"cls": self.worker_class, "opts": {**self.kwargs}}
                        for i in range(self.n_workers)
                    }
                )
            ),
        ]
    )

    self.proc = await self.connection.create_process(cmd)

    # We watch stderr in order to get the address, then we return
    started_workers = 0
    while started_workers < self.n_workers:
        line = await self.proc.stderr.readline()
        if not line.strip():
            raise Exception("Worker failed to start")
        logger.info(line.strip())
        if "worker at" in line:
            started_workers += 1
    logger.debug("%s", line)
    await super().start()

```

[distributed/deploy/ssh.py](https://github.com/dask/distributed/blob/dc182bda54af488d029f2c40db0893d5f48e69d5/distributed/deploy/ssh.py#L97-L154) · [More projects using AsyncSSH →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20asyncssh%20for%20SSH%20file%20transfers%2C%20remote%20worker%20startup%20and%20network%20configuration%20commands&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import asyncio, asyncssh, sys

async def run_client():
    async with asyncssh.connect('localhost') as conn:
        result = await conn.run('echo "Hello!"', check=True)
        print(result.stdout, end='')

try:
    asyncio.run(run_client())
except (OSError, asyncssh.Error) as exc:
    sys.exit('SSH connection failed: ' + str(exc))

```

From [latest.md](https://asyncssh.readthedocs.io/en/latest/)

### sshtunnel

[GitHub](https://github.com/pahaz/sshtunnel) · [PyPI](https://pypi.org/project/sshtunnel) · [Docs](https://sshtunnel.readthedocs.io/en/latest/)

Opens SSH tunnels in pure Python.

- Downloads / mo: 14.7M
- Stars: 1.3K
- Last release: 0.5.1
- License: MIT
- Capabilities: [From the sshtunnel docs](https://sshtunnel.readthedocs.io/en/latest/)

```sh
pip install sshtunnel
```

**dbcli/pgcli** (13.5K stars)

[dbcli/pgcli](https://github.com/dbcli/pgcli) 

```python
def connect(self, database="", host="", user="", port="", passwd="", dsn="", **kwargs):
    # Connect to the database.

    if not user:
        user = getuser()

    if not database:
        database = user

    kwargs.setdefault("application_name", self.application_name)

    # The resolved value is passed as a connection parameter rather than
    # merged into the dsn, leaving the user's connection string untouched.
    timeout = get_connect_timeout(self.connect_timeout, dsn, kwargs, self.default_connect_timeout)
    if timeout is not None:
        kwargs["connect_timeout"] = str(timeout)

    # If password prompt is not forced but no password is provided, try
    # getting it from environment variable.
    if not self.force_passwd_prompt and not passwd:
        if dsn:
            # Check if DSN contains a password - if so, don't use PGPASSWORD
            parsed_dsn = conninfo_to_dict(dsn)
            if "password" not in parsed_dsn:
                passwd = os.environ.get("PGPASSWORD", "")
        else:
            passwd = os.environ.get("PGPASSWORD", "")

    # Prompt for a password immediately if requested via the -W flag. This
    # avoids wasting time trying to connect to the database and catching a
    # no-password exception.
    # If we successfully parsed a password from a URI, there's no need to
    # prompt for it, even with the -W flag
    if self.force_passwd_prompt and not passwd:
        passwd = click.prompt("Password for %s" % user, hide_input=True, show_default=False, type=str)

    key = f"{user}@{host}@{port}"

    if not passwd and auth.keyring:
        passwd = auth.keyring_get_password(key)

    def should_ask_for_password(exc):
        # Prompt for a password after 1st attempt to connect
        # fails. Don't prompt if the -w flag is supplied
        if self.never_passwd_prompt:
            return False
        error_msg = exc.args[0]
        if "no password supplied" in error_msg:
            return True
        if "password authentication failed" in error_msg:
            return True
        return False

    if dsn:
        parsed_dsn = conninfo_to_dict(dsn)
        if "host" in parsed_dsn:
            host = parsed_dsn["host"]
        if "port" in parsed_dsn:
            port = parsed_dsn["port"]

    if self.dsn_alias and self.dsn_ssh_tunnel_config and not self.ssh_tunnel_url:
        for dsn_regex, tunnel_url in self.dsn_ssh_tunnel_config.items():
            if re.search(dsn_regex, self.dsn_alias):
                self.ssh_tunnel_url = tunnel_url
                break

    if self.ssh_tunnel_config and not self.ssh_tunnel_url:
        for db_host_regex, tunnel_url in self.ssh_tunnel_config.items():
            if re.search(db_host_regex, host):
                self.ssh_tunnel_url = tunnel_url
                break

    if self.ssh_tunnel_url:
        # We add the protocol as urlparse doesn't find it by itself
        if "://" not in self.ssh_tunnel_url:
            self.ssh_tunnel_url = f"ssh://{self.ssh_tunnel_url}"

        tunnel_info = urlparse(self.ssh_tunnel_url)
        params = {
            "local_bind_address": ("127.0.0.1",),
            "remote_bind_address": (host, int(port or 5432)),
            "ssh_address_or_host": (tunnel_info.hostname, tunnel_info.port or 22),
            "logger": self.logger,
        }
        if tunnel_info.username:
            params["ssh_username"] = tunnel_info.username
        if tunnel_info.password:
            params["ssh_password"] = tunnel_info.password

        # Hack: sshtunnel adds a console handler to the logger, so we revert handlers.
        # We can remove this when https://github.com/pahaz/sshtunnel/pull/250 is merged.
        logger_handlers = self.logger.handlers.copy()
        try:
            self.ssh_tunnel = sshtunnel.SSHTunnelForwarder(**params)
            self.ssh_tunnel.start()
        except Exception as e:
            self.logger.handlers = logger_handlers
            self.logger.error("traceback: %r", traceback.format_exc())
            click.secho(str(e), err=True, fg="red")
            sys.exit(1)
        self.logger.handlers = logger_handlers

        atexit.register(self.ssh_tunnel.stop)
        # Preserve original host for .pgpass lookup and SSL certificate verification.
        # Use hostaddr to specify the actual connection endpoint (SSH tunnel).
        hostaddr = "127.0.0.1"
        port = self.ssh_tunnel.local_bind_ports[0]

        if dsn:
            dsn = make_conninfo(dsn, host=host, hostaddr=hostaddr, port=port)
        else:
            kwargs["hostaddr"] = hostaddr

    # Attempt to connect to the database.
    # Note that passwd may be empty on the first attempt. If connection
    # fails because of a missing or incorrect password, but we're allowed to
    # prompt for a password (no -w flag), prompt for a passwd and try again.
    try:
        try:
            pgexecute = PGExecute(
                database,
                user,
                passwd,
                host,
                port,
                dsn,
                notify_callback,
                **kwargs,
            )
        except (OperationalError, InterfaceError) as e:
            if should_ask_for_password(e):
                passwd = click.prompt(
                    "Password for %s" % user,
                    hide_input=True,
                    show_default=False,
                    type=str,
                )
                pgexecute = PGExecute(
                    database,
                    user,
                    passwd,
                    host,
                    port,
                    dsn,
                    notify_callback,
                    **kwargs,
                )
            else:
                raise e
        if passwd and auth.keyring:
            auth.keyring_set_password(key, passwd)

    except Exception as e:  # Connecting to a database could fail.
        self.logger.debug("Database connection failed: %r.", e)
        self.logger.error("traceback: %r", traceback.format_exc())
        click.secho(str(e), err=True, fg="red")
        sys.exit(1)

    self.pgexecute = pgexecute
    self.service_name = None

```

[pgcli/main.py](https://github.com/dbcli/pgcli/blob/dc9ce9447e0fc005a347b75b7eb5d541e282b1c1/pgcli/main.py#L749-L908) · [More projects using sshtunnel →](https://dashboard.exa.ai/playground/search?q=sshtunnel%20GitHub%20projects)

**Quickstart**

```python
from sshtunnel import SSHTunnelForwarder

server = SSHTunnelForwarder(
    'alfa.8iq.dev',
    ssh_username="pahaz",
    ssh_password="secret",
    remote_bind_address=('127.0.0.1', 8080)
)

server.start()

print(server.local_bind_port)  # show assigned local port
# work with `SECRET SERVICE` through `server.local_bind_port`.

server.stop()

```

From [README.rst](https://api.github.com/repos/pahaz/sshtunnel/contents/README.rst)

### Fabric

[GitHub](https://github.com/fabric/fabric) · [PyPI](https://pypi.org/project/fabric) · [Docs](https://docs.fabfile.org/en/latest/getting-started.html)

Runs shell commands remotely over SSH.

- Downloads / mo: 7.9M
- Stars: 15.5K
- Last release: 3.2.3
- License: BSD-2-Clause
- Capabilities: [From the Fabric docs](https://docs.fabfile.org/en/latest/getting-started.html)

**Strengths**

- **Captures remote command results.** Inspect captured output, exit status, and success through the returned result.
- **Includes SSH gateway configuration.** Use ProxyJump-style connections or ProxyCommand-style gateways.

**Watch out for**

- **Connections need explicit cleanup.** Close connections or use a context manager to avoid shutdown hangs.

```sh
pip install fabric
```

**Quickstart**

```python
from fabric import Connection
c = Connection('web1')
result = c.run('uname -s')

```

From [getting-started.html](https://docs.fabfile.org/en/latest/getting-started.html) · [Find projects using Fabric →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20fabric%20for%20SSH%20file%20transfers%2C%20remote%20worker%20startup%20and%20network%20configuration%20commands&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

### Netmiko

[GitHub](https://github.com/ktbyers/netmiko) · [PyPI](https://pypi.org/project/netmiko) · [Docs](https://ktbyers.github.io/netmiko/docs/netmiko/base_connection.html)

Simplifies command-line connections to network devices from multiple vendors.

- Downloads / mo: 967.5K
- Stars: 4.3K
- Last release: 4.8.0
- License: MIT
- Capabilities: [From the Netmiko docs](https://ktbyers.github.io/netmiko/docs/netmiko/base_connection.html)

**Strengths**

- **Targets network-device command lines.** Select a device driver suited to the target network platform.
- **Sends network configuration commands.** Apply a list of configuration commands through send_config_set.

**Watch out for**

- **Device profiles must match hardware.** Set device_type to a supported platform before connecting.

```sh
pip install netmiko
```

**napalm-automation/napalm** (2.5K stars)

[napalm-automation/napalm](https://github.com/napalm-automation/napalm) 

```python
@_file_prompt_quiet
def _commit_handler(self, cmd):
    """
    Special handler for hostname change on commit operation. Also handles username removal
    which prompts for confirmation (username removal prompts for each user...)
    """
    current_prompt = self.device.find_prompt().strip()
    terminating_char = current_prompt[-1]
    # Look for trailing pattern that includes '#' and '>'
    pattern1 = r"[>#{}]\s*$".format(terminating_char)
    # Handle special username removal pattern
    pattern2 = r".*all username.*confirm"
    patterns = rf"(?:{pattern1}|{pattern2})"
    output = self.device.send_command(cmd, expect_string=patterns, read_timeout=90)
    loop_count = 50
    new_output = output
    for _ in range(loop_count):
        if re.search(pattern2, new_output):
            # Send confirmation if username removal
            new_output = self.device.send_command_timing(
                "\n", strip_prompt=False, strip_command=False
            )
            output += new_output
        else:
            break
    # Reset base prompt in case hostname changed
    self.device.set_base_prompt()
    return output

```

[napalm/ios/ios.py](https://github.com/napalm-automation/napalm/blob/820a06b2069eb1d7b0cbe8943ee2dea6e2949d1a/napalm/ios/ios.py#L463-L490) · [More projects using Netmiko →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20netmiko%20for%20SSH%20file%20transfers%2C%20remote%20worker%20startup%20and%20network%20configuration%20commands&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from netmiko import ConnectHandler
from getpass import getpass

cisco1 = {
    "device_type": "cisco_ios",
    "host": "cisco1.lasthop.io",
    "username": "pyclass",
    "password": getpass(),
}

net_connect = ConnectHandler(**cisco1)
print(net_connect.find_prompt())
net_connect.disconnect()

```

From [EXAMPLES.md](https://api.github.com/repos/ktbyers/netmiko/contents/EXAMPLES.md)

### ssh2-python

[GitHub](https://github.com/ParallelSSH/ssh2-python) · [PyPI](https://pypi.org/project/ssh2-python) · [Docs](https://ssh2-python.readthedocs.io/en/latest/session.html)

Binds the libssh2 C library.

- Downloads / mo: 297.4K
- Stars: 237
- Last release: 1.2.0.post1
- License: LGPL-2.1-only
- Capabilities: [From the ssh2-python docs](https://ssh2-python.readthedocs.io/en/latest/session.html)

```sh
pip install ssh2-python
```

**ParallelSSH/parallel-ssh** (1.3K stars)

[ParallelSSH/parallel-ssh](https://github.com/ParallelSSH/parallel-ssh) 

```python
def _init_session(self, retries=1):
    self.session = Session()
    if self.compress:
        self.session.flag(LIBSSH2_FLAG_COMPRESS)

    if self.timeout:
        # libssh2 timeout is in ms
        self.session.set_timeout(self.timeout * 1000)
    try:
        if self._auth_thread_pool:
            THREAD_POOL.apply(self.session.handshake, (self.sock,))
        else:
            self.session.handshake(self.sock)
    except Exception as ex:
        if retries < self.num_retries:
            sleep(self.retry_delay)
            return self._connect_init_session_retry(retries=retries+1)
        msg = "Error connecting to host %s:%s - %s"
        logger.error(msg, self.host, self.port, ex)
        if not self.sock.closed:
            try:
                self.sock.shutdown(SHUT_RDWR)
                self.sock.detach()
            except Exception:
                pass
        if isinstance(ex, SSH2Timeout):
            raise Timeout(msg, self.host, self.port, ex)
        raise

```

[pssh/clients/native/single.py](https://github.com/ParallelSSH/parallel-ssh/blob/97a7414236b1186a8b86816a3f981203941fd2f1/pssh/clients/native/single.py#L284-L311) · [More projects using ssh2-python →](https://dashboard.exa.ai/playground/search?q=ssh2-python%20GitHub%20projects)

**Quickstart**

```python
import os
import socket
from ssh2.session import Session
host = 'localhost'
user = os.getlogin()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 22))
session = Session()
session.handshake(sock)
session.agent_auth(user)
channel = session.open_session()
channel.execute('echo me')

```

From [example_echo.py](https://api.github.com/repos/ParallelSSH/ssh2-python/contents/examples/example_echo.py)

### ssh-python

[GitHub](https://github.com/ParallelSSH/ssh-python) · [PyPI](https://pypi.org/project/ssh-python) · [Docs](https://ssh-python.readthedocs.io/en/latest/session.html)

Binds the libssh C library to Python.

- Downloads / mo: 237.5K
- Stars: 48
- Last release: 1.2.0.post1
- License: LGPL-2.1-only
- Capabilities: [From the ssh-python docs](https://ssh-python.readthedocs.io/en/latest/session.html)

```sh
pip install ssh-python
```

**ParallelSSH/parallel-ssh** (1.3K stars)

[ParallelSSH/parallel-ssh](https://github.com/ParallelSSH/parallel-ssh) 

```python
def _init_session(self, retries=1):
    logger.debug("Starting new session for %s@%s:%s",
                 self.user, self.host, self.port)
    self.session = Session()
    self.session.options_set(options.USER, self.user)
    self.session.options_set(options.HOST, self.host)
    if self.compress:
        self.session.options_set(options.COMPRESSION, "yes")
    self.session.options_set_port(self.port)
    if self.gssapi_server_identity:
        self.session.options_set(
            options.GSSAPI_SERVER_IDENTITY, self.gssapi_server_identity)
    if self.gssapi_client_identity:
        self.session.options_set(
            options.GSSAPI_CLIENT_IDENTITY, self.gssapi_client_identity)
    if self.gssapi_client_identity or self.gssapi_server_identity:
        self.session.options_set_gssapi_delegate_credentials(
            self.gssapi_delegate_credentials)
    logger.debug("Session started, connecting with existing socket")
    try:
        self.session.set_socket(self.sock)
        self._session_connect()
    except Exception as ex:
        if retries < self.num_retries:
            return self._connect_init_session_retry(retries=retries+1)
        msg = "Error connecting to host %s:%s - %s"
        logger.error(msg, self.host, self.port, ex)
        raise ex

```

[pssh/clients/ssh/single.py](https://github.com/ParallelSSH/parallel-ssh/blob/97a7414236b1186a8b86816a3f981203941fd2f1/pssh/clients/ssh/single.py#L153-L180) · [More projects using ssh-python →](https://dashboard.exa.ai/playground/search?q=ssh-python%20GitHub%20projects)

**Quickstart**

```python
import socket

from ssh.session import Session
from ssh import options

USERNAME = 'your-user'
HOST = 'localhost'
PORT = 22

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))

s = Session()
s.options_set(options.HOST, HOST)
s.options_set(options.USER, USERNAME)
s.options_set_port(PORT)
s.set_socket(sock)
s.connect()

# Authenticate with agent
s.userauth_agent(USERNAME)

chan = s.channel_new()
chan.open_session()
chan.request_exec('echo me')
size, data = chan.read()
while size > 0:
    print(data.strip())
    size, data = chan.read()
chan.close()

```

From [exec.py](https://api.github.com/repos/ParallelSSH/ssh-python/contents/examples/exec.py)

## FAQ

### Which Python SSH library should I use?

[Paramiko](#paramiko) suits most scripts, with native Python SSH and SFTP clients. [AsyncSSH](#asyncssh) suits asyncio code. [Fabric](#fabric) suits remote commands and file transfers across hosts. [Netmiko](#netmiko) suits CLI sessions on network devices.

### What is Paramiko?

[Paramiko](#paramiko) implements the SSH protocol in Python, with SSH and SFTP client and server building blocks. Fabric and sshtunnel build on it.

### What is Netmiko?

[Netmiko](#netmiko) is a multi-vendor library for CLI connections to network devices, with prompt handling and platform-specific commands.

### What is Pexpect?

[Pexpect](#pexpect) controls interactive console applications. Its pxssh module drives the system SSH client through a terminal session.

### Paramiko vs AsyncSSH: which fits asyncio code?

[AsyncSSH](#asyncssh) implements its client and server on the asyncio framework. [Paramiko](#paramiko) uses blocking channel reads and writes.

### Why does Paramiko reject a previously unseen host?

Its default missing-host-key policy rejects an unknown key. Load the trusted host keys before connecting.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python SSH libraries Paramiko AsyncSSH Fabric Netmiko SFTP asyncio jump host automation code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
