Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

A shell script to upload SSH keys to remote machines UNIX
This is a script that I initially found online and have modified to be a bit more useful. Basically it automates the process of uploading your SSH key to a remote host that you SSH into by doing the following:
  1. Creates a .ssh directory if there is not one already there, and sets the correct permissions on it.
  2. Puts your key in the authorized_keys file (and creates it if it was not there already), and changes the permissions on it.
Here's the code:

#!/bin/sh

KEY="$HOME/.ssh/id_dsa.pub"

if [ ! -f ~/.ssh/id_dsa.pub ];then
    echo "private key not found at $KEY"
    echo "* please create it with "ssh-keygen -t dsa" *"
    echo "* to login to the remote host without a password, don't give the key you create with ssh-keygen a password! *"
    exit
fi

if [ -z $1 ];then
    echo "Please specify user@host.tld as the first switch to this script"
    exit
fi

echo "Putting your key on $1... "

KEYCODE=`cat $KEY`
ssh -q $1 "mkdir ~/.ssh 2>/dev/null; chmod 700 ~/.ssh; echo "$KEYCODE" >> ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys"

echo "done!"

If you SSH into many machines, the script can save you a lot of manual work.

[robg adds: I tested this, and it works as described -- I edited it to reflect the fact that I have an RSA key, not a DSA key (so I just changed id_dsa.pub to id_rsa.pub). When you run the script, you'll be prompted for the password on the remote machine; after it runs, you can connect without a password (if you're not using a passphrase).]
    •    
  • Currently 3.00 / 5
  You rated: 4 / 5 (7 votes cast)
 
[50,758 views]  

A shell script to upload SSH keys to remote machines | 15 comments | Create New Account
Click here to return to the 'A shell script to upload SSH keys to remote machines' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
A shell script to upload SSH keys to remote machines
Authored by: Lysis on Sep 19, '07 09:35:19AM

OS X doesn't ship it, but the portable OpenSSH comes with a script called ssh-copy-id which does exactly that, and has the advantage of being maintained by the OpenSSH Port guys.



