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

时间:2016-12-30 13:06:17

标签: shell ssh expect

我正在尝试在主机群集中启用无密码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发送,或者我们可以说它无法发送到正确的频道。我现在真的很困惑。

有人可以帮一下吗?

真的很感谢你的帮助!非常感谢你!

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

使用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