How do I lock the desktop screen via command line?

You can lock the computer by running gnome-screensaver-command with the -l flag like so:

gnome-screensaver-command -l

However this will only work if you have Gnome Screensaver running for your session (should be - unless you've disabled it) you can start that from the commandline with:

gnome-screensaver

gnome-screensaver-command -l

If you're in a different (desktop) session (e.g. virtual console, switched to another login, SSH), specify the display explicitly (:0 is the default display):

DISPLAY=:0 gnome-screensaver-command -l

To unlock, use the -d (--deactivate) option.


In newer versions of GNOME 3, gnome-screensaver is no more.

The generic solution seems to be

xdg-screensaver lock

You also can call dbus directly instead (source):

dbus-send --type=method_call --dest=org.gnome.ScreenSaver /org/gnome/ScreenSaver org.gnome.ScreenSaver.Lock

It also seems they have taken away the possibility to unlock the screen from the command line.