Skip to content

Instantly share code, notes, and snippets.

@jvhaarst
Last active April 6, 2022 02:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvhaarst/fecc8d404a932bdce69a to your computer and use it in GitHub Desktop.
Save jvhaarst/fecc8d404a932bdce69a to your computer and use it in GitHub Desktop.
Script to create bash aliases for hostnames in ssh config and known_hosts files
#!/bin/bash
# Script to create bash aliases for hostnames in ssh config and known_hosts files
# Original fom http://samrowe.com/wordpress/2008/07/29/bash-ssh-happiness/
# Updated by ja@vanhaarst.net
# Example usage:
# ALIAS_TEMP=$(mktemp);bash ssh_alias.sh | sort -r > $ALIAS_TEMP;source $ALIAS_TEMP;rm $ALIAS_TEMP;alias
set -o errexit # Exit on error
set -o nounset # Exit on use of unset variable
#set -o verbose # Prints shell input lines as they are read.
#set -o xtrace # Print command traces before executing command.
shopt -s extglob # Turn on extended globbing
# Function to check whether input is an integer
isint(){
case $1 in
?([-+])+([0-9]) )
return 0;;
*) return 1;;
esac
}
if [[ -d ~/.ssh ]]; then
# Touch files we expect to exist
if [[ ! -e ~/.ssh/config ]]; then touch ~/.ssh/config; fi
if [[ ! -e ~/.ssh/known_hosts ]]; then touch ~/.ssh/known_hosts; fi
# Parse ~/.ssh/known_hosts and ~/.ssh/config to find unique hosts
for x in $(echo $(sed -e 's/[, ].*//' ~/.ssh/known_hosts; awk '/^Host [^*?]+$/{print $2}' ~/.ssh/config) | tr ' ' '\n' | sort | uniq); do
# Remove the domainname, and leave only the first octet of an IPv6 adress
y=$(echo ${x} | cut -f 1 -d'.' | cut -f 1 -d':')
# you don't want IP addresses for aliases, trust me.
isint "${y}" && continue
# If it's a short-name, move on
#z=${x##*.}
#[[ "${z}" == 'edu' || "${z}" == 'com' || "${z}" == 'net' ]] || continue
# So the above is commented out because you'd be surprised at how much
# you rely on your search path. You should pipe the output of this script to
# sort and your fqdn's will override your shorts.
# Check for existing commands with the same name
type "${y}" > /dev/null 2>&1 && continue
# Return alias command
echo alias "${y}"="'ssh ${x}'"
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment