SSH on a Mac
After vim, the program I use the most on my mac is ssh. And though modern cloud architectures are taking us further and further away from direct interaction with the host OS, most people still have something that runs right on the server, and most people still use ssh for getting that kind of work done.
Here are some tips that I have saved me time when using ssh.
Custom Nameservers (mac only)
Take advantage of /etc/resolver/*. Files placed in here will have their names used as url patterns for which a match will mean the use of a custom nameserver.
Example:
File: /etc/resolver/lab
nameserver 192.168.1.220This means that I’ll use the DNS running on 192.168.1.220 to resolve the ip address of any host that uses the extension .lab. So if I have a web server running at myweb.lab and that name myweb is mapped to some ip on my DNS server on 192.168.1.220, all I have to do is I slap the url in Chrome and load it up and my OS will take care of the rest.
Host pattern matching in SSH Config File
Say you have a bunch of servers that use some naming convention in their domain name, like say they all end with “.lab”, and also say
they all have the same generic user, say admin, then you can skip appending admin@ to your hostnames and just do this:
File: ~/.ssh/config
Host +.lab
User adminBy the way, there are many more awesome features that ssh/config provides, I’m just mentioning the ones of which I make the heaviest use.
SSH Host Autocomplete
In my opinion, this is the biggest thing you can do to improve your ssh experience.
In my .bash_profile I source in an ssh_autocomplete script, here’s what that looks like:
File: ssh_autocomplete
#!/bin/bash
_ssh()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
# combine our ssh config and known_hosts file for ssh autocomplete
opts="$(grep '^Host' ~/.ssh/config | grep -v '[?*]' | cut -d ' ' -f 2-) $(echo `cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`;)"
COMPREPLY=( $(compgen -W "$opts" -- ${cur}) )
return 0
}
complete -F _ssh sshAs you can see here, we use both the ~/.ssh/known_hosts and ~/.ssh/config files to source autocomplete options.
Also note the importance of putting this in a function which will be evaluated each time you use ssh and then hit tab. If the list is exported once at the time of the .bash_profile being run then you will need to re-source the file to get new hosts from either source file.