Quickstart

This guide will walk you through the basics of how to create SSH connections, with and/or without tunnels, and open SFTP sessions.

Connection Methods

In order to establish a SSH connection to a remote host, user’s can use one of the following 3 methods:

  1. Direct Connection

  2. Decorated Connection

  3. Context Connection

See also

For a full reference on the available configuration properties, see the ssh2.config.SSHConfigData.

Direct Connection

A direct connection, instantiates a new ssh2.SSH, by invoking the ssh2.SSH directly.

"""
Examples for ssh2.SSH

The following examples, create a new :class:`ssh2.SSH`, executes the command
and returns a 2-tuple with the STDOUT and exit status code.
"""

from ssh2 import SSH, SSHConfigData, SSHConnectionError


HOSTNAME = "example.com"
USERNAME = "user"
PASSWORD = "password"


def ssh_ex1():
    """
    SSH example using :class:`ssh2.SSH` with SSH configuration 
    file (:code:`~/.ssh/config`).
    """
    try:
        ssh = SSH()
        configs = SSHConfigData(hostname=HOSTNAME)
        ssh.connect(configs)
        return ssh.execute("ls -l")
    except SSHConnectionError as err:
        print(f"SSH error: {err}")


def ssh_ex2():
    """
    SSH example using :class:`ssh2.SSH` with manual SSH configuration
    arguments.
    """
    try:
        ssh = SSH()
        configs = SSHConfigData(
            hostname=HOSTNAME,
            username=USERNAME,
            password=PASSWORD, 
            use_ssh_config=False
        )
        ssh.connect(configs)
        return ssh.execute("ls -l")
    except SSHConnectionError as err:
        print(f"SSH error: {err}")


if __name__ == "__main__":
    ssh_ex1()
    ssh_ex2()

Decorated Connection

A decorated connection, instantiates a new ssh2.SSH, by invoking the ssh2.core.SSHConnect object. Invocation of this object will automatically include the ssh2.SSH object into the decorated function.

For examples, please see SSHConnect

"""
Examples for ssh2.SSHConnect

The following examples, create a new :class:`ssh2.SSH`, executes the command
and returns a 2-tuple with the STDOUT and exit status code.
"""

from ssh2 import SSH, SSHConnect


HOSTNAME = "example.com"
USERNAME = "user"
PASSWORD = "password"
CONFIGS  = {
    "hostname": HOSTNAME,
    "username": USERNAME,
    "password": PASSWORD,
    "use_ssh_config": False
}


@SSHConnect(hostname=HOSTNAME)
def sshconnect_ex1(ssh: SSH):
    """
    SSH example using :class:`ssh2.SSHConnect` with SSH configuration 
    file (:code:`~/.ssh/config`).
    """
    return ssh.execute("ls -l")


@SSHConnect(**CONFIGS)
def sshconnect_ex2(ssh: SSH):
    """
    SSH example using :class:`ssh2.SSHConnect` with manual configuration
    arguments.
    """
    return ssh.execute("ls -l")


if __name__ == "__main__":
    sshconnect_ex1()
    sshconnect_ex2()

Context Connection

A context connection, instantiates a new ssh2.SSH, by invoking the ssh2.core.SSHContext object.

"""
Examples for ssh2.SSHContext

The following examples, create a new :class:`ssh2.SSH`, executes the command
and returns a 2-tuple with the STDOUT and exit status code.
"""

from ssh2 import SSH, SSHContext


HOSTNAME = "example.com"
USERNAME = "user"
KEY_FILENAME = ["~/.ssh.id_rsa.user"]
CONFIGS  = {
    "hostname": HOSTNAME,
    "username": USERNAME,
    "key_filename": KEY_FILENAME,
    "use_ssh_config": False
}


def sshcontext_ex1():
    """
    SSHContext example using SSH configuration file (~/.ssh/config).
    """
    with SSHContext(hostname=HOSTNAME) as ssh:
        return ssh.execute("ls -l")


