Ben Higginbotham
Ben Higginbotham

Reputation: 3

paramiko expect timing out

Thinking about making a move from Perl to Python running scripts to automate certain tasks on remote servers and devices. We need to be able to use Expect to check for certain results and get the data back. Taking a look at Paramiko-Expect and I like it, but it's timing out every time.

import paramiko
from paramikoe import SSHClientInteraction

HOSTNAME = "HOST IP"
PASSWORD = "PWORD"
USERNAME = "UNAME"
PROMPT = "(node name)#"

command = "show command"

print PROMPT

file = open("testlog.txt","w")

def main():

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

    client.connect(HOSTNAME, port=22, username=USERNAME, password=PASSWORD)

    interact = SSHClientInteraction(client, timeout=10, display=True)

    interact.send(command)
    interact.expect(PROMPT)
    file.write(interact.current_output_clean)
    client.close()

    return



main()
file.close()

This is the traceback I get:

Traceback (most recent call last):    
 File "python_test.py", line 40, in <module> 
  main()    
 File "python_test.py", line 28, in main 
  interact.expect(PROMPT)
 File "/usr/local/lib/python2.7/site-packages/paramikoe.py", line 122, in expect 
  buffer = self.channel.recv(self.buffer_size)    
 File "/usr/local/lib/python2.7/site-packages/paramiko/channel.py", line 598, in recv 
  raise socket.timeout() socket.timeout

I've tried multiple versions of the PROMPT to expect, from directly putting in the text of the node I'm trying it on to full regex. Nothing works. It always times out when it gets to the client.expect. Paramiko-expect documentation does not help and the only other place I see this question is different enough that it doesn't help. Any advice is appreciated.

Upvotes: 0

Views: 4340

Answers (1)

Michał Zaborowski
Michał Zaborowski

Reputation: 4387

Put prompt to something you expect, as... prompt. Here is paramiko interaction example. Please note lines 21, and 37 -

PROMPT = 'vagrant@paramiko-expect-dev:~\$\s+'

interact.expect(PROMPT)

So, when I've updated part of your code to:

interact = SSHClientInteraction(client, timeout=10, display=True)
interact.expect(PROMPT)

interact.send("ls")
interact.expect(".*Maildir.*")
file.write(interact.current_output_clean)
client.close()

I have testlog.txt filled with listing of the home directory, of remote host.

As a side note - switch to python 3. If you are starting, it is better to use tool that is not well known to be outdated soon. Also you can use ipython, or jupyter - code will be more interactive, faster to test. Maybe netmiko will be interested for you?

Upvotes: 2

Related Questions