Python pexpect & pxssh with sudo and EOF

I am doing ssh login using this script:

import pxssh
import pexpect

s = pxssh.pxssh()
hostname = 'localhost'
username = 'py_worker'
password = 'nicejob'
s.login (hostname, username, password)
print "logged in"

      

Then I want to run some program which in some cases may require a sudo password and in some cases may not be required. So I want to create a script that can provide the sudo password when needed and just run the program if sudo is not given. I thought this code could handle:

s.sendline('sudo apt-get check')
i=s.expect(['password', pexpect.EOF])
if i==0:
    print "I give password"
    s.sendline("nicejob")
    s.prompt()
elif i==1:
    print "EOF cought"
    s.prompt()
print s.before

      

Can anyone help with lines of code that sudo might handle correctly?

0


source to share


1 answer


thanks for asking, it helped me.

you will probably need to spell out the exceptions and re for rootprompt, but here you go.



def sudo(s,password):
    rootprompt = re.compile('.*[$#]')
    s.sendline('sudo -s')
    i = s.expect([rootprompt,'assword.*: '])
    if i==0:
        print "didnt need password!"
        pass
    elif i==1:
        print "sending password"
        s.sendline(password)
        j = s.expect([rootprompt,'Sorry, try again'])
        if j == 0:
            pass
        elif j == 1:
            raise Exception("bad password")
    else:
        raise Exception("unexpected output")
    s.set_unique_promp

      

+3


source







All Articles