Member-only story
How To Automate Connect, Generate And Add An SSH Key To A Server
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.shSSH_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.shSSH_DIR="$HOME/.ssh"
SSH_ADDED_SERVERS="$HOME/.ssh-added-servers"abort() {
echo -e "$1"
exit 1
}