Bash Script for SSH Key Generation
Posted by: Eric Hansen
I’ve mentioned a good couple of times here on how to set up SSH key authentication, as well as some benefits to it. But, I was always wondering how (and if) I could make it more automated. Then it hit me, there’s always ssh-keygen’s wonderful man pages! A good hour or two later, I’ve come up with two different methods of doing this. One is purely automated (minus asking for the passphrase), and the other has default answers for each prompt.
The (almost) purely automated script can be found here: http://itknowledgeexchange.techtarget.com/itanswers/ssh-key-authentication-generator/ Underneath the cut, you’ll see the less-automated script.
There’s really not a lot to be said about this. The most noticable part of it is the use of stty -echo to disable read from outputting what you type into it (so no one can visibly see the passphrase you enter). Other than that, it’s all pretty self explanatory.
#!/bin/bash
echo "This script is to e used for generating SSH certificates only."
read -p "Bits (default: 8192): " bits
if [ -z "$bits" ]; then
bits=8192
fi
read -p "Encryption Type (default: rsa): " enc
if [ -z "$enc" ]; then
enc="rsa"
fi
read -p "File (default: $HOME/.ssh/id_$enc): " path
if [ -z "$path" ]; then
path="$HOME/.ssh/id_$enc"
fi
if [ -e "$path" ]; then
read -p "$path already exists...delete? (Y/n): " ans
case "$ans" in
N|n)
echo "File must be deleted first."
exit 1
;;
Y|y|*)
rm -rf $path
;;
esac
fi
stty -echo
read -p "Passphrase: " pp
stty echo
if [ "${#pp}" -lt 4 ]; then
echo -e "\nPassphrase must be greater than 4 characters."
exit 1
fi
echo -e -n "\nGenerating a $bits bit $enc SSH key file in $path..."
ssh-keygen -q -b $bits -t $enc -N $pp -f "$path"
if [ -e "$path" ]; then
echo "SUCCESS"
else
echo "FAIL"
fi
exit 0




