1

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)
user102825
  • 45
  • 7

1 Answers1

1

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
Community
  • 1
  • 1
Graeme
  • 2,971
  • 21
  • 26
  • This looks pretty close to what i originally started with. i was trying to use "expect" because most of the servers that im connecting to arent in my known_hosts file so each time i get prompted to save with a "(yes/no)?". i was trying to avoid that. is there a way to script in the "yes" to the known_hosts and the password prompt? – user102825 Jan 17 '14 at 22:30
  • http://serverfault.com/questions/132970/can-i-automatically-add-a-new-host-to-known-hosts – Graeme Jan 17 '14 at 22:36
  • You mean like `/usr/bin/yes` ? – OnlineCop Jan 17 '14 at 22:39
  • Updated answer to disable StrictHostKeyChecking, although using `ssh-keygen`/`ssh-keyscan` to add keys to known_hosts before starting is a safer approach. – Graeme Jan 17 '14 at 22:45
  • Why don't you use `sshpass -p"$my_pass" ssh-copy-id -o StrictHostKeyChecking=no -i /Users/macuser/.ssh/id_rsa $user@$server`? This will also ensure the remote user's .ssh directory is created if it doesn't exist. – alvits Jan 17 '14 at 22:52