The Personal Blog of Lennart Koopmann _

How to control and share a local TTY via SSH

When building nzyme tracker devices that use a physical Raspberry PI display, I had to find a way to log into the device via SSH and control the output of the display. In a graphical environment, I would have just used VNC, but this Raspberry PI was only running in Terminal mode.

The easiest way around this was to use /usr/bin/screen, launch it automatically on login and then make any new SSH session re-attach to that screen session in a shared mode.

Using screen

The two relevant commands are starting a new screen session and attaching to that session later.

Starting a new screen session with the name main:

$ screen -S main

Attaching to screen session main in shared (multi-display) mode:

$ screen -x main

Entering screen automatically

We'll need to start a new screen session (-S main) when the Raspberry Pi boots up (make sure to set it to auto-login into terminal mode) and we have to make each new SSH session automatically re-attach to that screen session (-x main).

On each login, the commands in ~/.profile are executed and we can make use of that by adding the following script to it:

if screen -ls | grep -q "main"; then
    screen -x main
    screen -S main

This script detects if there is already a screen session called main running, and then either starts a new one or re-attaches to it based on the result.

Restart the device and then SSH into it. You should see that the SSH session immediately starts up screen and even reduces your input to the physical size of the terminal on the Raspberry PI:

Each command entered in the SSH session will now be echoed on the physical display and vice-versa. Of course you can even connect multiple SSH sessions and all will be shared.

Make sure to detach (CTRL+a d) from the screen session when exiting SSH because you don't want to exit and end the screen session.