I have seen questions on tunnelling SSH through multiple machines but I want to tunnel a SOCKS connection.

Normally I would use something like ssh -C2qTnN -D 8080 username@remote_machine to make the local port 8080 a SOCKS tunnel through the remote machine. I would like to open a socks connect from my laptop on machine2, that can only be reached via SSH from machine1.

So rather than tunnelling SSH connections in the normal sense, I suppose I wish to run that command on machine1 so the local port 8080 is redirected to machine2 and somehow pipe 8080 on machine1 back to a local port on laptop.


So, if I understand correctly, you can ssh from machine 1 to machine 2 but not from your laptop (from which you can ssh to machine 1). So you'd like to have a socks server on machine 1 and use it from your laptop? So looks like all you need is port forward that 8080: run on your laptop:

ssh -nL 8080:localhost:8080 machine1 ssh -C2qnN -D 8080 username@machine2
  • Amazing, thanks! The quote marks haven't shown in your answer but that works. It's also worth adding to your answer, that machine1 need key authentication to machine2, so it is non interactive.
    – jwbensley
    Dec 13 '12 at 22:58

The 2018+ answer to this question will be the RemoteCommand option to be specified in the ~/.ssh/config.

Host proxy
    Hostname ma.ch.in.e1
    RemoteCommand ssh -C2qnN -D 8080 username@machine2
    LocalForward 8080 localhost:8080

This requires OpenSSH 7.6 from 11/2017 or later. Versions before that need to use the answer from @StéphaneChazelas.

If you also want to connect to machine1 without also launching the proxy, just add an alias such as m1:

Host m1
    Hostname ma.ch.in.e1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.