我正在努力通过期望完成一项简单的工作。我想在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"
我不想使用任何密码短语。因此,为“输入”键操作键入"\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正则表达式。
答案 0 :(得分: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"
答案 1 :(得分:1)
我想你很快就要离开了。这个对我有用:
#!/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