Skip to content

ParamikoInteractiveSSH

Dennis Lee edited this page May 27, 2026 · 1 revision

title: Paramiko Interactive SSH Automation type: technique created: 2026-05-26 last_updated: 2026-05-26 related: [] sources: ["https://joelinoff.com/blog/?p=905"]

Paramiko Interactive SSH Automation

Python pattern for automating interactive SSH sessions that require arbitrary input — password prompts, confirmation dialogs, or interactive shells — using paramiko's invoke_shell() rather than the simpler exec_command().

When This Applies

Paramiko's exec_command() works for non-interactive commands that run and exit cleanly. It fails when the remote process expects input during execution: a legacy device that prompts for confirmation, a configuration tool with an interactive menu, or a script that calls getpass. For these cases, invoke_shell() opens a persistent shell session that can send and receive data iteratively.

The Pattern

import paramiko
import time

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=user, password=password)

shell = client.invoke_shell()
time.sleep(1)  # wait for shell to initialise

shell.send("some-interactive-command\n")
time.sleep(0.5)  # wait for prompt

output = shell.recv(4096).decode()
if "confirm?" in output:
    shell.send("yes\n")
    time.sleep(0.5)
    output += shell.recv(4096).decode()

client.close()

The key characteristics: invoke_shell() instead of exec_command(), explicit time.sleep() calls to wait for prompts, and iterative recv() calls to read output in chunks.

Limitations

  • Timing-based waits are fragile — slow connections or loaded hosts can miss prompts
  • Output parsing is brittle compared to structured alternatives
  • Not suitable for long-running or high-reliability automation

When to Use Instead

  • Ansible — for standard server automation; handles SSH, retries, and idempotency cleanly
  • subprocess + ssh binary — for simple non-interactive remote commands from Python
  • Paramiko exec_command — for non-interactive remote commands where you don't need shell features

The invoke_shell() pattern is appropriate specifically when automating interactive SSH sessions from Python and no higher-level alternative covers the target system.

Clone this wiki locally