开发者

Handling an interactive script from another script , using python

开发者 https://www.devze.com 2023-03-06 06:30 出处:网络
I have a shell script a开发者_开发问答nd this one is interactive and I am creating some automation to provide inputs to this shell scripts. The automation is done using Python. example,

I have a shell script a开发者_开发问答nd this one is interactive and I am creating some automation to provide inputs to this shell scripts. The automation is done using Python. example,

the shell script waits for an input like, "what is the domain name?" now the python should be able to provide the input and press ENTER.

Please provide solutions to handle this kind of session with some example.


pexpect: http://pypi.python.org/pypi/pexpect/

it comes with a bunch of examples. e.g. this one for ftp:

import pexpect
import sys

child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')
child.sendline('cd /pub/OpenBSD/3.7/packages/i386')
child.expect('ftp> ')
child.sendline('bin')
child.expect('ftp> ')
child.sendline('prompt')
child.expect('ftp> ')
child.sendline('pwd')
child.expect('ftp> ')
print("Escape character is '^]'.\n")
sys.stdout.write (child.after)
sys.stdout.flush()
child.interact() # Escape character defaults to ^]
# At this point this script blocks until the user presses the escape character
# or until the child exits. The human user and the child should be talking
# to each other now.

# At this point the script is running again.
print 'Left interactve mode.'

# The rest is not strictly necessary. This just demonstrates a few functions.
# This makes sure the child is dead; although it would be killed when Python exits.
if child.isalive():
    child.sendline('bye') # Try to ask ftp child to exit.
    child.close()
# Print the final state of the child. Normally isalive() should be FALSE.
if child.isalive():
    print 'Child did not exit gracefully.'
else:
    print 'Child exited gracefully.'
0

精彩评论

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

关注公众号