Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
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
Pexpect has the most monthly downloads in this comparison, at 137.7M, a count that includes many non-SSH tasks.
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()
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,
)
AsyncSSH
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
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.
Limitations
Hardware keys need another package.Install fido2 for compatible hardware security-key authentication.
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()
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()
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
Fabric
Runs shell commands remotely over SSH.
Downloads / mo
7.9M
Stars
15.5K
Last release
3.2.3
License
BSD-2-Clause
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.
Limitations
Connections need explicit cleanup.Close connections or use a context manager to avoid shutdown hangs.