[ Reply to This | # ]
A shell script to upload SSH keys to remote machines
Authored by: fizik on Sep 19, '07 10:28:52AM

"echo" in the script "Please specify user@host.tld as the first switch to this script" means that one needs to issue a command "sh path_to_this_script userid@hostid" to make it work.



[ Reply to This | # ]
A shell script to upload SSH keys to remote machines
Authored by: patniemeyer on Sep 19, '07 03:34:52PM

This is nice, but my main problem is figuring out how to export my keys to different flavors for different machines... it drives me batty. I need to go from OSX to various linux and freebsd machines and it never seems to be as easy as I expect. I RTFM, import / export the public keys, fiddle with things and half the time can never get it to work with no indication as to why. I try running the ssh client in super-debug mode and it spits out a lot of things its trying, but that's usually not what I need (the server side of the story).

I wish there were a definitive spec somewhere on how to do this for various machines or a single converter app that reads everything, etc.

thanks,
Pat



[ Reply to This | # ]
A shell script to upload SSH keys to remote machines
Authored by: fungus on Sep 24, '07 02:42:32PM

There is no messy import/export in SSH keys between OSX, BSD, or Linux. They all use OpenSSH, which is the current defacto standard. All that's necessary is to copy the keys over.

When copying the keys it is absolutely critical that the permissions on the files are correct. SSH will ignore keys if permissions are too open. The .ssh directory should not be readable or writable by anyone but you.

drwx------  .ssh/
-rw-------  .ssh/authorized_keys
-rw-------  .ssh/id_dsa
-rw-r--r--  .ssh/id_dsa.pub


[ Reply to This | # ]
A shell script to upload SSH keys to remote machines
Authored by: heggaton on Sep 19, '07 05:48:52PM
Nice script. I've always found SSH keys to be a PITA to setup but this script will put an end to that!

I use it with http://www.sshkeychain.org/ which makes using ssh a dream

[ Reply to This | # ]
A shell script to upload SSH keys to remote machines
Authored by: rich101 on Sep 20, '07 06:06:49AM

nice 'n easy ;-)

Works on Apple TV too ! ! !



[ Reply to This | # ]
Syntax problem
Authored by: gshenaut on Sep 20, '07 10:01:30AM
Note the nested double quotes in
ssh -q $1 "mkdir ~/.ssh 2>/dev/null; chmod 700 ~/.ssh; echo "$KEYCODE" >> ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys"

Depending on the value of KEYCODE, this may cause intermittent errors. You could change the inner ones to single quotes, or put a backslash in front of them.

Greg Shenaut

[ Reply to This | # ]

A shell script to upload SSH keys to remote machines
Authored by: slacker on Sep 21, '07 10:42:10AM
Nice script. If you ask three Bourne shell scripters to solve a problem, you'll probably get 9 different ways to solve it. I made a couple of corrections to this version: 1) use $KEY variable consistently, 2) set the umask to user rwx only and you don't need chmods anywhere, 3) use $* to pass "-p portnum" arguments for nonstandard ports, 4) mkdir -p argument ignores existing directories, 5) the KEYCODE variable line wasn't necessary, just in-line the backquoted cat command.

#!/bin/sh                                                                                                                                            
                                                                                                                                                     
KEY="$HOME/.ssh/id_dsa.pub"                                                                                                                          
                                                                                                                                                     
if [ ! -f $KEY ];then                                                                                                                                
    echo "private key not found at $KEY"                                                                                                             
    echo "* please create it with \"ssh-keygen -t dsa\" *"                                                                                           
    exit                                                                                                                                             
fi                                                                                                                                                   
                                                                                                                                                     
if [ -z $1 ];then                                                                                                                                    
    echo "Usage: $0 username@host"                                                                                                                       
    exit                                                                                                                                             
fi                                                                                                                                                   
                                                                                                                                                     
echo "Putting your key on $1... "                                                                                                                    
ssh -q $* "umask 0077; mkdir -p ~/.ssh ; echo "`cat $KEY`" >> ~/.ssh/authorized_keys"                                                                
echo "done!"                                                                                                                                         


[ Reply to This | # ]
no passphrase
Authored by: slacker on Sep 21, '07 10:55:51AM

One other thing, many new Unix/Linux distributions don't accept ssh keys without a passphrase as a default security setting. Don't recommend password-less keys to users. Otherwise, 5 minutes with your machine and my Knoppix bootalble CD and your arse is mine :-). Seriously, braindead things happen with filesystems and private keys do get compromised. Learn to use ssh-agent or SSH Keychain.



[ Reply to This | # ]
no passphrase
Authored by: bendybendy on Sep 21, '07 11:03:11AM

it's not perfect, but a decent compromise is to keep the ~/.ssh in an encrypted sparseimage that I open and close when I need to do remote work.



[ Reply to This | # ]
A shell script to upload SSH keys to remote machines
Authored by: bendybendy on Sep 21, '07 10:57:36AM
if i know that the remote .ssh directory exists, I usually just type this one liner-

cat ~/.ssh/id_rsa.pub | ssh account@remoteserver.com "cat - >> .ssh/authorized_keys"


[ Reply to This | # ]
Well, here's a version that actually creates a password free ssh connection
Authored by: dhjdhj on Sep 22, '07 12:20:55PM

I found the script below somewhere on the net last year, it was slightly broken and so has been minorly modified by me. It has been used successfully for CREATING a password free connection to a remote machine. That is, you run this script on a local machine, and give it as a parameter the userid@remoteserver. The script will then connect to the remote machine, prompt you for your password a few times, setup and transfer the keys appropriately and after it's done, you can just ssh to the remote machine and be logged in.

It has been tested on Windows (cygwin), Linux, and OS X.

David Jameson
-------------------------------------------



#!/bin/sh

# create ssh connections without giving a password - found on the net
# Modified by DHJ to correct several bugs and missing commands

if [ $# -lt 1 ]; then
echo Usage: $0 username@remotehost
exit
fi
remote="$1" # 1st command-line argument is the user@remotehost address
this=$HOST # name of client host

# first check if we need to run ssh-keygen for generating
# $HOME/.ssh with public and private keys:
if [ ! -d $HOME/.ssh ]; then
echo "just type RETURN for each question:" # no passphrase - unsecure!!
# generate DSA keys only:
echo; echo; echo
#This will generate the .ssh directory and put the keys in it
ssh-keygen -t dsa
else
# we have $HOME/.ssh, but check that we have
# key (DSA):
if [ ! -f $HOME/.ssh/id_dsa ]; then
# generate DSA keys:
echo "just type RETURN for each question:" # no passphrase - unsecure!!
ssh-keygen -t dsa
fi
fi

echo "You will be asked for your remote password several times during this phase"

cd $HOME/.ssh

if [ ! -f config ]; then
# make ssh try ssh -2 (DSA keys)
echo "Protocol 2" > config
chmod 600 config
fi

#Make sure private key cannot be read by anyone else
chmod 600 $HOME/.ssh/id_dsa

# copy public keys to the destination host:

echo; echo; echo
# create .ssh on remote host if it's not there:
echo "Connecting to remote host to create .ssh directory..."
ssh $remote 'if [ ! -d .ssh ]; then mkdir .ssh; fi'
# copy DSA key:
echo "Copying public DSA key to remote host..."
scp id_dsa.pub ${remote}:.ssh/${this}_dsa.pub
# make authorized_keys(2) files on remote host:

echo; echo; echo
# this one copies DSA key:
echo "Configuring authorized_keys2 file on remote host..."
ssh $remote "cd .ssh; touch authorized_keys2; cat ${this}_dsa.pub >> authorized_keys2;"
echo "Configuring directory permissions on remote host..."
ssh $remote "cd .ssh; rm ${this}_dsa.pub; chmod 600 *; cd ..; chmod go-rwx .ssh;"
echo; echo; echo
echo "You should now be able to ssh to the remote host without a password"
echo "try ssh $remote"



[ Reply to This | # ]
sshkeygen and ssh-rekey
Authored by: ubiquitin on Sep 22, '07 12:56:06PM
to make your own robustly generated ssh keys, sshkeygen is online at:
http://www.sshkeygen.com

ssh-rekey allows for automated re-key of ssh keys, see:
http://caughron.googlepages.com/


[ Reply to This | # ]
A shell script to upload SSH keys to remote machines
Authored by: quentinsf on Sep 23, '07 05:08:49AM
It seems as if many people have created scripts to do a similar thing - there was definitely a need!

I called mine 'sshput'. Info here:

http://www.qandr.org/quentin/software/sshput/

[ Reply to This | # ]
ssh-copy-id script code and ssh-agent instructions
Authored by: chris7cmcc on Sep 26, '07 04:29:53PM

'Apologies if someone already pasted in the following information,

but OpenSSH should include the very useful ssh-copy-id script.
Apparently the native MAC OSX version does not contain it?

Also, I agree with Slacker--don't use passphrase-less keys, unless you won't care when someone breaks into your system--note the use of "when."

--> use ssh-agent (man ssh-agent)
ssh-agent bash
ssh-add (enter passphrase)
ssh-add -l (see what you got going on now?)

Now (assuming you have your public key added to the dest account's ~/.ssh/authorized_keys file) you should be able to start having some fun.

Now you can ssh without passwords to all hosts you have your key installed on until you terminate your ssh-agent. For added securiy, you could start your ssh-agent like this (will not display its PID):
eval `ssh-agent` > /dev/null


Below is the ssh-copy-id from my Debian box:
less /usr/bin/ssh-copy-id

#!/bin/sh

# Shell script to install your identity.pub on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.

ID_FILE="${HOME}/.ssh/identity.pub"

if [ "-i" = "$1" ]; then
shift
# check if we have 2 parameters left, if so the first is the new ID file
if [ -n "$2" ]; then
if expr "$1" : ".*\.pub" ; then
ID_FILE="$1"
else
ID_FILE="$1.pub"
fi
shift # and this should leave $1 as the target name
fi
else
if [ x$SSH_AUTH_SOCK != x ] ; then
GET_ID="$GET_ID ssh-add -L"
fi
fi

if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
GET_ID="cat ${ID_FILE}"
fi

if [ -z "`eval $GET_ID`" ]; then
echo "$0: ERROR: No identities found" >&2
exit 1
fi

if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
exit 1
fi

{ eval "$GET_ID" ; } | ssh $1 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1

cat <<EOF
Now try logging into the machine, with "ssh '$1'", and check in:

.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

EOF

#####

Since it's missing from my OSX box too, here is the man page for ssh-copy-id

SSH-COPY-ID(1)

NAME
ssh-copy-id - install your identity.pub in a remote machine's authorized_keys

SYNOPSIS
ssh-copy-id [-i [identity_file]] [user@]machine

DESCRIPTION
ssh-copy-id is a script that uses ssh to log into a remote machine (presumably using a login password, so password authentication should be enabled, unless
you've done some clever use of multiple identities)

It also changes the permissions of the remote user's home, ~/.ssh, and ~/.ssh/authorized_keys to remove group writability (which would otherwise prevent
you from logging in, if the remote sshd has StrictModes set in its configuration).

If the -i option is given then the identity file (defaults to ~/.ssh/identity.pub) is used, regardless of whether there are any keys in your ssh-agent.
Otherwise, if this:

ssh-add -L

provides any output, it uses that in preference to the identity file.

If the -i option is used, or the ssh-add produced no output, then it uses the contents of the identity file. Once it has one or more fingerprints (by
whatever means) it uses ssh to append them to ~/.ssh/authorized_keys on the remote machine (creating the file, and directory, if necessary)

SEE ALSO
ssh(1), ssh-agent(1), sshd(8)



[ Reply to This | # ]