I usually lock my sessions, either manually or automatically after some idle time. At home that doesn’t make much of difference, but at the office, or in a public place, it’s important.

However, I’ve always had this secret hole in my security: sometimes, because Linux’s graphical interfaces tend to die, I hit Ctrl+Alt+F[1-6] to use the the real TTYs, curiously named virtual consoles, for the same historic reasons for which the V and the I in VIM mean visual interface. Yeah, google it.

But I digress. The virtual consoles are great, etc, etc. But when I’m done with them and return to my graphical environment du jour, I almost never remember to log out from them. And since I usually use them to troubleshoot stuff, in many many cases, I leave them around with the root user fully logged in.

That’s a problem, no need to explain it.

I searched for a solution before and learned about Bash’s TMOUT environment variable, which you can set up to have Bash log out automatically after an idle timeout. But that’s fragile. Bash can only log out if you leave your session at the prompt. If you’re running anything else like Vim, Bash will not log out, regardless of how long you leave that untouched. I know I’ve had Vims in TTYs running for weeks without noticing it.

Someone online had a slightly more effective approach: use finger or who periodically to monitor idle time and kill the sessions that go over some limit. That’s more secure, sure. But it’s also too aggressive, because it may lose data. What if, for instance, you hadn’t saved what you typed in that Vim?

So, today I came up with an alternative, using GNU screen. The idea is simple, make your TTYs start screen immediately after login. When that screen exits, the session will end. And then idle-locking is trivial, screen has a built-in solution. This is what I did:

Add this at the end of to your ~/.bashrc:

if [ "$TERM" = "linux" ] && tty | egrep -q '^/dev/tty[[:digit:]]+$'
    exec screen -c ~/.ttyscreenrc

The exec is important. It ensures that screen will replace bash, in the same process and it’s what guarantees that when screen ends the session will end too.

Create a particular screenrc for this. As seen above, I called it ~/.ttyscreenrc, with this content:

startup_message off
idle 180 lockscreen

And change that file to suit your preferences. I put 180 seconds (3 minutes).

And that’s it. Your TTYs will lock and ask you for a password after the configured idle timeout. And you won’t lose any work.

Share it!