Wi-Fizzle.com - Putting the fizzle in Wi-Fi since 2005 .. (yes, this was a poor choice for a domain name)

<div class="news_item">#251<div class="news_title">HOWTO: Get Bash SSH Hostname Tab Completion

Posted by dandriff on Thursday June 05, 2008@10:03AM

It is possible to get Bash SSH tab completion for hosts contained in your ~/.ssh/known_hosts file by performing the steps outlined below (this works great for me with Ubuntu 7.04 :). This also will work for SCP hostname automatic tab-completion.

HOWTO: Setup Bash SSH automatic tab completion for a single user-

  • Make a backup of your ~/.ssh/known_hosts file (so that you can revert to it if you decide that you want to go back to hashed hostnames):

 cp -a ~/.ssh/known_hosts ~/.ssh/.known_hosts

  • Clear the ~/.ssh/known_hosts file:

 echo '' > ~/.ssh/known_hosts

  • Create or update ~/.ssh/config and disable hostname hashing in the known_hosts file:

 HashKnownHosts no

  • To enable hostname tab auto-completion for both SSH and SCP, append the following lines to ~/.bashrc or ~/.bash_profile:

<pre>if [ -r ~/.ssh/known_hosts ] || [ -r /etc/ssh/ssh_known_hosts ]; then complete -W "$(echo `if [ -r ~/.ssh/known_hosts ]; then cat ~/.ssh/known_hosts; fi && if [ -r /etc/ssh/ssh_known_hosts ]; then cat /etc/ssh/ssh_known_hosts; fi | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" ssh complete -W "$(echo `if [ -r ~/.ssh/known_hosts ]; then cat ~/.ssh/known_hosts; fi && if [ -r /etc/ssh/ssh_known_hosts ]; then cat /etc/ssh/ssh_known_hosts; fi | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" scp fi</pre>

  • Or alternate option 1: enable hostname tab auto-completion for only SSH, append the following lines to ~/.bashrc or ~/.bash_profile:

<pre>if [ -r ~/.ssh/known_hosts ] || [ -r /etc/ssh/ssh_known_hosts ]; then complete -W "$(echo `if [ -r ~/.ssh/known_hosts ]; then cat ~/.ssh/known_hosts; fi && if [ -r /etc/ssh/ssh_known_hosts ]; then cat /etc/ssh/ssh_known_hosts; fi | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" ssh fi</pre>

  • Or alternate option 2: enable hostname tab auto-completion for only SCP, a, append the following lines to ~/.bashrc or ~/.bash_profile:

<pre>if [ -r ~/.ssh/known_hosts ] || [ -r /etc/ssh/ssh_known_hosts ]; then complete -W "$(echo `if [ -r ~/.ssh/known_hosts ]; then cat ~/.ssh/known_hosts; fi && if [ -r /etc/ssh/ssh_known_hosts ]; then cat /etc/ssh/ssh_known_hosts; fi | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)" scp fi</pre>

The next time you open a new terminal window or connect via SSH to that user account, you will be able to use the tab auto-complete on hostnames for SSH and/or SCP.

** Note: you will have to re-approve the RSA key fingerprint on machines you connect to via SSH since you have your known_hosts file. **

References: