bash 期待脚本问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7729948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:56:55  来源:igfitidea点击:

Expect script issue

bashexpect

提问by Dheeraj Kabra

I am trying to accomplish a simple job via expect. I want to create ssh keys using the "ssh-keygen" command on Linux VMs. My below expect code looks to be straight forward but it is not working:

我正在尝试通过期望完成一项简单的工作。我想在 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"

I do not want to use any pass phrase. hence typing "\r"for "Enter" key action. I tried running this code with "#!/usr/bin/expect -d", and I find that it never matches the strings I have mentioned. something like below:

我不想使用任何密码短语。因此键入"\r"“Enter”键操作。我尝试使用 运行此代码"#!/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
....

SO I would presume as it is not able to match the pattern, my script is failing. The question is, why it is not able to match the pattern. I am using "-exact"and still it fails to match the patter. I tried to play around with "-re"but I think I am not good at TCL regex.

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

Could you help. Thanks.

你能帮忙吗。谢谢。

回答by glenn Hymanman

The spawned program is likely sending more output than exactlywhat you're trying to match. That's why regular expression matching is so helpful.

在衍生程序很可能派遣更多的输出正是你想匹配的内容。这就是正则表达式匹配如此有用的原因。

Try this:

尝试这个:

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"

回答by Dimitre Radoulov

I suppose you're exiting to quickly. This one works for me:

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

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