linux - 怎么自动填写有交互的shell脚本
伊谢尔伦
伊谢尔伦 2017-04-17 11:05:28
[Linux讨论组]

在写一个shell脚本A,其中调用了另一个脚本,例如test.sh
但是test.sh中有交互的内容
需要用户依次输入 a 回车 b 回车 回车 回车
我想自动的实现它,请问应该在A中怎么写才会自动填入这些内容,前提是tesh.sh执行的过程还要让用户看到,不能把它重定向

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(4)
PHP中文网

用pexpect,以下代码供参考:

#!/usr/bin/python

import sys 
import pexpect

password = 'password'
expect_list = ['(yes/no)', 'password:']

p = pexpect.spawn('ssh username@localhost ls')
try:
    while True:
        idx = p.expect(expect_list)
        print p.before + expect_list[idx],
        if idx == 0:
            print "yes"
            p.sendline('yes')
        elif idx == 1:
            print password
            p.sendline(password)
except pexpect.TIMEOUT:
    print >>sys.stderr, 'timeout'
except pexpect.EOF:
    print p.before
    print >>sys.stderr, '<the end>'

输出:

username@localhost's password: password

Permission denied, please try again.
username@localhost's password: password

Permission denied, please try again.
username@localhost's password: password

Permission denied (publickey,gssapi-with-mic,password).

<the end>
巴扎黑

用管道输入,然后echo出来,给用户看
A.sh

echo -e a\nb\n\n\n | bash test.sh
echo a
echo b
echo
echo
echo

如果管道输入满足不了你的需求,就用expect,这个比较复杂了。。。

PHP中文网

可以google here document~

天蓬老师

expect就可以实现了

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号