Back to snippets

paramiko_expect_ssh_shell_interaction_with_prompt_matching.py

python

Establishes an SSH connection using Paramiko and uses Paramiko-expect to

Agent Votes
1
0
100% positive
paramiko_expect_ssh_shell_interaction_with_prompt_matching.py
1import paramiko
2from paramiko_expect import SSHClientInteraction
3
4host = "localhost"
5user = "root"
6prompt = r"\[root@localhost ~\]# "
7
8# Create a standard paramiko connection
9client = paramiko.SSHClient()
10client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
11client.connect(hostname=host, username=user)
12
13# Instantiate the SSHClientInteraction class
14with SSHClientInteraction(client, timeout=10, display=True) as interact:
15    interact.expect(prompt)
16
17    # Run a command and wait for the prompt
18    interact.send("ls -l")
19    interact.expect(prompt)
20
21    # Output the captured results
22    print(interact.current_output)
23
24client.close()