【问题标题】:Expect script issue期待脚本问题
【发布时间】:2011-12-05 12:12:23
【问题描述】:

我正在尝试通过期望完成一项简单的工作。我想在 Linux VM 上使用“ssh-keygen”命令创建 ssh 密钥。我下面的期望代码看起来很简单,但它不起作用:

#!/usr/bin/expect

spawn ssh-keygen -t rsa
expect -exact "Enter file in which to save the key (/root/.ssh/id_rsa): "
send -- "\r"
expect -exact "Enter passphrase (empty for no passphrase): "
send -- "\r"
expect -exact "Enter same passphrase again: "
send -- "\r"

我不想使用任何密码短语。因此为“Enter”键操作输入"\r"。 我尝试使用"#!/usr/bin/expect -d" 运行此代码,但我发现它与我提到的字符串不匹配。如下所示:

...
expect: does "" (spawn_id exp6) match exact string "Enter file in which to save the key (/root/.ssh/id_rsa): "? no
....

所以我假设它无法匹配模式,我的脚本失败了。 问题是,为什么它不能匹配模式。我正在使用"-exact",但它仍然无法匹配模式。我试图玩弄"-re",但我认为我不擅长 TCL 正则表达式。

你能帮忙吗? 谢谢。

【问题讨论】:

    标签: bash expect


    【解决方案1】:

    生成的程序可能发送的输出比您尝试匹配的确切更多。这就是正则表达式匹配如此有用的原因。

    试试这个:

    spawn ssh-keygen -t rsa
    expect -re {Enter file in which to save the key (/root/.ssh/id_rsa): $}
    send -- "\r"
    expect -re {Enter passphrase (empty for no passphrase): $}
    send -- "\r"
    expect -re {Enter same passphrase again: $}
    send -- "\r"
    

    【讨论】:

    • 谢谢格伦,你在正则表达式部分是对的。它适用于匹配模式,但 expect 命令的调试显示模式不匹配。我不关心调试,只要我的脚本有效。谢谢。
    【解决方案2】:

    我想你很快就退出了。这个对我有用:

    #!/usr/bin/expect
    
    spawn ssh-keygen -t rsa
    expect "Enter file in which to save the key (/root/.ssh/id_rsa): "
    send  "\r"
    expect "Enter passphrase (empty for no passphrase): "
    send  "\r"
    expect "Enter same passphrase again: "
    send  "\r"
    expect
    

    【讨论】:

    • 谢谢 Dimitre,你说得对,我退出得太早了。我从来没有意识到这一点。在遵循您和格伦的建议后,我的脚本工作得非常好。谢谢你们。
    猜你喜欢
    • 2012-05-18
    • 2010-09-28
    • 2011-03-12
    • 2016-02-03
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    相关资源
    最近更新 更多