开发者

How to automate shell input with python?

I am automating some tasks with python, but have hit a bit of a roadblock. One of the tasks I am automating requires user input in the shell.

The requirement is that you to run the command with an email address as a parameter (simple enough), and then you are asked to auth开发者_C百科enticate with the password for that email address. How can you simulate user input to provide the password?

There are also some menus afterwards which ask options, for which the input need just be to repeatedly hit enter. How is this simulated? Keeping in mind that this window will not always have focus..


I'm not sure what you're asking in the second part, but subprocesses can be controlled with the pexpect module. For example:

#!/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)


Looks like you are thinking in a wrong way. You just need to send some bytes via pipe to recipient (shell script in your case) and this can be done with subprocess.


I guess you can use expect for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