Skip to content

Linux如何设置用户长时间不操作就自动登出?

引言

当我们登录Linux系统后,如果长时间不操作,比如忘记关闭终端窗口了,怎么做到用户自动退出登录呢?

$ ls -l /etc/profile
-rw-r--r-- 1 root root 1819 Apr  1  2020 /etc/profile

这个文件是系统环境变量的配置文件,并且只有root有修改权限;如果能够在这个文件里面做一些设置,那么每个用户登录后都会加载里面的配置。

/etc/profile

# /etc/profile

# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc

# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.

这个文件不建议直接修改,而是创建自己的配置文件:

$ ls -1 /etc/profile.d/*
/etc/profile.d/colorgrep.csh
/etc/profile.d/colorgrep.sh
/etc/profile.d/colorls.csh
/etc/profile.d/colorls.sh
/etc/profile.d/csh.local
/etc/profile.d/less.csh
/etc/profile.d/less.sh
/etc/profile.d/sh.local
/etc/profile.d/vim.csh
/etc/profile.d/vim.sh
/etc/profile.d/which2.csh
/etc/profile.d/which2.sh

这些都是系统默认自带的定制环境变量,我们看下vim.sh里面内容:

# cat /etc/profile.d/vim.sh

if [ -n "$BASH_VERSION" -o -n "$KSH_VERSION" -o -n "$ZSH_VERSION" ]; then
  [ -x /usr/bin/id ] || return
  ID=`/usr/bin/id -u`
  [ -n "$ID" -a "$ID" -le 200 ] && return
  # for bash and zsh, only if no alias is already set
  alias vi >/dev/null 2>&1 || alias vi=vim
fi

/etc/profile.d/timeout.sh

TMOUT

If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin. The select command terminates if input does not arrive after TMOUT seconds when input is coming from a terminal. In an interactive shell, the value is interpreted as the number of seconds to wait for input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if input does not arrive.

root用户新建/etc/profile.d/timeout.sh文件,用于定义变量TMOUT大于0,用户超时不操作自动退出登录:

# cat /etc/profile.d/timeout.sh

readonly TMOUT=600 # 单位是秒(s)
export TMOUT

变量TMOUT的作用是在Shell超过一定时间无操作后自动退出登录。

$ unset TMOUT
bash: unset: TMOUT: cannot unset: readonly variable

$ TMOUT=1000
bash: TMOUT: readonly variable

readonly是不允许修改这个值,除非root用户修改配置文件并重新登录才可以修改生效。

总结

这样设置后,所有用户超过600秒不操作,登录的终端就自动退出登录了,在一定程度上增加了Linux系统的安全性。