迭代 ssh-copy-id 命令以在多个主机上复制

iterating ssh-copy-id command to copy on multiple hosts

我正在尝试将 public 密钥复制到名为 "hostsfile" 的文件中的多个主机。 我正在编写一个脚本,允许我在设置开发环境时执行此操作,最终我可能会一遍又一遍地这样做。 谷歌搜索我已经能够使用 ssh-copy-id 命令插入 public 密钥,并且能够为一台主机自动执行它。 然而,需要对代码进行微调以遍历主机文件中的每个主机……不幸的是,它完成了第一个条目然后退出: 下面是代码...提前感谢任何帮助....

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

完成

您已指示 expect 在 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"]

格伦,我找到了第二个问题的答案...下面是显然对我有用的代码。感谢您的热心帮助,让我度过难关。

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