Home > Enterprise >  How to check for *open* user desktop session
How to check for *open* user desktop session

Time:05-12

I would like to check (from cron) whether a user has an open desktop session. (with "open" I mean visible on screen no matter how idle) So far I have covered two bases:

  • I can check whether the user is logged in (I use "w" to check for a tty belonging to the user) and
  • I can check whether a screenlock is active. (mate-screensaver-command)

However there is the case when another user session has been started (via Switch User) which apparently does not activate the regular screen locking mechanism. Is there a way to detect this case? Or perhaps an even better, single universal approach? Would be nice if this was future proof (read Wayland capable).

System is: Ubuntu 20.04 Mate with X11 /Xorg

CodePudding user response:

I found a somewhat clumsy solution by using loginctl list-sessions to get the ids of all current sessions and then loginctl show-session $id to scan for a session with Active=yes and Type=x11:

#!/usr/bin/env python3

import subprocess
import re

res = subprocess.run( [ "loginctl", "--no-legend", "list-sessions" ],
  stdout=subprocess.PIPE )

for line in res.stdout.decode("utf-8").split("\n"):
  if len(line)==0: continue
  session, uid, user, rest = re.split( r"\s ", line, maxsplit=3 )
  info = subprocess.run( [ "loginctl", "show-session", session ],
     stdout=subprocess.PIPE )
  data = {}
  for infoline in info.stdout.decode("utf-8").split("\n"):
    if len(infoline)==0: continue
    key, value = re.split( "=", infoline, maxsplit=1 )
    data[key] = value
  if data.get("Active")=="yes" and data.get("Type")=="x11":
    print( user )
  • Related