Generate ssh hosts

Do you often use ssh hosts and hate having to write them over and over again full of errors?

Just add this piece of code by my colleagues Dave Lens and Jan Moesen to your .bash_profile:

# creates an SSH key and uploads it to the given host
configure_ssh_host()
{
	username=$1
	hostname=$2
	identifier=$3
	keyfile=$4
	
	if [[ "$identifier" == "" ]] || [[ "$username" == "" ]] || [[ "$hostname" == "" ]] || [[ "$keyfile" == "" ]]
	then
		echo "usage: configure_ssh_host    "
	else
		ssh-keygen -f ~/.ssh/$keyfile.id_rsa -C "$USER $(date +'%Y/%m%/%d %H:%M:%S')"
		
		echo -e "Host $identifier\n\tHostName $hostname\n\tUser $username\n\tIdentityFile ~/.ssh/$keyfile.id_rsa" >> ~/.ssh/config
		
		ssh $identifier 'mkdir -p .ssh && cat >> ~/.ssh/authorized_keys' < ~/.ssh/$keyfile.id_rsa.pub
		
		tput bold; ssh -o PasswordAuthentication=no $identifier true && { tput setaf 2; echo 'Success!'; } || { tput setaf 1; echo 'Failure'; }; tput sgr0
		
		ssh_load_autocomplete
	fi
}

# adds ~/.ssh/config to the ssh autocomplete
ssh_load_autocomplete()
{
	complete -W "$(awk '/^\s*Host\s*/ { sub(/^\s*Host /, ""); print; }' ~/.ssh/config)" ssh
}

# adds ~/.ssh/config to the ssh autocomplete
ssh_load_autocomplete

It doesn't only generate your ssh host, but also adds autocomplete for them. So whenever you start typing "ssh" and press Tab, it will autocomplete with every ssh host you have configured inside your ~/.ssh/config file so you don't even have to remember what name you gave that host a year ago.

If you don't want the autocomplete part, you're free to leave it out of course :) have fun!