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: 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

 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.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

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: