Bits and Bytes from Johnny Mac

Friday, October 14, 2005

SSH Command Completion

Fedora Core 4 (and others) ship with some sort of command completion for ssh. I had heard about it but never seen it work until recently. I work in a small office, and we were using /etc/hosts instead of DNS. I recently setup BIND on an internal server, but I needed to make it use a third-level domain. I didn't want to maintain an independent authoritative DNS server that would have to include our outward facing servers, but BIND is probably a whole post unto itself.

It turns out that ssh command completion only works on /etc/hosts. Yeah, that's about useful. So we lengthened our FQDNs and lost command completion. Cool. So every ssh command line is 30 characters.

Unitl now.

I wrote a new command completion function for ssh that operates on ~/.ssh/known_hosts. It works correctly with no user name or with the user@host syntax.

Enjoy.


function ssh_complete
{
local c=${COMP_WORDS[COMP_CWORD]};
local commands=`cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed 's/,/ /g'`

if [ 1 -eq `echo $c | grep -c '@'` ]; then
c=`echo $c | sed 's/^.*@/@/'`
commands=`echo @$commands | sed 's/ / @/g'`
fi

if [ -z "$c" ]; then
COMPREPLY=($commands)
else
COMPREPLY=(`echo $commands | sed 's/ /\n/g' | grep ^$c`)
fi
}


Of course this must be followed by the command to associate the 'ssh' command with the 'ssh_complete' function:

complete -o default -F ssh_complete ssh

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home