如何用Python自动化shell输入?
我正在用Python自动化一些任务,但遇到了一些困难。其中一个任务需要在命令行中输入用户信息。
这个任务的要求是,你需要用一个电子邮件地址来运行命令(这很简单),然后系统会要求你输入这个邮箱的密码。请问怎么才能模拟用户输入来提供这个密码呢?
之后还有一些菜单会询问选项,你只需要不断按回车键就可以了。这个怎么模拟呢?还要考虑到这个窗口不一定总是处于活动状态……
3 个回答
0
我想你可以用 expect 来实现这个功能。
1
看起来你想的方向不太对。你只需要通过管道发送一些字节给接收方(在你这个例子中是一个shell脚本),这可以通过subprocess
来实现。
3
我不太明白你在第二部分问的是什么,不过你可以用 pexpect
模块来控制子进程。比如说:
#!/usr/bin/env python
import pexpect
import sys
# Get email and password somehow
#email = ...
#password = ...
# Start the subprocess
child = pexpect.spawn('mycommand %s' % email)
# redirect output to stdout
child.logfile_read = sys.stdout
# Assumes the prompt is "password:"
child.expect('password:')
child.sendline(password)
# Wait for the process to close its output
child.expect(pexpect.EOF)