Load SSH key remotely I often create new accounts or virtual machines, and then have to load my SSH public key/signature in to the authorized keys on that account. That process can be tedious, so I created this script that pushes my authorization on the remote machine. So, typically when you ssh to a remote machine you have to enter your password, etc. To automate jobs, though, you often don't want to do that, and key-based authentication allows you to authenticate without the password.

There are other ways to push keys around, but this makes it simple to fix things after the fact, or to initialize new accounts, etc.

I am looking for a review of any and all aspects, including the way that SSH is set up, and so on.

Here's an example transcript of what the script outputs:

panabox:~/bin&gt; loadkey sol@solarium
Installing Key...
sol@solarium's password: 
Checking Key ...
Great!
panabox:~/bin&gt; loadkey sol@solarium
Already Works!
panabox:~/bin&gt; 


And here is the script:

#!/bin/bash

if [ "$#" -ne 1 ]
then
  echo "Must supply user@hostname:   loadkey &lt;user@hostname&gt;"
  exit 1
fi

host=$1

ssh -2 -o BatchMode=yes $host "echo hi" &gt;&amp; /dev/null &amp;&amp; echo Already Works! &amp;&amp; exit 0

echo Installing Key...
install="mkdir -p ~/.ssh &amp;&amp; chmod 700 ~/.ssh &amp;&amp; cat - &gt;&gt; ~/.ssh/authorized_keys &amp;&amp; chmod 600 ~/.ssh/authorized_keys"
cat ~/.ssh/id_rsa.pub | ssh -2 $host $install

echo Checking Key ...
ssh -2 -o BatchMode=yes $host "echo hi" &gt;&amp; /dev/null &amp;&amp; echo Great! &amp;&amp; exit 0

echo Failed to install key.
exit 2
In modern systems, there's ssh-copy-id for this. But yeah it's not everywhere. In systems that don't have it, I have a similar script like yours, but to mimic the "standard", I call it ssh-copy-id.sh. Name it as you like, but I don't think "loadkey" really sums up the action of appending your public key to the authorized list file on a remote server. So I'd pick something better.

Cats are sure cute creatures, but you don't need one here:


cat ~/.ssh/id_rsa.pub | ssh -2 $host $installcat 



You can use input redirection:

ssh -2 $host $install &lt; ~/.ssh/id_rsa.pub


Lastly, the ssh ... echo hi stuff is repeated twice. It would be better to put it in a function. You can chain the different final echo + exit commands after the function with &amp;&amp; normally.