Bash Script for Automatic Creation and Generation of Public Private Key for Linux Server Login

Wrote this quick blurb so I never have to do this process again.

The general idea is to take the output that is created on the screen, copy and paste it to a file somewhere on your computer, and either use it as is with your environment ssh configuration or convert it to a *.ppk for Putty.

What the script does is the following:

  1. Create the .ssh directory as the user you are currently logged in as (if it doesn’t already exist)
  2. Set necessary permissions on the directory (if it isn’t already set)
  3. Create the “authorized_keys” file (if it doesn’t already exist)
  4. Generate the Public/Private Pair
  5. Append the thumbprint to the “authorized_keys” file
  6. Output the private key for copying to Standard Out
  7. Delete the generated files for the Public/Private pair

After copying the key from the terminal screen you’ll paste it into a text file and either use it as is or convert it to a *.ppk for usage in Putty.

KEY_OWNER="Cody Garrett"
KEY_NAME="automatic.key"
KEY_NAME_PUB="$KEY_NAME.pub"
mkdir ~/.ssh
chmod 0700 ~/.ssh
touch ~/.ssh/authorized_keys
chmod 0644 ~/.ssh/authorized_keys
ssh-keygen -t rsa -b 4096 -C "$KEY_OWNER" -f "$KEY_NAME" -P ""
cat "$KEY_NAME.pub" >> ~/.ssh/authorized_keys
echo "Very Important!"
echo "The next screen that will come up will display the key needed for login."
echo "You must copy this in it's entirety in order to login using what was setup in the previous commands."
echo ""
echo "Press enter to continue..."
read
clear
echo ""
echo "##################"
echo "## Private Key: ##"
echo "##################"
echo ""
cat $KEY_NAME
echo ""
echo "###########################"
echo "## Authorized Key Entry: ##"
echo "###########################"
echo ""
cat $KEY_NAME_PUB
echo ""
rm -f "$KEY_NAME" "$KEY_NAME_PUB"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s