Skip to main content

SSH

Installation

# For the server
sudo apt-get update && sudo apt-get install -qy openssh-server

# For the client
sudo apt-get update && sudo apt-get install -qy openssh-client

Create a SSH Key

Here is an easy way. Check out other encryptions, etc., later on.

ssh-keygen -t rsa -b 4096 -C "NAME OF KEY OR EMAIL"

Remove Known Host

ssh-keygen -f ".ssh/known_hosts" -R "ADDRESS_OF_REMOTE_VM"

Port Forwarding

Expose on Local Port

To expose the remote port on another local port:

sudo ssh -N -L 0.0.0.0:8080:127.0.0.1:80 ubuntu@SERVER_ADDR -i SSH_KEY
  • -N Don't run any command, wait in this command (otherwise it will ssh into the other server).
  • -L Expose on the local port.
  • 0.0.0.0:8080 Forward the remote port 8080, listening on all interfaces.
  • 127.0.0.1:80 Expose on port 80 of the local host.

Expose on Remote Port

To expose a local port on a remote server:

ssh -N -R 0.0.0.0:8080:127.0.0.1:80 root@SERVER_ADDR -i SSH_KEY

This will achieve the same thing as the command above. The difference is that this one should be executed on the remote host. This exposes the local port 80 on the port 8080 of the remote host.

  • Note: When doing this, you need to allow tcp forwarding on sshd_config. To do so, change the following settings in /etc/ssh/sshd_config:
AllowTcpForwarding yes
GatewayPorts yes

And then, restart sshd:

sudo service sshd restart

Keep Forwarding Open

First, use the following options in the SSH command to exit when connection is closed:

-o ExitOnForwardFailure=yes -o ServerAliveInterval=60

You can create a bash script like this:

while true
do
    ssh -N -R 0.0.0.0:8080:127.0.0.1:80 root@SERVER_ADDR -i SSH_KEY -o ExitOnForwardFailure=yes -o ServerAliveInterval=60
    # or use sshpass: sshpass -p PASSWORD ssh -N ...
    sleep 30
done

And then you can simply do something like this:

nohup bash openconn.sh &

Passing Password

To pass the password, you can use sshpass like this:

sudo apt-get update && sudo apt-get install sshpass -qy
sshpass -p PASSWORD ssh ...