使用 Expect 将文件从一个远程复制到另一个

Using Expect to copy a file from one remote to another

我正在尝试在主机集群中启用免密码 ssh 登录。因此,在我通过 ssh-keygen 生成 id_rsa.pub 之后,我想通过此命令

将其复制到所有其他人

此命令在 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 发送,或者我们可以说它无法发送到正确的频道。我现在真的很困惑。

有人可以帮忙吗?

非常感谢您的帮助!非常感谢!

如果有一些关于 Expect 的好的参考或教程,我也将非常感谢您的分享!

使用ssh-copy-idsshpass 命令。
这是我的在线解决方案:

for i in `cat hosts.txt`; do sshpass -p YOUR_PASSWORD_HERE ssh-copy-id -i ~/.ssh/id_rsa.pub -o StrictHostKeyChecking=no $i; done

您需要等待 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 "$ "