Ansible Pylibssh

1.4.0 · active · verified Wed Apr 15

Ansible Pylibssh provides Python bindings for the `libssh` client library, specifically designed for Ansible's SSH connection needs. It offers a low-level interface to SSH functionalities. The library is actively maintained with regular stable releases, with the current version being 1.4.0, which was released in March 2026.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SSH session, execute a simple command, and then properly disconnect. It uses environment variables for host, user, and password for security and flexibility. Ensure the `libssh` C library is installed on your system and replace `SSH_HOST` and `SSH_USER` with valid credentials if not using a passwordless setup.

import os
from pylibsshext.errors import LibsshSessionException
from pylibsshext.session import Session

HOST = os.environ.get('SSH_HOST', 'localhost')
USER = os.environ.get('SSH_USER', 'testuser')
PASSWORD = os.environ.get('SSH_PASSWORD', '')
# Use a placeholder if not set, but real connections need a password or key

if not PASSWORD:
    print("Warning: SSH_PASSWORD environment variable not set. Connection might fail if password authentication is required.")

TIMEOUT = 30
PORT = 22

ssh = Session()
try:
    ssh.connect(
        host=HOST,
        user=USER,
        password=PASSWORD,
        timeout=TIMEOUT,
        port=PORT,
    )
    print(f'Successfully connected to {HOST}:{PORT}.')
    # Example: Execute a command
    channel = ssh.open_session()
    channel.request_exec('echo Hello from pylibssh!')
    output = channel.read_stdout(2048).decode()
    print(f'Command output: {output.strip()}')
    channel.close()
    channel.send_eof()

except LibsshSessionException as ssh_exc:
    print(f'Failed to connect to {HOST}:{PORT} over SSH: {ssh_exc!s}')
except Exception as e:
    print(f'An unexpected error occurred: {e}')
finally:
    if ssh.is_connected:
        ssh.disconnect()
        print(f'Disconnected from {HOST}.')

view raw JSON →