How do I connect to a pc through another pc using ssh

ssh -o 'ProxyCommand ssh -W %h:%p [email protected]'

Then you can simply run ssh PC1.

Best used through an alias in ~/.ssh/config:

Host PC1
HostName 192.168.0.2
User user
ProxyCommand ssh -W %h:%p [email protected]

For older versions of OpenSSH that don't have the -W option (I think this means ≤5.4), make sure that netcat is available on PC2 and use

Host PC1
HostName 192.168.0.2
User user
ProxyCommand ssh [email protected] nc %h %p

Using SSH there is a clear solution:

  1. on your local machine set up your ~/.ssh/config such that it has the following:

    host WhatYouWillCallTheConnection
        hostname the.gateway.server.address.com
        user YourUsernameOnTheGateway
    
  2. On both the gateway and the end server you'd like to connect to, make sure that you have your local client's public keys located in the ~/.ssh/authorized_keys

  3. On the gateway machine you need to alter the ~/.ssh/authorized_keys such that at the beginning of the line that specifies your client's public key, add the forced command as follows:

    command="ssh -A [email protected]" ...yourPublicKey....
    

The -A is to forward the agent if you don't like to send passwords all the time...

This way, anytime you do something like ssh WhatYouWillCallTheConnection it will run straight through the gateway and connect you to the server on the other side transparently.


Port Forwarding might come in handy.
From PC1:

~# ssh -fN -L 22:PC3:7777 -l <user> PC2  

7777 can be just any port (provided it is not already being used). I just like that number, plus any "ordering up" I can manage by +1 's (7778, 7779, etc, etc).

This being done, you will have a 'transparent' tunnel from PC1's local port 7777 to PC3's port 22. Just issue:

~# ssh -l <user> -p 7777 localhost  

And you should be on PC3.
You can also use -D to dynamically forward a port if you want a SOCKS proxy established.

~# ssh -D <someport> -fN -L 22:PC3:7777 -l <user> PC2  

Cheers!

Tags:

Ssh