Skip to content

Instantly share code, notes, and snippets.

@clcollins
Created March 14, 2016 15:54
Show Gist options
  • Save clcollins/1a87fd275c498da0309b to your computer and use it in GitHub Desktop.
Save clcollins/1a87fd275c498da0309b to your computer and use it in GitHub Desktop.
Generate throwaway SSH key pairs for automated ... things.
#!/bin/bash
error () {
local msg="${1}"
echo "${msg}"
exit 1
}
make_tempdir () {
local dir="${1}"
# Create a temp dir, and make this user the only owner
(umask 077 && mkdir -p $dir)
}
create_key () {
local key_type='rsa'
local num_bits='4096'
local out_file="${1}/our_key"
local comment="${@:2}"
# Generate without a passphrase
(umask 077 && ssh-keygen -q -N "" -t $key_type -b $num_bits -f ${out_file} $comment)
}
print_key () {
local key="$1/our_key"
local pub="${key}.pub"
if ! cat $key || ! cat $pub ; then
return 1
fi
}
delete_key () {
local tmp_dir="$1"
local key="${tmp_dir}/our_key"
local pub="${key}.pub"
if ! rm $key || ! rm $pub ; then
my_error="Unable to delete key pair in ${tmp_dir}/${our_tmp_dir}!"
fi
}
main () {
local tmp_dir="/tmp"
local our_tmp_dir="$(pwgen)"
if [[ ! -z "$1" ]] ; then
local comment="-C ${1}"
fi
make_tempdir "${tmp_dir}/${our_tmp_dir}"
if ! create_key "${tmp_dir}/${our_tmp_dir}" "${comment}" ; then
error "Unable to create SSH key"
fi
if ! print_key "${tmp_dir}/${our_tmp_dir}" ; then
echo "Unable to print key(s). Attempting to delete it, to be safe"
fi
# We either printed or did not. Either way, delete the keys if possible.
delete_key "${tmp_dir}/${our_tmp_dir}"
rmdir $our_tmp_dir
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment