Search code examples
pythonpython-2.7subprocesscronpexpect

Using pexpect to get output of 'ls' command


I am trying to login as a user using pexpect and trying to print all the crons available :

import pexpect
import os, time
passwd = "mypass"
child = pexpect.spawn('su myuser')
child.expect('Password:')
child.sendline(passwd)
child.expect('$')
child.sendline('crontab -l')
i =child.expect(['%','.*$', '$'  ])
print i                       # prints 1 here so, the shell is expected.
print child.before            # this doesn't print anything though.

This code doesn't seem to be working and prints empty line.

  1. Couldn't figure out the issue with this code
  2. If there is any better way to list cron job of other user, given username and password

Any pointers or suggestions would be much appreciated.


Solution

  • If you can arrange to configure password-less sudo access, then the above simply becomes:

    import subprocess
    output = subprocess.check_output('sudo -u myuser crontab -l', shell=True)
    

    If you need to continue using su, then you can pass it a command and avoid trying to parse shell prompts:

    import pexpect
    passwd = "mypass"
    child = pexpect.spawn('su myuser -c "crontab -l"')
    child.expect('Password:')
    child.sendline(passwd)
    child.expect(pexpect.EOF)
    
    print child.before