本文承接帳戶管理主題,把使用者類型、相關檔案、useradd/usermod/userdel、群組操作、密碼策略,以及 SUID、SGID、粘滯位等特殊權限一次講清楚。
RHEL 7
RHEL 6
/etc/login.defs # 建立使用者的模板(uid 範圍、密碼效期等) /etc/group # 群組資訊 /etc/passwd # 使用者資訊 /etc/shadow # 密碼資訊 $HOME # 使用者家目錄 ~/.bash_profile # 環境變數 ~/.bashrc # bash 設定檔 ~/.bash_logout # 登出腳本 /etc/skel/* # 使用者設定檔模板
在 RHEL 7 中建立普通使用者前,需先建立群組:
groupadd -g 2000 g01 useradd -u 2000 -g g01 u01 id u01 # uid=2000(u01) gid=2000(g01) groups=2000(g01)
常用選項:
-u 指定 uid -g 指定 gid -c 指定備註內容 -d 指定家目錄 -s 指定 shell(普通使用者 /bin/bash,程式使用者 /sbin/nologin) -p 設定密碼(明文) -r 建立系統帳戶(RHEL 7) -m 建立家目錄 -M 不建立家目錄 -U 建立與使用者同名的群組
which useradd 會顯示 /usr/sbin/useradd,只有 root 能建立帳戶。/etc/passwd 的每一行由七個欄位組成:
root:x:0:0:root:/root:/bin/bash 使用者名稱 : 密碼(x 代表密碼存在於 /etc/shadow) : uid : gid : 備註 : 家目錄 : shell
練習一:建立 test 帳戶,家目錄 /home/test1、uid 10086、指定 shell:
useradd -d /home/test1 -u 10086 -c "這是一個普通的移動用戶" -s /bin/bash test
練習二:建立不給家目錄的程式帳戶:
useradd -u 959 -M -c "這是一個程序用戶" -s /sbin/nologin -r system1
usermod -c 備註 -d 家目錄 -e 帳號過期時間 usermod -l 新名稱 舊名稱 usermod -g 主群組 -G 輔助群組(多個) -L 鎖定帳號 userdel -f 強制刪除 userdel -r 連家目錄與郵件池($HOME 與 /var/mail/$USER)一起刪除
注意:修改 uid 與家目錄時要加 -m 才會實際搬移家目錄內容,且順序上通常先改 uid/家目錄,再改使用者名稱。
groupadd -g 2000 g01 # 建立群組並指定 gid groupadd -r sysgrp # 建立系統群組 groupdel g01 # 刪除群組(該群組不能仍有使用者以其為主群組) groupmod -n 新名稱 舊名稱 groupmod -p 新密碼 g01 gpasswd -a user01 g01 # 加入成員 gpasswd -A user01 g01 # 設定群組管理員 gpasswd -d user01 g01 # 移出成員 gpasswd -r g01 # 移除群組密碼 gpasswd -M user01,user02,user03 student # 一次設定成員列表
帳戶被鎖定時,即使密碼正確也無法登入,這類「鑑定故障」多半源自 passwd -l 或 usermod -L。su 使用者名 可切換帳戶,-u 指定 uid,-m 需與 -d 搭配修改家目錄。
root:$6$9QT1u/6XBOof0f0i$OJrKd2...:0:99999:7:::
每一行共九個欄位,以冒號分隔:
另外三種特殊符號的含義:* 代表系統帳戶、!! 代表尚未設定密碼、!密碼 代表帳戶已被鎖定。
passwd # 只有 root 能為所有帳戶設密碼 passwd -d user01 # 刪除密碼 passwd -l / -u user01 # 鎖定 / 解鎖 passwd -e user01 # 設定帳戶到期時間 passwd -x 3 test2 # 密碼最長修改間隔 passwd -n 2 test2 # 密碼最短修改間隔 passwd -w 5 test2 # 到期前告警天數 passwd -i 3 test2 # 到期後保留天數 echo 123 | passwd --stdin test # 非互動式設定密碼
chage 則以另一組參數管理同一批資訊:
chage -d 0 user01 # 最後修改日期設為 0,強制首次登入即改密碼 chage -E 2026-12-31 user01 # 帳戶到期日 chage -I 3 user01 # 到期後保留天數 chage -m 2 -M 90 user01 # 密碼最小/最大修改間隔 chage -W 7 user01 # 告警天數
chmod u-w /root/公共 chmod g+w /root/公共 chmod o=rw /root/公共 chmod a-x /root/公共 chmod 755 /root/公共 chmod -R 755 /root/公共 # 遞迴
權限三段對應 user、group、other,r=4、w=2、x=1;對目錄而言 x 代表「進入」權限,對檔案而言 x 代表「執行」權限。
chown [-R] user.group /path/file # 同時修改擁有者與群組 chown user:group /path/file chown user /path/file # 只改擁有者 chown :group /path/file # 只改群組 chgrp -R groupname /path/file # 只改群組
SUID(冒險位):針對擁有者設定,讓命令暫時擁有擁有者的權限,通常用於命令檔。
chmod u+s /path/filename chmod 4755 /path/filename # mask 4000
SGID(強制位):針對群組設定,通常用於目錄,使目錄中新建立的檔案自動繼承父目錄的群組。
chmod g+s /path/dir chmod 2755 /path/dir # mask 2000
粘滯位(Sticky Bit):針對其他人設定,用於公共目錄,誰建立的檔案就由誰管理,其他人只能讀取,不能修改或刪除。
chmod o+t /opt/public chmod 1777 /opt/public # mask 1000
顯示時的字母差異:所在位有 x 時顯示小寫 s/t,沒有 x 時顯示大寫 S/T。例如 drwxrwxr-T 代表粘滯位已設但 other 沒有執行權限。