Toggle Gnome screensaver lock on USB key insertion

Sunday, Sep 25, 2011 9:39 am
William Barnes

While I like my computer to lock itself automatically when I leave, it gets annoying when it does it every time I get up for a few minutes. I decided that it would be nice if I could toggle the screen lock only when I’m out of the apartment. I decided that the trigger should be the USB key I have on my keychain. It’s always with me. If it’s plugged in to the computer, then I’m likely home. I apologize for the (lack of) formatting of the code, I will be fixing that when I get my computer back up and running.

Ubuntu uses an event-based system called udev that, among other things, can run a script when a USB device is plugged in or unplugged. Local (ie: user-created) udev rules are stored in /etc/udev/rules.d/. Before you can create a rule, you need to know a little about the device that is going to trigger it. Open a terminal and type:

udevadm monitor --udev --environment

Connect your USB device. It doesn’t have to be a USB key, it could be a phone, for example. A bunch of text will come up. Look for “ID_SERIAL” and “ID_VENDOR_ID”. Write down the values of those. You can use other variables if they suit your device better, just change the rules file accordingly.

Create a file called “/etc/udev/rules.d/85-screen-lock-toggle.rules”. Put the following in it, replacing VALUE with the proper value:

  1. ACTION=="remove", ENV{ID_SERIAL}=="VALUE", ENV{ID_VENDOR_ID}=="VALUE", RUN+="/usr/local/bin/gnome-lock-enable"
  2. ACTION=="add", ENV{ID_SERIAL}=="VALUE", ENV{ID_VENDOR_ID}=="VALUE", RUN+="/usr/local/bin/gnome-lock-disable"

Next create the scripts to actually disable and enable locking:

  1. #!/bin/bash
  2.  
  3. user=`ps aux | grep gnome-screensaver | head -n 1 | awk '{print $1}'`
  4.  
  5. if [ -n $user ]; then
  6. GNOME_SCREENSAVER_PROC=`ps xa | grep gnome-screensaver | head -n 1 | awk '{print $1}'`
  7. export `grep -z DBUS_SESSION_BUS_ADDRESS /proc/$GNOME_SCREENSAVER_PROC/environ`
  8. su $user -c "gconftool-2 --set "/apps/gnome-screensaver/lock_enabled" --type bool 1"
  9. fi
  1. #!/bin/bash
  2.  
  3. user=`ps aux | grep gnome-screensaver | head -n 1 | awk '{print $1}'`
  4.  
  5. if [ -n $user ]; then
  6. GNOME_SCREENSAVER_PROC=`ps xa | grep gnome-screensaver | head -n 1 | awk '{print $1}'`
  7. export `grep -z DBUS_SESSION_BUS_ADDRESS /proc/$GNOME_SCREENSAVER_PROC/environ`
  8. su $user -c "gconftool-2 --set "/apps/gnome-screensaver/lock_enabled" --type bool 0"
  9. fi

Make the scripts executable:

sudo chmod a+x /usr/local/bin/gnome-lock-enable /usr/local/bin/gnome-lock-disable

Restart udev:

sudo restart udev

Enjoy the convenience.