patternbashMinor
Load SSH key remotely
Viewed 0 times
remotelysshkeyload
Problem
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:
And here is the script:
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> loadkey sol@solarium
Installing Key...
sol@solarium's password:
Checking Key ...
Great!
panabox:~/bin> loadkey sol@solarium
Already Works!
panabox:~/bin>
And here is the script:
#!/bin/bash
if [ "$#" -ne 1 ]
then
echo "Must supply user@hostname: loadkey "
exit 1
fi
host=$1
ssh -2 -o BatchMode=yes $host "echo hi" >& /dev/null && echo Already Works! && exit 0
echo Installing Key...
install="mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat - >> ~/.ssh/authorized_keys && 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" >& /dev/null && echo Great! && exit 0
echo Failed to install key.
exit 2Solution
In modern systems, there's
Cats are sure cute creatures, but you don't need one here:
You can use input redirection:
Lastly, the
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 $installcatYou can use input redirection:
ssh -2 $host $install < ~/.ssh/id_rsa.pubLastly, 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 && normally.Code Snippets
cat ~/.ssh/id_rsa.pub | ssh -2 $host $installcatssh -2 $host $install < ~/.ssh/id_rsa.pubContext
StackExchange Code Review Q#93431, answer score: 9
Revisions (0)
No revisions yet.