简体   繁体   English

使用 pexpect 获取“ls”命令的输出

[英]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 :我正在尝试使用 pexpect 以用户身份登录并尝试打印所有可用的 cron:

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如果有任何更好的方法来列出其他用户的 cron 作业,给定用户名和密码

Any pointers or suggestions would be much appreciated.任何指示或建议将不胜感激。

If you can arrange to configure password-less sudo access, then the above simply becomes:如果您可以安排配置无密码sudo访问,那么上面的内容就变成了:

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:如果您需要继续使用su ,那么您可以向它传递一个命令并避免尝试解析 shell 提示:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM