SSH tricks

SSH tricks

This is a small bundle of useful SSH tricks for you if you have not discovered the wonders of ssh config files. This tutorial assumes that the reader is familiar with basic basic Linux commands and is vaguely familiar with a terminal editor. All the commands mentioned below are meant to be run on the host machine aka on the local computer/laptop.

SSH without password

Entering your password becomes a serious problem when you interact with multiple servers everyday and at this stage SSH keys become a lifesaver. Apart from the obvious pain to using password with SSH, there is also an element of security involved. The steps for having a password-less ssh setup and to write a simple ssh-config file are enumerated below.

ssh-keygen -t rsa
ssh-copy-id -i ~/.ssh/id_rsa.pub <user-name>@<remote-host>
ssh-copy-id <user-name>@<remote-host>
vim config
host sample
  User username
  HostName sample.cs.jhu.edu
  Port 22
ssh sample

Local Port Forwarding with SSH Config file

We live in the world with firewalls and these can be very restrictive at times. Frequently the only open ports are 80/443(HTTP/HTTPS) and 22(SSH). This prevents you from accessing services running on other ports, for example MySQL on 3306. Here port forwarding via SSH (also called SSH tunneling) can be a life saver. A short description of what this entails, is to create a connection between your local computer and a remote machine through which traffic can be relayed.

ssh -f -N -L 8036:localhost:3306 user@sample.cs.jhu.edu

The command above will forward all traffic from your local port 8036 to port 3306 on the remote host. Here options -f will run the job in the background and -N will make it execute a remote command. Now it can be difficult to remember the numerous ssh options and this long command. This can be easily mapped to your ssh config file as follows:

host tunnel
  User username
  HostName sample.cs.jhu.edu
  LocalForward 8036 localhost:3306
ssh -f -N tunnel

X11 forwarding over SSH

ssh -X <user-name>@<remote-host>
xclock
firefox

SSH X11 Forwarding on OSX

If you want to forward X11 on OSX, here is what you need in the config file.

host sample
  User username
  HostName sample.cs.jhu.edu
  Port 22
  ForwardX11 yes
  ForwardX11Trusted yes

Keeping your SSH connection alive

Are your ssh connections dropped due to inactivity? Adding ServerAliveInterval to the config file will prevent this from happening.

host sample
  User username
  HostName sample.cs.jhu.edu
  Port 22
  ServerAliveInterval 100
Kunal Lillaney

Kunal Lillaney

rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora