HowtoForge

Some Tips To Make SSH/SCP Usage More Convenient

Some Tips To Make SSH/SCP Usage More Convenient

I guess many of us rely heavily on ssh/scp to access/maintain remote hosts. In this short article I would like to share some experiences I find useful for ssh/scp usage.

First let's have a look how things started:

I use a simple trick to get out of this mess: I have a simple script named ssh-generic that looks as follows:

#!/bin/bash
port="22"
case "$0" in
*-host1)
    account="myid@192.168.0.1"
    ;;
*-host2)
    account="root@192.168.0.2"
    ;;
*-host3)
    account="admin@192.168.0.3"
    port="222"
    ;;
*)  
    echo "unsupported name: $0"
    exit 1
    ;;
esac

case "$0" in
*/ssh-*)
    echo running ssh -p $port $account "$@"
    ssh -p $port $account "$@"
    ;;
*/scp-to-*)
    echo running scp -P $port "$@" $account:
    scp -P $port "$@" $account:$scpdir
    ;;
*/scp-from-*)
    echo scp -P $port $account:$1 .
    scp -P $port $account:$1 .
    ;;
*) echo "unsupported name: $0" exit 1 ;; esac

Then I make ssh-host1, scp-to-host1 and scp-from-host1 as symlink to the above script (ie ssh-generic). Usage is trivial:

Similar for host2 and host3. When we get another host, it's easy to edit ssh-generic, add the relevant entry and make needed symlinks. For example, let's add another host with ip 192.168.0.4, port for ssh 2222 and user id admin2. We want to access this host by simply saying ssh-host4. This turns out to be easy:

*-host4)
    account="admin2@192.168.0.4"
    port="2222"
    ;;

A bonus is that we can say in the command line eg ssh-host<Tab> to free ourselves from remembering the hostnames, connection details and hence from making mistakes. There are some cosmetic details that I left out from the script for clarity, like automatically setting the title of current xshell before running ssh/scp, or a dryrun option for the script.

I also have a companion script that can be used to ease uploading ssh keys. I named it "enable-ssh" (a bit poor chosen name, should be renamed to something better) and it looks as follows:

if test -z "$1"; then
        echo Usage: $0 '[-p <port>] <host>'
        exit 1
fi

if ! test -s $HOME/.ssh/id_rsa.pub; then
    ssh-keygen -t rsa
fi

cd
cat $HOME/.ssh/id_rsa.pub | \
    ssh "$@" "mkdir -p .ssh; touch .ssh/authorized_keys; cat >> .ssh/authorized_keys"

Usage:

That's it. I hope you find this useful.

Some Tips To Make SSH/SCP Usage More Convenient