ssh2-python

1.2.0.post1 · active · verified Thu Apr 16

ssh2-python provides Python bindings for the `libssh2` C library, offering a low-level, high-performance interface for SSHv2 protocol operations. It is currently at version 1.2.0.post1 and is actively maintained with regular releases that include updates to embedded libraries like `libssh2` and OpenSSL, and support for newer Python versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SSH connection, authenticate with a username and password, execute a remote command, read its output, and gracefully close the connection. Ensure `SSH_HOST`, `SSH_PORT`, `SSH_USERNAME`, and `SSH_PASSWORD` environment variables are set for actual use.

import socket
import os
from ssh2.session import Session

HOST = os.environ.get('SSH_HOST', 'localhost')
PORT = int(os.environ.get('SSH_PORT', '22'))
USERNAME = os.environ.get('SSH_USERNAME', 'user')
PASSWORD = os.environ.get('SSH_PASSWORD', 'password')

try:
    # 1. Create a socket and connect
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))

    # 2. Initialize an SSH2 session
    session = Session()
    session.handshake(sock)

    # 3. Authenticate with password
    session.userauth_password(USERNAME, PASSWORD)

    # 4. Check if authenticated
    if not session.is_userauth_authenticated():
        print("Authentication failed!")
        exit(1)

    print(f"Successfully authenticated to {HOST} as {USERNAME}")

    # 5. Open a channel and execute a command
    channel = session.open_session()
    channel.execute('echo Hello from ssh2-python; uname -a')

    # 6. Read output
    size, data = channel.read()
    while size > 0:
        print(data.decode('utf-8').strip())
        size, data = channel.read()

    # 7. Get exit status
    print(f"Command exit status: {channel.get_exit_status()}")

    # 8. Close the channel and session
    channel.close()
    session.disconnect()
    sock.close()

except exceptions.SSH2Error as e:
    print(f"SSH2 Error: {e}")
except socket.error as e:
    print(f"Socket Error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →