我正在尝试将公钥复制到名为" hostsfile"的文件中的多个主机。 我正在写一个脚本,这将允许我这样做,因为我正在设置开发环境,我可能会一遍又一遍地完成它。 谷歌搜索我已经能够使用ssh-copy-id命令插入公钥,并且能够为一个主机自动化它。 但是,需要对代码进行微调以遍历hosts文件中的每个主机...不幸的是,它完成了第一个条目,然后退出: 以下是代码...提前感谢任何帮助....
#!/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
Glen这是我的评论....你能否提出建议,如果你不介意完整代码的帮助:
#!/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
嗨Glen如你所说,它使用了以下代码。但是,如果密钥已存在于其中一个主机上,则该进程将终止。如果远程主机响应密钥已经存在,你能建议我如何添加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
}
完成
答案 0 :(得分: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"]
答案 1 :(得分: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