Last active
April 6, 2022 02:55
-
-
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
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
#!/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 [email protected] | |
# 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