我正在尝试在主机集群中启用无密码 ssh 登录。所以在我通过 ssh-keygen 生成 id_rsa.pub 之后,我想通过这个命令将它复制给所有其他人
ssh -t user_name1@client "ssh-copy-id -i ~/.ssh/id_rsa.pub user_name2@server" 此命令在 shell 中有效,但我无法通过
spawn正如预期的那样。我目前正在尝试的是:
#!/usr/bin/expect
#exp_internal 1
set user_name [lindex $argv 0]
set password [lindex $argv 1]
set client [lindex $argv 2]
set server [lindex $argv 3]
set timeout -1
spawn ssh -t $user_name@$client
expect {
# first connection, no public key in ~/.ssh/known_hosts
"yes/no" {
send -- "yes\r"
exp_continue
}
# already has public key in ~/.ssh/known_hosts
"password:" {
send -- "$password\r"
}
}
expect "$ "
send -- "ssh-copy-id -i ~/.ssh/id_rsa.pub $user_name@$server\r"
expect {
"yes/no" {
send -- "yes\r"
exp_continue
}
"password:" { send -- "$password\r" }
}
我调试了一下,发现最后一个
sending有效,但结果与shell中的结果一样出乎意料。我还尝试合并
send -- "ssh-copy-id -i ~/.ssh/id_rsa.pub $user_name@$server\r"和
spawn ssh -t $user_name@$client然后以分层期望发送方式处理它们,但结果是相同的。脚本无法进一步完成最后
password发送,或者我们可以说它无法发送到正确的 channel 。我现在真的很困惑。
有人可以帮忙吗?
非常感谢您的帮助!非常感谢!
如果有关于 Expect 的好的引用资料或教程,我也非常感谢您的分享!
请您参考如下方法:
您需要等待ssh-copy-id命令完成,就像您手动运行命令一样。
expect -ex "$ "
send -- "ssh-copy-id -i ~/.ssh/id_rsa.pub $user_name@$server\r"
expect {
"yes/no" {
send -- "yes\r"
exp_continue
}
"password:" { send -- "$password\r" }
}
expect -ex "$ "




