强制用户(在 Mac 上)在不活动后注销

强制用户(在 Mac 上)在不活动后注销

我正在寻找一种方法,可以强制使登录到我的 Mac 的帐户在一段时间不活动后自动注销。

操作系统(Lion)中有一个内置设置可以执行此操作,但它适用于所有用户,而我只想对某些帐户执行此操作。

在 Windows 上,我可以使用 gpedit 强制用户使用屏幕保护程序来注销用户。在 Mac OS X Lion 上我可以做类似的事情吗?

附言:我是该系统的唯一管理员。

答案1

我已经找到了一种方法来做到这一点,它有点像使用 shell 脚本、cron 和 sudo 的 hack,但它似乎工作得很好。

首先,创建一个由 root 拥有的 shell 脚本/bin/usertimeout,将其 chmod 为 755,并将以下内容粘贴到文件中

#!/bin/bash

# Timeout is the number of seconds a login session can be idle before it is
# automatically logged out.
timeout=3600

if [ $(stat -f %u /dev/console) == $UID ]
then
  if [ -e /tmp/backgroundUserLogout.$UID ]
  then
    rm /tmp/backgroundUserLogout.$UID
  fi
else
  if [ ! -e /tmp/backgroundUserLogout.$UID ]
  then
    touch /tmp/backgroundUserLogout.$UID
  else
    if [ $(( `date +%s` - `stat -f %m /tmp/backgroundUserLogout.$UID || printf 0` )) -ge $(( $timeout )) ]
    then
      rm /tmp/backgroundUserLogout.$UID
      sudo /sbin/killuser
    fi
  fi
fi

接下来,创建一个文件/sbin/killuser,所有者为 root,将其 chmod 设置为 755,并粘贴以下内容

#!/bin/bash
#
# Logs out the user calling this script   

# Get the PID of the loginwindow process for the user executing this
pid=`ps -Axjc | grep ^$SUDO_USER | grep loginwindow | cut -c 14-20 | tr -d /\ /` 

# If the PID appears to be valid, kill the process
if [ $pid -gt 0 2>/dev/null ]
then
  kill -9 $pid
fi

接下来,为您希望自动注销的每个用户添加一个 crontab 条目。如果您希望所有用户都受到影响,这将是一个麻烦,但就我而言,我只要求少数用户在空闲时注销。

# Crontab for user that has to be autologged out
* * * * * /bin/usertimeout

请注意,上述示例每分钟运行一次,具体取决于您允许的空闲时间,您可能希望将其增加到更合适的频率(例如每 15 分钟使用*/15 * * * * /bin/usertimeout

现在对 sudoers 文件进行简单的修改visudo就可以了。

%users          ALL=(ALL) NOPASSWD: /sbin/killuser

相关内容