SSH Aliases

SSH Aliases

Another little fun tip that I created the other day. I have a cluster of machines, and I log into them as various users. I could type out the whole command to ssh into these various machines, but I'm lazy someone who likes to do things efficiently. Therefore, I wrote a little bash/zsh script to do this.

Here's the bash:


declare -A hosts=(["lab1"]="123.456.789.1" 
                  ["lab2"]="123.456.789.2" 
                  ["lab3"]="123.456.789.3"
                  ...
                  ["lab8"]="123.456.789.8")
                  
for HST in "${!hosts[@]}"
do
  for USR in 'userone' 'usertwo'
  do
    if [ "$USR" == 'userone' ]; then
      alias sa$HST="ssh $USR@${hosts[$HST]}"
    else
      alias sb$HST="ssh $USR@${hosts[$HST]}"
    fi
  done
  alias $HST="echo ${hosts[$HST]}"
done

The equivalent in zsh is:


typeset -A hosts
hosts=("lab1" "123.456.789.1"
       "lab2" "123.456.789.2"
       "lab3" "123.456.789.3"
       ...
       "lab9" "123.456.789.9")
for KEY HST in "${(@kv)hosts}"; do
  for USR in 'userone' 'usertwo'; do
    if [ "$USR" = 'userone' ]; do
      alias sa$KEY="ssh $USR@$HST"
    else
      alias sb$KEY="ssh $USR@$HST"
    fi
  done
  alias $KEY="echo $HST"
done

This gives me aliases like this:


salab1='ssh userone@123.456.789.1'
sblab1='ssh usertwo@123.456.789.1'
salab2='ssh userone@123.456.789.2'
sblab2='ssh usertwo@123.456.789.2'
...
salab9='ssh userone@123.456.789.9'
sblab9='ssh usertwo@123.456.789.9'
lab1='echo 123.456.789.1'
lab2='echo 123.456.789.1'
lab3='echo 123.456.789.1'
...
lab9='echo 123.456.789.1'

Now I can simply type one command to ssh to any of the hosts as either user, and I can also do tricks like this to do other commands involving whatever host I need:


$ echo "I'm on host $(lab1)"
I'm on host 123.456.789.1

The other advantage of doing it this way is that if I add hosts, they change IPs, whatever, I just update one associative array and everything else gets updated automatically. Simple!

Related Article