Skip to content

Instantly share code, notes, and snippets.

@alxf
Created May 14, 2012 09:46
Show Gist options
  • Save alxf/2692990 to your computer and use it in GitHub Desktop.
Save alxf/2692990 to your computer and use it in GitHub Desktop.
Read hosts in ssh client configuration.
#!/bin/sh
# - ssh-lookup -
#
# This script read configuration file for ssh client. Without argument it list
# all hosts entries in the file. With host as argument, it print the real address
# for this entry.
#
# $ ssh-lookup.sh
# host1.domain.tld
# host2.domain.tld
# ...
#
# compare old and new script version:
# - old script [ real 0m0.969s | user 0m1.208s | sys 0m0.468s ]
# - awk script [ real 0m0.009s | user 0m0.008s | sys 0m0.000s ]
#
# $ ssh-lookup.sh host1.domain.tld
# host1.domain.tld => www@www.domain.tld:2212
#
# or with ProxyCommand (ssh other.domain.tld nc -q 1 www.domain.tld 22):
# $ ssh-lookup.sh host2.domain.tld
# host2.domain.tld => www@www.domain.tld:2212 via other.domain.tld:22
#
if [ $# -eq 0 ]; then
exec awk '
BEGIN {
count = 0
}
/^[Hh]ost/ {
count += 1
print $2
}
END {
printf "\n%d item(s)\n", count
}' $HOME/.ssh/config
else
for host in $@; do
awk --assign arg="$host" '
BEGIN {
proceed = 0
hostname = arg
port = 22
user = ENVIRON["USER"]
}
/^[Hh]ost / {
if (arg == $2) {
proceed = 1
} else {
if (proceed == 1) {
proceed = 0
}
}
}
/[Hh]ostname/ {
if (proceed == 1) {
hostname = $2
}
}
/[Uu]ser/ {
if (proceed == 1) {
user = $2
}
}
/[Pp]ort/ {
if (proceed == 1) {
port = $2
}
}
/[Pp]roxy[Cc]ommand/ {
if (proceed == 1) {
phost = $3
proxy = $7":"$8
}
}
END {
if (proxy == "") {
print arg" => "user"@"hostname":"port
} else {
print arg" => "user"@"proxy" via "phost":"port
}
}' $HOME/.ssh/config
done
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment