Multi-hop X-forwarding over SSH

Sometimes you’d like to do X-forwarding over multiple hops. For instance:

Home ↔ Office gateway ↔ Office machine.

One way to automate this is with this Bash function:

1
2
3
4
5
6
7
8
sshx () {
        [ -z "$2" ] && return
        sudo ssh -Nn $1 -L 2200:$2:22 &
        sleep 1s
        PID=$!
        ssh localhost -XYC -p2200
        sudo kill $PID
}

Choose a random localhost port number; 2200 is merely an example here.

Then invoke with:

$ sshx passthrough_server destination_server

Since the snippet relies on Bash forking, it assumes you have set up SSH for public key based authentication with the passthrough server, and it will not ask for a password. Because SSH requires root privileges on your local machine to set up the port forwarding, your ~/.ssh/authorized_keys on the passthrough server must contains the public key of root from your local machine.

Leave a Reply

Your email address will not be published. Required fields are marked *