0

I work on multiple servers through ssh. I have automated the copying of ssh auth keys with the script below.

The only problem is it asks for the remote servers password 4 times.

How can I change this to ask just once.

#!/usr/bin/env bash

#
# Usage:
#     copy-ssh-key.sh example.com
#

echo -e "\n>>> Creating remote .ssh folder"
ssh -t $1 "mkdir ~/.ssh"

echo -e "\n>>> Updating .ssh folder permissions"
ssh -t $1 "chmod 700 ~/.ssh"

echo -e "\n>>> Copying Auth Keys"
cat ~/.ssh/id_rsa.pub | ssh $1 "cat >> ~/.ssh/authorized_keys"

echo -e "\n>>> Updating auth keys permissions"
ssh -t $1 "chmod 600 ~/.ssh/authorized_keys"
3
  • 3
    Don't reinvent the wheel. Use ssh-copy-id. Oct 27, 2014 at 3:11
  • 1
    man ssh-copy-id. Your problem has been solved.
    – Sven
    Oct 27, 2014 at 3:11
  • Thanks! Googled and googled and did not find this!
    – harvey
    Oct 27, 2014 at 3:30

1 Answer 1

1

Remember that SSH on the remote server uses your shell (e.g. bash) to run the commands. So this will work:

echo "\n>>> running commands"
cat ~/.ssh/id_rsa.pub | ssh -t $1 "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

(Because the commands prior to cat don't read from STDIN, cat gets the input.)

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .