創(chuàng)建用戶
在linux中創(chuàng)建用戶可以使用兩種指令 adduser 和 useradd ,其區(qū)別可參考 這篇文章 。
在 ubuntu 中使用 adduser 會(huì)更方便地創(chuàng)建用戶。
語(yǔ)法
sudo adduser username
示例

其需要使用 root 用戶才能創(chuàng)建用戶,需要輸入當(dāng)前用戶的密碼,如果未指定組,會(huì)自動(dòng)創(chuàng)建同名組并將其添加到組中,自動(dòng)創(chuàng)建家目錄。然后要求輸入該用戶的密碼與相關(guān)信息。
useradd 則需要指定一系列信息。
語(yǔ)法
useradd [-mMnr][-c <備注>][-d <登入目錄>][-e <有效期限>][-f <緩沖天數(shù)>][-g <群組>][-G <群組>][-s <shell>][-u <uid>][用戶帳號(hào)]
或
useradd -D [-b][-e <有效期限>][-f <緩沖天數(shù)>][-g <群組>][-G <群組>][-s <shell>]
參數(shù)說(shuō)明
-c<備注>
-d<登入目錄>
-D
-e<有效期限>
-f<緩沖天數(shù)>
-g<群組>
-G<群組>
-m
-M
-n
-r
-s<shell>
-u<uid>
示例
- 創(chuàng)建 test2 用戶,指定家目錄為 /home/test2 ,如果未有家目錄則自動(dòng)創(chuàng)建家目錄 /home/test2 ,指定shell為 /bin/bash
注意如果為有指定的組,需要先自行創(chuàng)建改組。
注意此時(shí)是 test2 用戶是沒(méi)有密碼的,需要手動(dòng)添加密碼,否則無(wú)法登錄用戶。可以使用 passwd 設(shè)置密碼, passwd 具體可看 這篇文章 。

添加用戶之后,會(huì)在 /etc/passwd 中添加一個(gè)記錄

/etc/passwd 文件內(nèi)容非常規(guī)律, 每行記錄對(duì)應(yīng)一個(gè)用戶

這里的密碼 x 并不是真正的密碼,密碼存放在 /etc/shadow 中,需要 root 用戶才能查看

同 /etc/passwd 文件一樣,文件中每行代表一個(gè)用戶,同樣使用 : 作為分隔符,不同之處在于,每行用戶信息被劃分為 9 個(gè)字段。每個(gè)字段的含義如下:
用戶名:加密密碼:最后一次修改時(shí)間:最小修改時(shí)間間隔:密碼有效期:密碼需要變更前的警告天數(shù):密碼過(guò)期后的寬限時(shí)間:賬號(hào)失效時(shí)間:保留字段
切換用戶
su (英文全拼:switch user) 命令用于變更為其他使用者的身份,除 root 外,需要鍵入該使用者的密碼。
語(yǔ)法
su [-fmp] [-c command] [-s shell] [--help] [--version] [-] [USER [ARG]]
-f 或 --fast
-m -p 或 --preserve-environment
-c command 或 --command=command
-s shell 或 --shell=shell
--help
--version
- -l 或 --login
USER
ARG
示例
變更帳號(hào)為 root 并在執(zhí)行 ls 指令后退出變回原使用者
su -c ls root
變更帳號(hào)為 root 并傳入 -f 參數(shù)給新執(zhí)行的 shell
su root -f
變更帳號(hào)為 clsung 并改變工作目錄至 clsung 的家目錄(home dir)
su - clsung
切換用戶
[email protected]:~$ whoami //顯示當(dāng)前用戶
hnlinux
[email protected]:~$ pwd //顯示當(dāng)前目錄
/home/hnlinux
[email protected]:~$ su root //切換到root用戶
密碼:
[email protected]:/home/hnlinux# whoami
root
[email protected]:/home/hnlinux# pwd
/home/hnlinux
切換用戶,改變環(huán)境變量
[email protected]:~$ whoami //顯示當(dāng)前用戶
hnlinux
[email protected]:~$ pwd //顯示當(dāng)前目錄
/home/hnlinux
[email protected]:~$ su - root //切換到root用戶
密碼:
[email protected]:/home/hnlinux# whoami
root
[email protected]:/home/hnlinux# pwd //顯示當(dāng)前目錄
/root
切換用戶后可以使用 exit 命令切換回來(lái)

刪除用戶
Linux userdel 命令用于刪除用戶賬號(hào)。 userdel 可刪除用戶賬號(hào)與相關(guān)的文件。若不加參數(shù),則僅刪除用戶賬號(hào),而不刪除相關(guān)文件。
語(yǔ)法
userdel [-r][用戶帳號(hào)]
參數(shù)說(shuō)明
- r 刪除用戶登入目錄以及目錄中所有文件
實(shí)例
- 刪除用戶賬號(hào)及工作目錄
sudo userdel -r test2