Skip to content

Instantly share code, notes, and snippets.

@keith-bennett-gbg
Created January 20, 2017 21:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keith-bennett-gbg/b6aa9af5be13f6dbe257399e6191000b to your computer and use it in GitHub Desktop.
Save keith-bennett-gbg/b6aa9af5be13f6dbe257399e6191000b to your computer and use it in GitHub Desktop.
sshi() {
if [ $# -eq 0 ]
then
ssh
return $?
fi
username=$(echo -n "${1}" | grep -oP "^.*@")
if [ "${username}" == "" ]
then
username=$(whoami)
else
# remove @
username=${username:0:${#username}-1}
if [ "${username}" == "" ]
then
username=$(whoami)
fi
fi
target_host=$(echo -n "${1}" | grep -oP "@.*$")
if [ "${target_host}" == "@" ]
then
target_host=$(hostname)
elif [ "${target_host:0:1}" == "@" ]
then
# remove @
target_host="${target_host:1}"
elif [ "${target_host}" == "" ]
then
target_host="${1}"
fi
key=""
if [ -f "${HOME}/.ssh/$(whoami)-$(hostname)-${username}-${target_host}.id_rsa" ]
then
key="${HOME}/.ssh/$(whoami)-$(hostname)-${username}-${target_host}.id_rsa"
elif [ -f "${HOME}/.ssh/${username}-${target_host}.id_rsa" ]
then
key="${HOME}/.ssh/${username}-${target_host}.id_rsa"
elif [ -f "${HOME}/.ssh/$(whoami)-$(hostname)-${username}-$(echo ${target_host} | sed -r 's/[0-9]+$//g').id_rsa" ]
then
key="${HOME}/.ssh/$(whoami)-$(hostname)-${username}-$(echo ${target_host} | sed -r 's/[0-9]+$//g').id_rsa"
else
>&2 echo "Cannot find keyfile for target ${1}: ${username}@${target_host}"
return 1
fi
ssh -i "${key}" "${username}@${target_host}" "${@:2}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment