I wanted to ssh
remote machine and run the ls-l
using pexpect
. i am a system engineer learning the python language and don't have knowledge on coding. Could someone please assist me in this. Thanks in advance.
My code:
import pexpect
child = pexpect.spawn('/usr/bin/ssh root@192.168.32.1')
child.expect('password:', timeout=120)
child.sendline('pass123')
child.expect ('prompt# ')
#child.maxread=100000
child.sendline ('uname -a')
child.expect ('prompt# ')
print child.before, child.after
Below is the error output when run the above code.
usr/bin/python /root/PycharmProjects/IS_LAB/pexpect-test.py
Traceback (most recent call last):
File "/root/PycharmProjects/IS_LAB/pexpect-test.py", line 36, in <module>
child.expect ('prompt# ')
File "/usr/lib/python2.6/site-packages/pexpect/__init__.py", line 1451, in expect
timeout, searchwindowsize)
File "/usr/lib/python2.6/site-packages/pexpect/__init__.py", line 1466, in expect_list
timeout, searchwindowsize)
File "/usr/lib/python2.6/site-packages/pexpect/__init__.py", line 1568, in expect_loop
raise TIMEOUT(str(err) + '\n' + str(self))
pexpect.TIMEOUT: Timeout exceeded.
<pexpect.spawn object at 0x9b4110>
version: 3.3
command: /usr/bin/ssh
args: ['/usr/bin/ssh', 'root@192.168.32.1']
searcher: <pexpect.searcher_re object at 0x9b4450>
buffer (last 100 chars): 'cape.canonical.com/\r\n\r\nLast login: Tue Jun 16 10:26:18 2015 from 192.168.32.1\r\r\nroot@ubuntu14:~# '
before (last 100 chars): 'cape.canonical.com/\r\n\r\nLast login: Tue Jun 16 10:26:18 2015 from 192.168.32.1\r\r\nroot@ubuntu14:~# '
after: <class 'pexpect.TIMEOUT'>
match: None
match_index: None
exitstatus: None
flag_eof: False
pid: 13015
child_fd: 3
closed: False
timeout: 30
delimiter: <class 'pexpect.EOF'>
logfile: None
logfile_read: None
logfile_send: None
maxread: 2000
ignorecase: False
searchwindowsize: None
delaybeforesend: 0.05
delayafterclose: 0.1
delayafterterminate: 0.1
Process finished with exit code 1
The Problem is when you login to any linux box for first time it prompts you for RSA exception. We need to add the Keys permanently in device to avoid this. Hence login from Your Source device to destination device and add the ssh RSA to Linux box.
pexpect
has not found the string you are expecting (prompt#
), so it raised an error.In the stacktrace in can see
buffer
value:You should expect
root@ubuntu14:~#
or#
instead ofprompt#
.You can debug the
pexpect
output.Here is what is going on with your code, it may help you understand why your script is not working:
At this line, your script is searching for the string
prompt#
, but what the server is returning isroot@ubuntu14:~#
. As this doesn't match what you have provided for the script to check for, it raises an exception, which basically means "I waited for TIMEOUT period for a string to match your pattern, but I didn't find it."To solve the problem you can either enter the exact prompt string for your script to search for, like this:
Or simply pause your script for a few seconds: