nixos/scripts/generate_ssh_keys.sh

61 lines
1.5 KiB
Bash
Executable File

#!/usr/bin/env bash
#
# usage: ./generate_ssh_keys.sh --type "host" --username "root" --hostname "hostname"
#
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
--type)
type="$2"
shift # past argument
shift # past value
;;
--username)
username="$2"
shift # past argument
shift # past value
;;
--hostname)
hostname="$2"
shift # past argument
shift # past value
;;
*) # unknown option
echo "Unknown option $1"
exit 1
;;
esac
done
if [[ -z "$type" || -z "$username" || -z "$hostname" ]]; then
echo "All arguments are not specified."
exit 1
fi
if [[ $type != "user" && $type != "host" ]]; then
echo "Invalid type. It should be either 'user' or 'host'"
exit 1
fi
HOST_KEY_DIR="$HOME/keys/hosts/$hostname"
USER_KEY_DIR="$HOME/keys/users/$username"
mkdir -p "$HOST_KEY_DIR" "$USER_KEY_DIR"
if [[ $type == "user" ]]; then
keyfile="id_ed25519"
name="$username"
else
keyfile="ssh_host_ed25519_key"
name="root@$hostname"
fi
keydir=$([[ $type == "user" ]] && echo "$USER_KEY_DIR" || echo "$HOST_KEY_DIR")
fullpath="$keydir/$keyfile"
overwrite=""
[ -f "$fullpath" ] && read -p "Target key '$fullpath' already exists, would you like to overwrite it? (yes|no) " overwrite
[ "$overwrite" = "yes" ] || [ -z "$overwrite" ] && ssh-keygen -t ed25519 -f "$fullpath" -C "$name" -N ""