linux 用户(user) 管理

useradd 创建用户

Option Description
-c '<comment>' <comment> can be replaced with any string. This option is generally used to specify the full name of a user.
-d<home-dir> Home directory to be used instead of default /home/<username>/
-e<date> Date for the account to be disabled in the format YYYY-MM-DD
-f<days> Number of days after the password expires until the account is disabled. If 0 is specified, the account is disabled immediately after the password expires. If -1 is specified, the account is not be disabled after the password expires.
-g<group-name> Group name or group number for the user's default group. The group must exist prior to being specified here.
-G<group-list> List of additional (other than default) group names or group numbers, separated by commas, of which the user is a member. The groups must exist prior to being specified here.
-m Create the home directory if it does not exist.
-M Do not create the home directory.
-n Do not create a user private group for the user.
-r Create a system account with a UID less than 500 and without a home directory
-p<password> The password encrypted with crypt
-s User's login shell, which defaults to /bin/bash
-u<uid> User ID for the user, which must be unique and greater than 499

创建简单用户

1
useradd jack

jack 用户的默认配置,由 /etc/default/useradd 决定

  • /etc/default/useradd 文件内容示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
      $ cat /etc/default/useradd
      # useradd defaults file
      GROUP=100
      HOME=/home
      INACTIVE=-1
      EXPIRE=
      SHELL=/bin/bash
      SKEL=/etc/skel
      CREATE_MAIL_SPOOL=yes
    

创建包含 Home目录 的用户

1
2
useradd -m tom
cd /home/tom

创建用户时,指定非默认的 Home目录

1
useradd -m -d /home/guests/trump trump

默认就创建 Home目录,而不需要 -m 参数

修改 /etc/login.defs

1
CREATE_HOME yes

创建一个有期限的用户

1
useradd -m -e 2017-10-11 visitor-tony

创建时,将用户指派给Group

1
useradd -m -G visitors tony

创建用户时候的高级设置

1
2
3
4
# PASS_MAX_DAYS=5 密码5天后过期
# PASS_WARN_AGE=3 提前3天提醒密码将过期
# LOGIN_RETRIES=1 允许输错密码1次
sudo useradd test5 -m -K PASS_MAX_DAYS=5 -K PASS_WARN_AGE=3 -K LOGIN_RETRIES=1

修改 | 设置用户密码

1
passwd someone

切换用户

1
su - steve

usermod 修改用户

修改登录后的shell

1
usermod -s /bin/bash someone

禁止登录

1
usermod -s /bin/nologin someone

用户管理设置

/etc/login.defs

  • PASS_MAX_DAYS - how long before a password expires
  • PASS_MIN_DAYS - how often can a password be changed
  • PASS_WARN_AGE - number of days warning before a password expires
  • LOGIN_RETRIES - number of login attempts before failure
  • LOGIN_TIMEOUT - how long is it before the login times out.
  • DEFAULT_HOME - can a user login if no home folder exists

userdel 删除用户

1
userdel tony

-r , 连带 Home目录 一起删除

1
userdel -r tony

-f , 强制删除用户,即使该用户仍然登录