Running rdesktop through a SSH tunnel in one command

I am running ssh server -L 3392:192.168.1.138:3389 in one terminal window, then running rdesktop 127.0.0.1:3392 in another to connect to a Windows machine through an SSH tunnel. How can I merge this into one command that I can run from a Gnome shortcut or something?


Solution 1:

I assume you have a password-less SSH key set up so that ssh does not prompt for a password.

You can use a bash script like this:

#!/bin/bash
ssh server -L 3392:192.168.1.138:3389 -N &
SSH_PID=$!
sleep 5 # wait for the connection to establish
rdesktop 127.0.0.1:3392
kill $SSH_PID

I'm making an assumption here that rdesktop does not fork and return until the program ends. If it does, the SSH connection will die immediately. If that's true, you'd need to watch for running rdesktop processes, loop/sleep until they're all dead, and then close the SSH connection.

Solution 2:

As an improvement to the above, you don't have to kill the SSH PID at the end.

ssh server -fL 3392:192.168.1.138:3389 sleep 5  
rdesktop 127.0.0.1:3392

The above will tell ssh to run a sleep 5 on the remove server and go to the background (-f). This will make the connection stay open for 5 seconds, which is enough time for the rdesktop command to run. The port forwarding will remain in place whilst there is traffic passing through, so as as soon as you exit the rdesktop the ssh should die automatically.