How To Create SSH Keys And Use Them

How To Create SSH Keys And Use Them

SSH keys allow you to remote into a box without needing a password (if the server configuration supports it, which it typically does). This is a short post demonstrating how to create ssh-keys and use them.

Script First

First, a script create ssh keys and add them to the ssh keyring:


if [[ -z $1 ]]; then
  printf "name required for ssh key\n"
  exit 1


function is_ssh_key_added()
  if [[ `ssh-add -l | grep $SSH_KEY | wc -l` -ge 1 ]]; then
    return 1
    return 0

if [[ ! -e $SSH_KEY ]]; then
  printf "SSH key %s is missing\n" "$SSH_KEY"
  printf "The ssh key will be created in ~/.ssh/.\n"
  ssh-keygen -f $SSH_KEY
  printf "Created ssh key %s\n" $SSH_KEY


if [[ $? = 0 ]]; then
  ssh-add $SSH_KEY
  printf "SSH key ready for use\n"

What Needs to Happen

Basically you run ssh-keygen, set a passphrase, then use ssh-add to import the key into your keyring. This is an essential part of remote scripting as other posts on this site will demonstrate.

Generate the Key

First step is to generate a ssh-key.

ssh-keygen -f ~/foo.id_rsa

Enter your passphrase and verify the key was created. Sometime ssh can incorporate some personally identifying information (which the feds can use to bust your ass). Check it out:

cat ~/.ssh/  | awk '{print $3}'

Outputs something like:

> user@host

That third field, what appears to be your username@hostname, is a "Comment" in the lexicon of ssh-keygen. Change it with the -C flag like so:

ssh-keygen -f ~/.ssh/foo.id_rsa -C FOFF

Import the Key

Then, import the ssh-key

ssh-add ~/.ssh/foo.id_rsa

Configure SSH

Configure ssh to use that specific key for a specific host or hosts.

For example, edit '~/.ssh/config and add the following:

Host 172.16.*.*
  User myuser
  IdentityFile ~/.ssh/foo.id_rsa

Which will use that foo ssh key for every host in the entire Class B IPv4 subnet.