Created
June 7, 2014 04:17
-
-
Save daringer/f6a9786b8129b4e7ecae to your computer and use it in GitHub Desktop.
generate a bash alias for each (exact) host line from .ssh/config
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 | |
## | |
## create an alias for each unambigous host entry in ${HOME}/.ssh/config | |
## | |
## instead of using "ssh myhostname" you can simply use "myhostname" to | |
## establish a ssh-connection to the host! | |
## | |
## You most likely have to change CACHE_FN to point somewhere, | |
## where you want to store the cache | |
## | |
## Usage: | |
## $ source ssh_aliases.sh | |
## | |
## | |
## Author: Markus Meissner <coder@safemailbox.de> | |
## LICENSE: Apache License | |
## | |
# | |
# CONFIGURE THESE: | |
# | |
CACHE_FN="${HOME}/.bashrc.d/.cache_ssh_aliases.sh" | |
SSH_BINARY="/usr/bin/ssh" | |
SSH_CONFIG_FN="${HOME}/.ssh/config" | |
function __collect_ssh_aliases { | |
read_entry=0 | |
alias_name="" | |
target_port="" | |
target_host="" | |
target_user="" | |
OLDIFS=$IFS; | |
IFS=$'\n'; | |
for line in `cat ${SSH_CONFIG_FN}`; do | |
## ignore hosts with wildcards ?/* | |
## and dots (foo.bar) | |
if expr match "${line}" 'host' > /dev/null 2>&1; then | |
# first write old, if available | |
if [[ "$alias_name" != "" ]]; then | |
echo "alias ${alias_name}=\"${SSH_BINARY} ${target_port} ${target_user}${target_host}\"" >> ${CACHE_FN} | |
alias_name="" | |
target_port="" | |
target_user="" | |
target_host="" | |
fi | |
read_entry="1" | |
alias_name=`echo "${line}" | cut -d " " -f 2` | |
fi | |
if (expr index "$line" '\?' > /dev/null 2>&1) then | |
read_entry="0" | |
alias_name="" | |
fi | |
# skip until next "host", if wildcards were found... | |
[[ "$read_entry" = "0" ]] && continue | |
if expr match "${line}" "Hostname" > /dev/null 2>&1; then | |
target_host=`echo "${line}" | cut -d " " -f 2` | |
fi | |
if expr match "${line}" "user" > /dev/null 2>&1; then | |
target_user="`echo "${line}" | cut -d " " -f 2`@" | |
fi | |
if expr match "${line}" "port" > /dev/null 2>&1; then | |
target_port="-p `echo "${line}" | cut -d " " -f 2`" | |
fi | |
done | |
IFS=$OLDIFS | |
} | |
## rebuild cache only, | |
## if ${SSH_CONFIG_FN} is newer than the cache | |
if [[ ! -r "${CACHE_FN}" ]] || [[ "${SSH_CONFIG_FN}" -nt "${CACHE_FN}" ]] | |
then | |
rm -f ${CACHE_FN} | |
__collect_ssh_aliases | |
fi | |
source ${CACHE_FN} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment