How to Access the Desktop of a Firewalled Mac Using SSH
Problem
You have a remote Mac at home behind a router, or at work behind the company firewall, and you want to access its desktop from your local Mac. We will assume that screen sharing is enabled in the remote Mac. Of course you want to access the desktop securely [you don't want anyone else to record your session]. There are three possibilities.
Solution 1
You can't ssh between the local Mac and the remote Mac, but both Macs can ssh into a server:
- On the remote Mac, open a terminal and type "ssh -R 50123:localhost:5900 server".
- On the local Mac, open a terminal and type "ssh -L 50123:localhost:50123 server".
- On the local Mac, select "Finder > go > connect to server" and type "vnc://localhost:50123".
On the local Mac, you will be prompted for a [remote Mac] username/password, enter them, and the remote Mac's desktop will appear.
Solution 2
You can ssh from the local Mac into the remote Mac:
- On the local Mac, open a terminal and type "ssh -L 50123:localhost:5900 remotemac".
- On the local Mac, select "Finder > go > connect to server" and type "vnc://localhost:50123".
On the local Mac, you will be prompted for a [remote Mac] username/password, enter them, and the remote Mac's desktop will appear.
Solution 3
You can ssh from the remote Mac into the local Mac:
- On the remote Mac, open a terminal and type "ssh -R 50123:localhost:5900 localmac".
- On the local Mac, select "Finder > go > connect to server" and type "vnc://localhost:50123".
On the local Mac, you will be prompted for a [remote Mac] username/password, enter them, and the remote Mac's desktop will appear.
Notes
- The above commands need not be executed simultaneously [you can't be in two places at once].
- The port p=50123 may be changed to any unused port satisfying 49151 < p < 65536.
- The port p cannot equal the default vnc port 5900.
- In the ssh commands, "localmac", "remotemac", "server" must be replaced by their hostnames.
- In the ssh and vnc commands, "localhost" must stay as is.
- No settings need be changed on your home router or on the company firewall.
- The command invoking "ssh -L" is called "ssh tunneling".
- The command invoking "ssh -R" is called "reverse ssh tunneling".
- The meaning of the options -R and -L is explained in the man page of ssh.
- Solution 1 includes the degenerate case when the two Macs are the same [warning].
- Solution 2 corresponds to the degenerate case when the server and remote Mac are the same.
- Solution 3 corresponds to the degenerate case when the server and local Mac are the same.
- The degenerate case when all three computers are the same [vnc://localhost:5900] won't work.
- The remote computer need not be a Mac, it need only have a vnc server.
- The local computer need not be a Mac, it need only have a vnc client.
- You may need to disable sleep on the remote Mac.