用于推送ssh_keys的Bash脚本

时间:2014-01-17 21:58:43

标签: linux bash

我试图在各自的行上读取一个名称大约500个服务器名称的文件,然后为每个文件ssh输入并附加每个根authorized_keys文件。每次运行脚本和/或修改脚本时,我都会遇到错误。你能帮我弄清楚出了什么问题吗?我的操作系统是Mac OS X:

#!/usr/bin/expect
set timeout 60
set SERVERS "cat /Users/macuser/server.lst"
set USER "myuser"
set MY_PASS "mypasswordhere"

for EACH in $SERVERS; do
cat /Users/macuser/.ssh/id_rsa.pub | ssh $USER@$EACH "tee -a .ssh/authorized_keys"
expect {
    eof                          {break}
    "The authenticity of host"   {send "yes\r"}
    "password:"                  {send "$MY_PASS\r"}
    }

interact
done

这是错误:

wrong # args: should be "for start test next command"
while executing
"for EACH in $SERVERS"
(file "./keyssh_push.sh" line 7)

1 个答案:

答案 0 :(得分:1)

Use expect in bash script to provide password to SSH command开始,sshpass看起来是最简单的方法。我愿意:

#!/bin/sh
servers=`cat /Users/macuser/server.lst`
user="myuser"
my_pass="mypasswordhere"

for server in $servers
do
  </Users/macuser/.ssh/id_rsa.pub sshpass -p"$my_pass" \
    ssh -o StrictHostKeyChecking=no $user@$server cat '>>.ssh/authorized_keys'
done

更新

@ alvits的建议:

#!/bin/sh
servers=`cat /Users/macuser/server.lst`
user="myuser"
my_pass="mypasswordhere"

for server in $servers
do
  sshpass -p"$my_pass" ssh-copy-id -o StrictHostKeyChecking=no \
    -i /Users/macuser/.ssh/id_rsa $user@$server
done