Autossh

Autossh is a program to start a copy of ssh and monitor it, restarting it as necessary should it die or stop passing traffic. Here we use autossh to realize NAT traversal.

Suppose we have three mechine:

  1. HBC without public IP, ssh port 22

  2. Server(like aliyun) with public IP, ssh port 12318, another two free ports 5678 and 8765

  3. PC which need to connect A

Connect without password for A->B

  • Generate key in A:

ssh-keygen -t rsa
  • Give public key of A to B

cat .ssh/id_rsa.pub | ssh user_B@ip_B 'cat >> .ssh/authorized_keys'
  • Check that you can connect from A to B without password, otherswise you should see Others .

Auto ssh from B->A

  • Now you can create a tunnel from B to A

autossh -M 5678 -fCNR 8765:localhost:22 user_B@ip_B -p12318
  • In the file /etc/ssh/sshd_config, you need to set

GatewayPorts yes
  • Finally, connection from C to A is OK

ssh user_A@ip_B -p 8765

Others

Note

  1. make sure that A can connect B

  2. need to change access permission for .ssh and .ssh/* in B

chmod 700 .ssh
chmod 600 .ssh/*

Error

you may still have wrong in connect B from A

sign_and_send_pubkey: signing failed: agent refused operation

you should do this to add the key

ssh-add ~/.ssh/id_rsa