Last active
March 2, 2020 21:13
-
-
Save craSH/59b9f1650c0433e19bd5 to your computer and use it in GitHub Desktop.
Handy helper script to generate new SSH keys in a predictable format, provide the needed ssh_config stanza to use them, and automatically upload them to the remote server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Handy helper script to generate new SSH keys in a predictable format, | |
# provide the needed ssh_config stanza to use them, and automatically | |
# upload them to the remote server. | |
# | |
# Copyleft 2014 Ian Gallagher <crash@neg9.org> | |
if [ -z "$1" ]; then | |
echo "Usage: $0 <remote_host> [key_type] [key_size]" >&2 | |
exit 1 | |
fi | |
host="$1" | |
type="$2" | |
size="$3" | |
if [[ -z $type ]]; then | |
type="ed25519" | |
fi | |
if [[ -z $size ]]; then | |
size="1000" | |
fi | |
remote_host=$(echo "$host" | tr 'A-Z' 'a-z') | |
local_host=$(hostname -s | tr 'A-Z' 'a-z') | |
year_date=$(date '+%Y-%m') | |
filename="id_${type}-${USER}-${remote_host}" | |
comment="${USER}-${local_host}-${remote_host}-${year_date}" | |
private_key="~/.ssh/${filename}" | |
public_key="${private_key}.pub" | |
# Create files with 0600 permissions | |
umask 077 | |
# Use eval here so we can use tilde (~) in the variable and display it w/o expanding. eval expands for execution. | |
eval "ssh-keygen -t $type -b $size -f $private_key -C $comment" | |
if [ $? -eq 0 ]; then | |
upload_key="ssh $remote_host 'cat >> .ssh/authorized_keys' < $public_key" | |
echo "ssh_config entry:" | |
echo "Host $remote_host" | |
echo -e "\tIdentityFile $private_key" | |
echo | |
echo "Upload key to remote server: $upload_key" | |
echo -n "Run above command now? (y/n): " | |
read doit | |
if [ "y" == "$doit" ]; then | |
sh -c "$upload_key" | |
fi | |
exit 0 | |
else | |
echo "Failed to create new SSH keypair." >&2 | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote and tested this on OSX, but I think it should work on any *nix system. The date command may need tweaking in some situations though.