I.T. Security and Linux Administration

Oct 12 2011   1:00PM GMT

Bash Script for SSH Key Generation

Eric Hansen Eric Hansen Profile: 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: https://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.


echo "This script is to e used for generating SSH certificates only."

read -p "Bits (default: 8192): " bits

if [ -z "$bits" ]; then

read -p "Encryption Type (default: rsa): " enc

if [ -z "$enc" ]; then

read -p "File (default: $HOME/.ssh/id_$enc): " path

if [ -z "$path" ]; then

if [ -e "$path" ]; then
	read -p "$path already exists...delete? (Y/n): " ans

	case "$ans" in
			echo "File must be deleted first."
			exit 1

			rm -rf $path

stty -echo
read -p "Passphrase: " pp
stty echo

if [ "${#pp}" -lt 4 ]; then
	echo -e "\nPassphrase must be greater than 4 characters."
	exit 1

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"
	echo "FAIL"

exit 0

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: