Skip to content

Instantly share code, notes, and snippets.

@vdemeester
Created January 23, 2012 21:34
Show Gist options
  • Save vdemeester/1665642 to your computer and use it in GitHub Desktop.
Save vdemeester/1665642 to your computer and use it in GitHub Desktop.
An ssh wrapper
#!/bin/sh
# ssh-wrapper
# The main job of this wrapper is to load ssh-keys if not loaded
SELF=$(basename $0)
warn() {
echo "$(tput setaf 1)>$(tput bold)>$(tput sgr0) $1"
}
command -v ssh >/dev/null || {
echo "$SELF: Original ssh command no found..."
exit 1
}
# If no agent are running, there is nothing to do
if test -n "$SSH_AGENT_PID" && test -n "$SSH_AUTH_SOCK"; then
added_keys=$(ssh-add -l)
for pub_key in $HOME/.ssh/*.pub; do
private_key=$(echo $pub_key | sed 's/.pub//g')
# Get the fingerprint
#line="$(ssh-keygen -l -f $pub_key | sed 's/.pub//g')" # did it work ?
line="$(ssh-keygen -l -f $pub_key | awk '{ print $2 }')"
is_added=$(expr "$added_keys" : ".*$line.*")
if test $is_added -eq 0; then
# We have to add the key to the agent
ssh-add $private_key
fi
done
fi
# Parse .ssh/config in search of information.
# Let's give an example, let say I have the following .ssh/config
#
# Host foo
# User vincent
# IdentifyFile ~/.ssh/id_rsa
# Host bar
# User toto
# IdentifyFile ~/.ssh/id_rsa
# #-Option: TERM=xterm
# #-Option: ENCODING=ISO-8859-15
# Host foobar
# User titi
# #-Option: LANG=C
# #-Option: LC_MESSAGES=C
#
# If I want to connect to foobar, I want to use LANG=C and LC_MESSAGES=C when
# running ssh (or else). It run eval by default (something like a local export).
# If it contains ENCODING, this will try to run luit if present, and needed…
host=$1
pre_cmd=""
post_cmd=""
# Then some hacking to get commented line from config file
ssh_config=$(awk 'BEGIN \
{ RS = "Host"; FS = "#" } \
{ \
if ($1 ~ /'$host'/ && $1 !~ /ProxyCommand(.*)'$host'/) print }' $HOME/.ssh/config)
# ssh_config variable now contains the related Host config present in .ssh/config
for elt in $(echo $ssh_config | grep "#-"); do
var=$(echo $elt | awk 'BEGIN { FS=":" } { print $2 }')
if test $(expr "$var" : "ENCODING") -gt 0; then
# ENCODING is present, let's run luit if present (and needed)
encoding=$(echo $var | awk 'BEGIN { FS="=" } {print $2}')
if ! locale | grep -q "$encoding"; then
# the encoding requested is not the same
pre_cmd="luit -p -encoding $encoding"
enc_color="$(tput setaf 5)"
reset="$(tput sgr0)"
cenc_color="$(tput setaf 2)"
warn "Using $(tput sgr 0 1)luit${reset} to convert ${cenc_color}UTF-8${reset} to ${enc_color}$encoding${reset}"
fi
continue
fi
eval $var
done
$pre_cmd ssh $@
echo "$(tput setaf 2)<$(tput bold)<$(tput sgr0) Back on track (ssh $@)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment