8

Is there a way to run a bash script on locking the current KDE session?

countermode
  • 7,533
  • 5
  • 31
  • 58
dudas
  • 301

3 Answers3

7

It might depend on which version of KDE you're running, but if you've got a Notifications Entry in System Settings, then you can use the Screensaver controls to run scripts on both screen lock and unlock.

KDE Notifications System Settings Module

Chris
  • 81
5

On KDE and some other Desktop Environments, you can listen on dbus for the interface org.freedesktop.ScreenSaver.

A script to do this would look like this:

dbus-monitor --session "type='signal',interface='org.freedesktop.ScreenSaver'" |
  while read x; do
    case "$x" in 
      # You can call your desired script in the following line instead of the echo:
      *"boolean true"*) echo SCREEN_LOCKED;;
      *"boolean false"*) echo SCREEN_UNLOCKED;;  
    esac
  done

Please also see this question for more information.

Bob
  • 350
4

One workaround I can think of is (if you normally use a keyboard shortcut to lock) to rebind the keyboard shortcut from lock to instead execute your script, then locking the session, which can be achieved using this command in your script:

qdbus org.freedesktop.ScreenSaver /ScreenSaver Lock

However, I'm not on kde, so can't test it.

If you don't use a keyboard shortcut, I think it will be harder to do this. One possible method is forking the locking program to look for a script and execute it.

  • 1
    Although this looks like a hack, I prefer this answer to the dbus monitor solution, since it does not require the script to be running during the complete session. Especially if you are doing something security sensitive (e.g. close ssh keys), you will not notice a terminated dbus monitor script (and in the example you would leave keys in memory). – Till Schäfer Nov 06 '19 at 18:52
  • This does not work, at least as stated, when the screensaver is activated by a timeout. – Luis A. Florit Sep 03 '23 at 21:43