How to return the currently active user/session on a graphical Linux desktop session?
On many current distributions, login sessions (graphical and non-graphical) are managed by logind
. You can list sessions using
loginctl list-sessions
and then display each session’s properties using
loginctl show-session ${SESSIONID}
or
loginctl session-status ${SESSIONID}
(replacing ${SESSIONID}
as appropriate); the difference between the two variants is that show-session
is designed to be easily parsed, session-status
is designed for human consumption. Active sessions are identified by their state; you can query that directly using
loginctl show-session -p State ${SESSIONID}
which will output
State=active
for the active session(s). The full show-session
output will tell you which user is connected, which TTY is being used, whether it’s a remote session, whether it’s a graphical session etc.
Note that logind
can have multiple active sessions, if the system is configured with multiple seats, or if there are remote sessions.
Putting this all together,
for sessionid in $(loginctl list-sessions --no-legend | awk '{ print $1 }')
do loginctl show-session -p Id -p Name -p User -p State -p Type -p Remote $sessionid
done
will give all the information you need to determine which sessions are active and who is using them, and
for sessionid in $(loginctl list-sessions --no-legend | awk '{ print $1 }')
do loginctl show-session -p Id -p Name -p User -p State -p Type -p Remote $sessionid | sort
done |
awk -F= '/Name/ { name = $2 } /User/ { user = $2 } /State/ { state = $2 } /Type/ { type = $2 } /Remote/ { remote = $2 } /User/ && remote == "no" && state == "active" && (type == "x11" || type == "wayland") { print user, name }'
will print the identifiers and logins of all active users with graphical sessions.
The LockedHint
property now indicates whether a given session is locked, so
for sessionid in $(loginctl list-sessions --no-legend | awk '{ print $1 }')
do loginctl show-session -p Id -p Name -p User -p State -p Type -p Remote -p LockedHint $sessionid | sort
done |
awk -F= '/Name/ { name = $2 } /User/ { user = $2 } /State/ { state = $2 } /Type/ { type = $2 } /Remote/ { remote = $2 } /LockedHint/ { locked = $2 } /User/ && remote == "no" && state == "active" && (type == "x11" || type == "wayland") { print user, name, locked == "yes" ? "locked" : "unlocked" }'
will also indicate whether the active session is locked or not.