如何在Linux中找到未锁定的tty?

如何在Linux中找到未锁定的tty?

我刚刚发现,当我在后台打开 tty 时,我的锁屏就没用了。我有时使用另一个 tty 来终止某些进程,然后我忘记了未锁定的 tty。这就是为什么我想在我的 Polybar 中显示一个符号来显示我是否在后台解锁了会话。

我发现有一个 systemd 单元[email protected]为我至少切换过一次的每个 tty 运行。但我无法确定会话是否仍处于登录状态。

你知道一种方法来检查我是否在后台打开了 tty 会话吗?

答案1

w命令列出了具有 shell 的用户和相应的终端,因此

w | grep -e 'tty[0-9]'

如果存在打开的 TTY 会话,则返回 rc=0,否则返回 1。

答案2

如果loginctl知道你的会话,你可以使用它(重复如何在图形 Linux 桌面会话上返回当前活动的用户/会话?):

for sessionid in $(loginctl list-sessions --no-legend | awk '{ print $1 }')
do loginctl show-session -p User -p Type -p Remote $sessionid | sort
done |
awk -F= '/Type/ { type = $2 } /Remote/ { remote = $2 } /User/ && remote == "no" && type == "tty" { sessions++ } END { print sessions }'

将计算当前打开的非远程 tty 会话的数量。

相关内容