How To Automate Connect, Generate And Add An SSH Key To A Server

Mark Caggiano
3 min readMar 4, 2022

This is probably the last article you will read about connecting, generating and adding ssh keys to a server.

Let’s write a script that will do it for us.

First let’s generate the ssh key. Open a terminal and put this:

$ ssh-keygen -t rsa -b 4096

This will generate a ssh key, but we want to automate this so let’s write a script for it:

#!/bin/bash
# genkey.sh
SSH_DIR="$HOME/.ssh"[ -z "$1" ] && abort "[!] Missing Key Name"echo "[+] Generating Key In: $SSH_DIR/$1"ssh-keygen -t rsa -b 4096 -f "$SSH_DIR/$1" -q -N ""# chmod +x genkey.sh to make it executable

This script will save the ssh key in $HOME/.ssh with the name you provided like:

$ ./genkey.sh my-key
[+] Generating Key In: /home/user/.ssh/my-key

With a simple script we made it easier and faster to generate an ssh key. So let’s do the same for adding an ssh key to a server.

#!/bin/bash
# addkey.sh
SSH_DIR="$HOME/.ssh"
SSH_ADDED_SERVERS="$HOME/.ssh-added-servers"
abort() {
echo -e "$1"
exit 1
}
[ -z "$1" ] && abort "[!] Missing Server User"
[ -z "$2" ] && abort "[!] Missing Server Ip Or Domain"
[ -z "$3" ] && abort "[!] Missing Key Name"
user="$1"
server="$2"
key_name="$3"
# Check If key doesn't not exist
if [ ! -f "$SSH_DIR/$key_name.pub" ]; then
abort "[!] \"$SSH_DIR/$key_name.pub\" does not exist; exit"fi# Copy Key to user@server
addcmd="ssh-copy-id -f -i $SSH_DIR/$key_name $user@$server"
print "[+] Running '$addcmd'"output=`$addcmd`# You could add a verbose flag to silence output
echo "$output"
[[ "$output" == *"ERROR"* ]] && abort "[!] Error Running ssh-copy-id"
[[ "$output" == *"Name or service not known"* ]] && abort "[!] Error Running ssh-copy-id"
# OPTIONAL: Let's Keep Track of Added…

--

--