【问题标题】:use of if/else statement with pexpect将 if/else 语句与 pexpect 一起使用
【发布时间】:2018-07-18 12:11:54
【问题描述】:

我正在尝试编写一个脚本,我想在交互式 pexpect 模块的帮助下使用 tacacs 凭据访问交换机。但是我想使用 if/else 语句并相应地发送不同的命令。

例如:

1) 期望 'password:' 并发送登录密码。

abc:PythonScripts$ ssh username@ip_address
password:

2) 期待“您确定要继续连接(是/否)吗?”并发送命令“yes”。

abc:PythonScripts$ ssh username@ip_address
Are you sure you want to continue connecting (yes/no)?

【问题讨论】:

    标签: pexpect


    【解决方案1】:

    嘿,你解决了吗? 我处于同样的情况,我正在尝试评估 c.expect('connecting') 的返回值 并在 if 语句上使用它,但我不确定,因为我也试图将所有命令放入一个函数中,以便调用它而不是多次编写它

    编辑:

    我找到了这个

    index = p.expect (['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
    if index == 0:
        do_something()
    elif index == 1:
        do_something_else()
    elif index == 2:
        do_some_other_thing()
    elif index == 3:
        do_something_completely_different()
    
    instead of code like this:
    
    try:
        index = p.expect (['good', 'bad'])
        if index == 0:
            do_something()
        elif index == 1:
            do_something_else()
    except EOF:
        do_some_other_thing()
    except TIMEOUT:
        do_something_completely_different()
    

    源代码:http://www.bx.psu.edu/~nate/pexpect/pexpect.html

    【讨论】:

    • 你找到了。它有帮助吗?它是否解决了本页顶部的问题?如果是,请删除与How to Answer 不匹配的所有内容,并解释显示的代码如何解决问题。目前,您的帖子有可能被误解为您对某些代码有疑问的问题,因此应该被您删除。 (不过风格不错,链接到你找到的地方)
    猜你喜欢
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多