SSH productivity tips

February 28, 2021

A few SSH tips I use often.

Exiting a stuck SSH session without killing the terminal

Automatic timeout when session unresponsive

There's two useful options: ServerAliveCountMax and ServerAliveInterval. When we active ServerAliveInterval, ssh will send a server alive message every interval. If no replies are recieved after ServerAliveCountMax messages, ssh will terminate the session automatically.

Add this to your ~/.ssh/config to disconnect after about 5 seconds of inactivity:

ServerAliveInterval 5
ServerAliveCountMax 1

Killing a session manually from SSH

When you run telnet, you get:

Escape character is '^]'.

Turns out ssh also has an escape character, and we can use one of its escape sequences to kill a session:

  1. Make sure Enter was the last key you pressed.
  2. Enter the tilde character and a dot: ~..

There's a bunch of other escape codes as well: you can see the listing at any time with ~?:

Supported escape sequences:
 ~.   - terminate connection (and any multiplexed sessions)
 ~B   - send a BREAK to the remote system
 ~C   - open a command line
 ~R   - request rekey
 ~V/v - decrease/increase verbosity (LogLevel)
 ~^Z  - suspend ssh
 ~#   - list forwarded connections
 ~&   - background ssh (when waiting for connections to terminate)
 ~?   - this message
 ~~   - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)

SSH aliases

Tired of writing ssh debian@server.example.com? Add an alias to ~/.ssh/config:

Host example
        HostName server.example.com
        User debian

and you can do ssh example instead.

Multiple windows and saving state in a SSH session

Don't want to open multiple terminals to ssh to the same server? tmux has you covered. Run tmux in your terminal session to start multiple terminals windows in a single ssh. A few basic commands:

Ctrl+B then " : Split horizontally into two panes
Ctrl+B then % : Split vertically into two panes
Ctrl+B then Up/Down/Left/Right : Navigate between split panes
Ctrl+B then C : New window
Ctrl+B then P : Move to previous window
Ctrl+B then N : Move to next window
Ctrl+B then PgUp : Scroll up in the pane's buffer

What if you want to exit while preserving all your current terminal panes and command history? Press Ctrl+B then D to detach your session, saving your entire state, before you log out. Next time you log in, type tmux attach to get your windows back.

Summary

I kept the tricks short and to the most productive. If you know of other things that make SSH more productive, feel free to leave a comment or message me.