paramiko-expect

0.3.5 · active · verified Wed Apr 15

paramiko-expect is an expect-like extension for the Paramiko SSH library, enabling scripts to interact with remote hosts via a true SSH connection in an interactive, automated fashion. It's particularly useful for automating interactions with command-line applications, shell scripts, or network devices that require 'expect'-style responses to prompts. The current version is 0.3.5, and releases are infrequent, with the last update in late 2022.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to establish an SSH connection using Paramiko, then wrap the SSHClient object with SSHClientInteraction to send commands and expect specific prompts. It prints the cleaned output of each command.

import paramiko
import os
from paramiko_expect import SSHClientInteraction

HOSTNAME = os.environ.get('SSH_HOSTNAME', 'localhost')
USERNAME = os.environ.get('SSH_USERNAME', 'testuser')
PASSWORD = os.environ.get('SSH_PASSWORD', 'testpass')
PROMPT = r'.*\$ ' # Example prompt for a Linux shell ending with $ or #

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:
    client.connect(hostname=HOSTNAME, username=USERNAME, password=PASSWORD, timeout=10)
    print(f"SSH connection established to {HOSTNAME}")

    with SSHClientInteraction(client, timeout=10, display=True) as interact:
        # Wait for the initial prompt after connection
        interact.expect(PROMPT)
        print(f"Initial prompt: {interact.last_match}")

        # Send a command and wait for the prompt again
        interact.send('uname -a')
        interact.expect(PROMPT)
        print(f"Uname output:\n{interact.current_output_clean}")

        # Send another command
        interact.send('echo Hello paramiko-expect!')
        interact.expect(PROMPT)
        print(f"Echo output:\n{interact.current_output_clean}")

finally:
    client.close()
    print("SSH connection closed.")

view raw JSON →