ssh-python Library

1.2.0.post1 · active · verified Fri Apr 17

ssh-python provides robust Python bindings for the `libssh` C library, enabling programmatic interaction with SSH servers. It offers functionalities for connecting, authenticating, executing commands, and managing SSH channels. The library is actively maintained, with version 1.2.0.post1 being the latest stable release, typically releasing minor updates every few months with periodic patch versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SSH connection, authenticate with a password (using environment variables for safety), execute a simple command, capture its output, and properly close the session. It also includes basic error handling for common SSH exceptions. Replace `SSH_HOST`, `SSH_USER`, and `SSH_PASSWORD` with your actual server details.

import ssh
import os

try:
    # Initialize an SSH session
    session = ssh.Session()
    
    # Set connection options
    session.options_set(ssh.SSH_OPTIONS_HOST, os.environ.get('SSH_HOST', 'localhost'))
    session.options_set(ssh.SSH_OPTIONS_PORT, int(os.environ.get('SSH_PORT', 22)))

    # Connect to the SSH server
    session.connect()
    print(f"Connected to {session.options_get(ssh.SSH_OPTIONS_HOST)}:{session.options_get_int(ssh.SSH_OPTIONS_PORT)}")

    # Authenticate using password
    username = os.environ.get('SSH_USER', 'guest')
    password = os.environ.get('SSH_PASSWORD', 'guestpass') # DO NOT hardcode passwords in production

    if session.userauth_password(username, password) != ssh.SSH_AUTH_SUCCESS:
        raise ssh.AuthError("Authentication failed")
    print(f"Authenticated as {username}")

    # Open a channel for executing commands
    channel = session.channel_session()
    channel.open_session()
    
    # Execute a command
    command = "echo Hello from ssh-python!"
    print(f"Executing command: '{command}'")
    channel.request_exec(command)
    
    # Read output
    stdout = channel.read_stdout(2048)
    stderr = channel.read_stderr(2048)
    exit_status = channel.get_exit_status()

    print(f"--- STDOUT ---\n{stdout.decode().strip()}")
    print(f"--- STDERR ---\n{stderr.decode().strip()}")
    print(f"Exit Status: {exit_status}")

    # Close the channel and session
    channel.close()
    print("Channel closed.")
    session.disconnect()
    print("Session disconnected.")

except ssh.AuthError as e:
    print(f"Authentication Error: {e}")
except ssh.SSHException as e:
    print(f"SSH Connection Error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

view raw JSON →