Ubuntu – How to make a script that interacts with screen lock / unlock

dbuslock-screenscripts

I need a script for when I press Ctrl + Alt + L (Lock screen)
I blocked or shut down all usb's and shut down all my network interfaces like eth0.

When I Unlock, everything should be back to normal. I tried

echo suspend> / sys / bus / usb / devices / usb1 / power / level 

.. but I could not ..

And also

dbus-monitor --session "type = 'signal', interface = 'org.gnome.ScreenSaver' 

to interact with the screen but could not too.

Is there any better method? Or something I can study to create this script?

Best Answer

How to run scripts or commands on changes in lock state

According to this answer on U&L, you tried an outdated dbus command. For 14.04 and up, you can use:

dbus-monitor --session "type='signal',interface='com.ubuntu.Upstart0_6'" | \
(
  while read X; do
    if [[ "$X" =~ desktop-lock ]]; then
      SCREEN_LOCKED;
    elif [[ "$X" =~ desktop-unlock ]]; then
      SCREEN_UNLOCKED;
    fi
  done
)

which works fine on my system (16.04).
(Thanks for improvements by @Serg and @muru)

Of course you need to replace SCREEN_LOCKED and SCREEN_UNLOCKED by the commands or scripts you want to run on changes in lock state, but tested it, and it works fine.