Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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