def sshcontext_ex2():
    """
    SSHContext example using manual configurations.
    """
    with SSHContext(**CONFIGS) as ssh:
        return ssh.execute("ls -l")


if __name__ == "__main__":
    sshcontext_ex1()
    sshcontext_ex2()

Also, available within the context connection, is the ssh2.core.SSHTunnelContext. Similarly, to the ssh2.core.SSHContext, this instantiates a new ssh2.SSH, but through a tunnel connection using a jumphost. It’s recommended to configure the ProxyCommand directive within your SSH configuration file, however, this provides the same functionality.

"""
Examples for ssh2.SSHTunnelContext.

The following examples, create a new :class:`ssh2.SSH` (via tunnel), 
executes the command and returns a 2-tuple with the STDOUT and exit 
status code.
"""

from ssh2 import SSHTunnelContext, SSHConfigData


HOSTNAME = "host1.example.com"
USERNAME = "jsmith"
KEY_FILENAME = ["~/.ssh/id_rsa.host1"]
CONFIGS  = {
    "hostname": HOSTNAME,
    "username": USERNAME,
    "key_filename": KEY_FILENAME,
    "use_ssh_config": False
}

JUMP_HOSTNAME = "jump1.example.com"
JUMP_USERNAME = "jsmith"
JUMP_PASSWORD = "p@ssw0rd"
JUMP_CONFIGS  = {
    "hostname": JUMP_HOSTNAME,
    "username": JUMP_USERNAME,
    "password": JUMP_PASSWORD,
    "use_ssh_config": False
}


def sshtunnelcontext_ex1():
    """
    SSH Tunnel example using :class:`ssh2.SSHTunnelContext` with SSH 
    configuration file (:code:`~/.ssh/config`).
    """
    with SSHTunnelContext(
        SSHConfigData(hostname=JUMP_HOSTNAME),
        SSHConfigData(hostname=HOSTNAME)) as ssh:
        return ssh.execute("ls -l")


def sshtunnelcontext_ex2():
    """
    SSH Tunnel example using :class:`ssh2.SSHTunnelContext` with manual
    configuration arguments.
    """
    with SSHTunnelContext(
        SSHConfigData(**JUMP_CONFIGS),
        SSHConfigData(**CONFIGS)) as ssh:
        return ssh.execute("ls -l")


if __name__ == "__main__":
    sshtunnelcontext_ex1()
    sshtunnelcontext_ex2()

SFTP Connection

To initiate an SFTP session, create a new ssh2.SSH, the open the SFTP session with ssh2.SSH.open_sftp.

"""
Examples for ssh2.SSH (SFTP)

The following examples, create a new :class:`ssh2.SSH`, opens an SFTP session
and returns the output.
"""

from ssh2 import SSH, SSHConfigData, SSHConnect, SSHContext


HOSTNAME = "example.com"


def sftp_ex1():
    """
    SSH example using :class:`ssh2.SSH` with SSH configuration 
    file (:code:`~/.ssh/config`).
    """
    ssh = SSH()
    configs = SSHConfigData(hostname=HOSTNAME)
    ssh.connect(configs)
    sftp = ssh.open_sftp()
    return sftp.listdir()


@SSHConnect(hostname=HOSTNAME)
def sftp_ex2(ssh: SSH):
    """
    SFTP example using :class:`ssh2.SSHConnect` with SSH configuration 
    file (:code:`~/.ssh/config`).
    """
    sftp = ssh.open_sftp()
    return sftp.listdir()


def sftp_ex3():
    """
    SFTP example using :class:`ssh2.SSHContext` with SSH configuration 
    file (:code:`~/.ssh/config`).
    """
    with SSHContext(hostname=HOSTNAME) as ssh:
        sftp = ssh.open_sftp()
        return sftp.listdir()


if __name__ == "__main__":
    sftp_ex1()
    sftp_ex2()
    sftp_ex3()