2011-10-11 200 views
1

我試圖完成一項簡單的工作通過期待。我想在Linux VM上使用「ssh-keygen」命令創建ssh密鑰。我下面預計的代碼看起來很直接,但它不工作:Expect腳本問題

#!/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正則表達式。

你能幫忙嗎? 謝謝。

回答

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" 
+0

謝謝格倫,你正確的正則表達式的一部分。它用於匹配模式,但expect命令的調試顯示模式不匹配。只要我的腳本正常工作,我不在乎調試。謝謝。 –

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 
+0

謝謝Dimitre,你是正確的,我是太早退出。我從未意識到這一點。遵循Glenn的建議,我的腳本工作得很好。感謝你們。 –