Skip to content

Instantly share code, notes, and snippets.

@craSH
Last active March 2, 2020 21:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save craSH/59b9f1650c0433e19bd5 to your computer and use it in GitHub Desktop.
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.
#!/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
@craSH
Copy link
Author

craSH commented May 19, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment