2015-11-03 71 views
1

我試圖將公鑰複製到名爲「hostsfile」的文件中的多個主機上。 我正在編寫一個腳本,允許我這樣做,因爲我正在設置一個開發環境,我可能會一遍又一遍地做它。 谷歌搜索我已經能夠使用ssh-copy-id命令插入公鑰,並且已經能夠爲一個主機自動化它。 但是,代碼需要微調以遍歷hosts文件中的每個主機......不幸的是,它完成了第一個條目,然後退出: 下面是代碼...提前感謝任何幫助....迭代ssh-copy-id命令在多個主機上覆制

#!/usr/bin/expect 
set timeout 10 
set f [open "hostsfile"] 
set hosts [split [read $f] "\n"] 
close $f 

set exp_internal 1 
foreach host $hosts { 
    spawn ssh-copy-id -i /home/vagrant/.ssh/ansible-use-ssh-key.pub $host 
    expect_after eof { exit 0 } 
    expect "password:" { send "vagrant\r" } 
    expect_after eof { exit 0 } 
    expect "$ " 
    } 
send "exit\r" 
expect eof 

格倫 - 這是我做出來的你的意見....你可以建議討好,如果你不介意的幫助與完整代碼:

#!/usr/bin/expect 
set timeout 10 
set f [open "hostsfile"] 
close $f 

set hosts [split [read -nonewline $f] "\n"] 

foreach host $hosts { 
    spawn ssh-copy-id -i /home/vagrant/.ssh/ansible-use-ssh-key.pub $host 
    expect "password:" 
    send "vagrant\r" 
    expect eof 
} 
puts done 

嗨格倫它與下面的代碼工作如你所建議的。但是,如果密鑰已經存在於進程終止的其中一臺主機上。你能否建議我如何添加if/else狀態,以便在遠程主機響應密鑰時不中斷?感謝您的幫助提前。

以下是適用於第一個問題的代碼。

#!/usr/bin/expect 
set timeout 10 
set f [open "hostsfile"] 
set hosts [split [read -nonewline $f] "\n"] 
close $f 


foreach host $hosts { 
    spawn ssh-copy-id -i /home/vagrant/.ssh/ansible-use-ssh-key.pub $host 
    expect "password:" 
    send "vagrant\r" 
    expect eof 
} 

卻將完成

回答

1

您已指示期望EOF後退出。不要這樣做。

foreach host $hosts { 
    spawn ssh-copy-id -i /home/vagrant/.ssh/ansible-use-ssh-key.pub $host 
    expect "password:" 
    send "vagrant\r" 
    expect eof 
} 
puts done 

請注意,您的$ hosts列表中有一個空的最後一個元素。使用read -nonewline讀取文件:

set hosts [split [read -nonewline $f] "\n"] 
+0

謝謝格倫,但是我現在得到以下錯誤:「無法找到名爲通道‘file6’ 在執行 ‘讀-nonewline $ F’ 從內部 援引」分裂[閱讀-nonewline $ f]「\ n」「 」set hosts [split [read -nonewline $ f]「\ n」]「 (文件」./ssh-copy_F.sh「line 6) –

+0

您的意思是以取代目前的分割讀取線,而不是在你已經關閉文件後添加一個新行 –

+0

好吧我想我找到了錯誤...我切換了關閉並設置主機線...但是現在我面對另一個問題是如果鍵已經存在於其中一臺主機上,終止了整個腳本......那麼,我將如何將其添加到腳本中?提前謝謝你的幫助。 –

1

格倫,我找到了答案,我的第二個問題......下面是顯然是爲我工作的代碼。感謝您的幫助,讓我瞭解這一點。

#!/usr/bin/expect 
set timeout 10 
set f [open "hostsfile"] 
set hosts [split [read -nonewline $f] "\n"] 
close $f 

foreach host $hosts { 
    spawn ssh-copy-id -i /home/vagrant/.ssh/ansible-use-ssh-key.pub $host 
    expect { 
      "password:" { 
        send "vagrant\r" 
        exp_continue 
       } 
       "already exist on the remote system." { 
        exp_continue 
       } 
    expect eof 
     } 
} 
puts done 
+0

將'expect eof'改爲'eof' –