Question

I started using the Pexpect library and for some reason I am having problems getting expressions to get matched.

For example in the following code

   import pexpect

   child=pexpect.spawn('su')
   i=child.expect_exact('Password:')
   print "value of i is %d" %i
   if i==1:
          p=input("Please enter root password : ")
          child.sendline(p)
          child.sendline('echo piggy')

problem i never equals 1

Was it helpful?

Solution

su refuses to run when not invoked from a terminal:

$ echo blah | su
su: must be run from a terminal

OTHER TIPS

IMO, when pexpect is the answer, you're asking the wrong question.

In this case, you could probably use sudo more effectively. It can be configured to run things as root, when invoked by a particular user, without demanding a password.

According to the documentation, when you pass a string to expect_exact(), it returns 0 on a match, not 1.

Have you tried comparing i to 0?

First you login in super user use for this comment,pxssh is This class extends pexpect.spawn to specialize setting up SSH connections.This adds methods for login, logout, and expecting the shell prompt.

import pexpect
import pxssh

hostname ='172.16.0.120 -p 2222'
username = 'root'  # must you login in super user add this line
password = 'zilogic'
host = pxssh.pxssh()
host.login (hostname, username, password)
host.logfile = open(logfile, "w")
host.sendline ('whoami') 
print host.before

you will use for pxssh module don’t need for child.expect_exact('Password:'),this password expect take care of pxssh module see this link Python: How can remote from my local pc to remoteA to remoteb to remote c using Paramiko and How to login the super user(root) in remote host system using pexpect?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top