简体   繁体   中英

Bash script to push ssh_keys

I'm trying to read a file with the names of approx 500 server names on their own individual lines, and then for each of those, ssh in and append the roots authorized_keys file for each. I keep getting errors each time I run the script and/or modify it. Can you please help me figure out what's wrong? My OS is 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

here is the error:

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

From Use expect in bash script to provide password to SSH command , sshpass looks like the easiest way to do this. I would do:

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

Update

With @alvits's suggestion:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM