Advanced SSH management

You too can be an SSH guru through the following tips.

SSH public host key management

Simply add the following to your shell startup files (~/.zshrc, or ~/.bashrc) in your web hosting user account.


function ssh_host_add () {

        local hostname=$1
        local server
        local tmp

        pushd $CFINPUTS_SSH; svn up ssh_known_hosts2
        if ! [ -r ssh_known_hosts2 ]
                echo "ERROR: Unable to read ssh_known_hosts2" 1>&2
                return 1

        tmp=$(host -t A $hostname)
        if [ $? -ne 0 ]
                echo "ERROR: Unable to resolve '$hostname'." 1>&2
                return 2

        server=$(echo "$hostname $tmp" | awk '{print $1","$2","$5}')
        if grep -q "$server" ssh_known_hosts2
                echo "ERROR: Entry for '$server' already exists!" 1>&2
                return 3

        echo $server | ssh-keyscan -t rsa,dsa -f - >> ssh_known_hosts2

        svn ci -m "$hostname SSH key" ssh_known_hosts2

        # Rebuild ssh configuration.
        [ -f $HOME/.ssh/Makefile ] && make -C $HOME/.ssh

Then as servers are built, simply run ssh_host_add SERVER_NAME (NB: Don't specify the domain name)

Configuration file management

Create the file $HOME/.ssh/Makefile (be sure to use tabs instead of spaces) with the following contents:

.PHONY: known_hosts_anchor
TARGETS=known_hosts config

all: $(TARGETS)

config: $(wildcard config_*) config.default
        -chmod 600 [email protected]
        cat $^ > [email protected]
        chmod 400 [email protected]

known_hosts: known_hosts_anchor $(filter-out known_hosts_anchor, $(wildcard known_hosts_*))
        -chmod 600 [email protected]
        cat $^ > [email protected]
        chmod 400 [email protected]

# Synchronise from subversion.
        (cd $(CFINPUTS); svn up data/common/etc/ssh/ssh_known_hosts2)
        cp $(CFINPUTS)/data/common/etc/ssh/ssh_known_hosts2 [email protected]

        rm -f $(TARGETS)

Inside your config.default place:

### Restrictive defaults.
Host *
BatchMode no
CheckHostIP yes
Compression yes
CompressionLevel 9
ConnectionAttempts 1
FallBackToRsh no
ForwardAgent no
ForwardX11 no
GatewayPorts no
KeepAlive yes
PasswordAuthentication no
Protocol 2
RhostsAuthentication no
RhostsRSAAuthentication no
SkeyAuthentication no
StrictHostKeyChecking yes
UsePrivilegedPort no
UseRsh no
User root

See also Faster SSH Logins for some additional voodoo.

Place any manually managed known_hosts content in known_hosts_SUFFIX. This will now let you manage common ssh data between multiple machines easily with simple uses of rsync and make.