splitbrain.org

electronic brain surgery since 2001

SSH Alias Script

One of the cool things you can do with SSH, is creating aliases for your connections. This is especially useful in cases where you need to connect to a (hard to remember) IP address, use a different user name or a different port number.

Adding an alias is simple. Just add the following to your ~/.ssh/config file:

host foo
  hostname    123.123.123.123
  user        foobar
  port        9876

Now you can simply run ssh foo instead of ssh foobar@123.123.123.123 -p 9876. Much better, right? And with bash completion this will even be autocompleted :-).

But this wasn't comfort enough for me. I also wanted a way to easily add a new alias from the command line. That's why I added a another function to my set of .bashrc tools:

# SSH bookmark creator
sbm(){
    if [ $# -lt 2 ]; then
        echo "Usage: sbm <short> [<user>@]<hostname> [-p <port>]" >&2
        return 1
    fi
 
    short=$1
    arg=$2
 
    if $(echo "$arg" | grep '@' >/dev/null); then
        user=$(echo "$arg"|sed -e 's/@.*$//')
    fi
 
    host=$(echo "$arg"|sed -e 's/^.*@//')
 
    if [ "$3" == "-p" ]; then
        port=$4
    fi
 
    if $(grep -i "host $short" "$HOME/.ssh/config" > /dev/null); then
        echo "Alias '$short' already exists" >&2
        return 1
    fi
 
    if [ -z "$host" ]; then
        echo "No hostname found" >&2
        return 1
    fi
 
    echo >> "$HOME/.ssh/config"
    echo "host $short" >> "$HOME/.ssh/config"
    echo "  hostname $host" >> "$HOME/.ssh/config"
    [ ! -z "$user" ] && echo "  user     $user" >> "$HOME/.ssh/config"
    [ ! -z "$port" ] && echo "  port     $port" >> "$HOME/.ssh/config"
 
    echo "added alias '$short' for $host"
}

This allows me to call sbm foo foobar@123.123.123.123 -p 9876 to create the above alias. The script is probably not perfect, so if you'd like to improve it checkout this gist at github.

Tags:
ssh, bash, shell, linux
Similar posts: