56506

ssh remote machine and run the 'ls-l' using pexpect

Question:

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

Answer1:

Here is what is going on with your code, it may help you understand why your script is not working:

import pexpect child = pexpect.spawn('/usr/bin/ssh root@192.168.32.1') # This line means, "wait until you see a string that matches password:" # in the response child.expect('password:', timeout=120) child.sendline('pass123') # Send the characters pass123 and "enter" # Wait till you see a string matching prompt# child.expect ('prompt# ')

At this line, your script is searching for the string prompt#, but what the server is returning is root@ubuntu14:~#. As this doesn't match what you have provided for the script to check for, it raises an exception, which basically means <em>"I waited for TIMEOUT period for a string to match your pattern, but I didn't find it."</em>

To solve the problem you can either enter the exact prompt string for your script to search for, like this:

child.sendline('pass123') # Send the characters pass123 and "enter" # Wait till you see a string matching ~# child.expect('~#') child.sendline ('uname -a') child.expect ('~#') print child.before, child.after

Or simply pause your script for a few seconds:

import time child.sendline('pass123') # Send the characters pass123 and "enter" time.sleep(10) child.sendline('uname -a') time.sleep(10) print child.before, child.after

Answer2:

pexpect has not found the string you are expecting (prompt#), so it raised an error.

In the stacktrace in can see buffer value:

'cape.canonical.com/\r\n\r\nLast login: Tue Jun 16 10:26:18 2015 from 192.168.32.1\r\r\nroot@ubuntu14:~# '

You should expect root@ubuntu14:~# or # instead of prompt#.

You can <a href="http://pexpect.readthedocs.org/en/latest/overview.html#debugging" rel="nofollow">debug</a> the pexpect output.

Answer3:

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.

Recommend

  • How to send None with Signals across threads?
  • Intel c/c++ compiler: “could not locate executable icc” (and ecc)
  • Importing pyplot in a Jupyter Notebook
  • proxy request in node.js / express
  • redirect user after update in class based view in django
  • git cherry-pick: how consider only lines modified by the commit (i.e., not the surrounding context)?
  • How to override List.Add method?
  • help('modules') crashing? Not sure how to fix
  • Python Tkinter after event OOPS implementation
  • How to synchronize two scrollview in Android?
  • How do I change the kernel/python version for iPython?
  • MRO with multiple inheritance in python
  • EF 4.1 DBContext AutoDetectChangesEnabled
  • user data scripts fails without giving reason
  • Binary trees in scheme
  • Microsoft Excel Pivot miscalculation in Sum for positive and negative numbers
  • How to convert integer to string and get length of string
  • Faster Way To Simultaneously Iterate Over Rolling Window Of Two Or More Numpy Arrays?
  • What causes the runtime difference in this trivial fortran code?
  • NHibernate manually control fetching
  • In-place sed command not working
  • Azure webjobs output logs indexing taking very long
  • Switch to popup in python using selenium
  • How to pass a value from ASP.NET MVC controller to ASP.NET webforms control inside MVC View?
  • During installation of Django, why do I keep getting ImportError: No module named django?
  • pillow imaging ImportError
  • Element.tagName for python not working
  • Problems installing Yesod for Haskell
  • Odoo 10 - Overriding unlink method
  • Eloquent paginate function in Slim 3 project using twig
  • error importing numpy
  • All Classes Conforming to Protocol Inherit Default Implementation
  • Ajax jQuery multiple calls at the same time - long wait for answer and not able to cancel
  • Cross-Platform Protobuf Serialization
  • Hazelcast - OperationTimeoutException
  • Websockets service method fails during R startup
  • File upload with ng-file-upload throwing error
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Bitwise OR returns boolean when one of operands is nil
  • MATLAB: Piecewise function in curve fitting toolbox using fittype