Autocomplete SSH Hostnames

There are plenty of SSH autocomplete (or command-line completion) scripts available on the web, but I found most don’t go far enough — they usually just parse the ~/.ssh/known_hosts, ignoring the ~/.ssh/config and /etc/hosts files. Some of these scripts also generate a static autocomplete list at login, and can’t include new hostnames added during the session. The following script uses a function call to autocomplete hostnames dynamically, and fetches hostnames from the ~/.ssh/known_hosts, ~/.ssh/config and system-wide /etc/hosts file.

There are several places to execute an autocomplete script — my personal preference (if you have root access) is a script located in /etc/profile.d/complete-hosts.sh. Most Linux distributions have an /etc/profile that sources additional files under /etc/profile.d/, and in those that don’t (like Mac OS X for example), you can include the following code at the end of your /etc/profile script [credit: CentOS 6.3].

for i in `ls -1 /etc/profile.d/*.sh` ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
            . $i
        else
            . $i >/dev/null 2>&1
        fi
    fi
done

An alternative (for those who can’t or won’t modify /etc/profile) might be to include the following complete-hosts.sh script in your ~/.bashrc file instead.

# /etc/profile.d/complete-hosts.sh
# Autocomplete Hostnames for SSH etc.
# by Jean-Sebastien Morisset (https://surniaulula.com/)
_complete_hosts () {
	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"
	host_list=`{ 
		for c in /etc/ssh_config /etc/ssh/ssh_config ~/.ssh/config
		do [ -r $c ] && sed -n -e 's/^Host[[:space:]]//p' -e 's/^[[:space:]]*HostName[[:space:]]//p' $c
		done
		for k in /etc/ssh_known_hosts /etc/ssh/ssh_known_hosts ~/.ssh/known_hosts
		do [ -r $k ] && egrep -v '^[#\[]' $k|cut -f 1 -d ' '|sed -e 's/[,:].*//g'
		done
		sed -n -e 's/^[0-9][0-9\.]*//p' /etc/hosts; }|tr ' ' '\n'|grep -v '*'`
	COMPREPLY=( $(compgen -W "${host_list}" -- $cur))
	return 0
}
complete -F _complete_hosts ssh
complete -F _complete_hosts host

Download the complete-hosts.sh script.

Find this content useful? Share it with your friends!