Automatically Serve SSH Key (ASS Key)

Here’s a simple shell script to add your SSH key to your user. Remember to replaceĀ YOUR_SSH_KEY_HERE with your public key.

#!/bin/bash
# Adds SSH key to the authorized keys
# Creates missing files and folders if required

sshdir="$HOME/.ssh"
sshkeys="$HOME/.ssh/authorized_keys"
publickey="YOUR_SSH_KEY_HERE"

if [ ! -d "${sshdir}" ]; then
	mkdir ${sshdir}
	touch ${sshkeys}
	chmod 700 ${sshdir}
	chmod 600 ${sshkeys}
	if [ ! $(grep -q "${publickey}" "${sshkeys}") ]; then
		echo "${publickey}" >> ${sshkeys}
	else
		echo "Key already in authorized_keys!"
	fi
else
	echo ".ssh already exists!"

	if [ ! -f "${sshkeys}" ]; then
		touch ${sshkeys}
		chmod 600 ${sshkeys}
	else
		echo "authorized_keys already exists!"

		if [ ! $(grep -q "${publickey}" "${sshkeys}") ]; then
			echo "${publickey}" >> ${sshkeys}
		else
			echo "Key already in authorized_keys!"
		fi
	fi
fi