Linux用戶和組管理命令-切換用戶su


切換用戶或以其他用戶身份執行命令

su: 即 switch user,命令可以切換用戶身份,並且以指定用戶的身份執行命令

格式:

su [options...] [-] [user [args...]]

常見選項:

-l --login su -l UserName 相當於 su - UserName
-c, --command <command> pass a single command to the shell with -c

切換用戶的方式:

  • su UserName:非登錄式切換,即不會讀取目標用戶的配置文件,不改變當前工作目錄,即不完全切換
  • su - UserName:登錄式切換,會讀取目標用戶的配置文件,切換至自已的家目錄,即完全切換
    說明:root su至其他用戶無須密碼;非root用戶切換時需要密碼
    注意:su 切換新用戶后,使用 exit 退回至舊的用戶,而不要再用 su 切換至舊用戶,否則會生成很多的bash子進程,環境可能會混亂。

換個身份執行命令:

su [-] UserName -c 'COMMAND'
范例:

[root@centos8 ~]#getent passwd mage
mage:x:1001:1001::/home/mage:/bin/bash
[root@centos8 ~]#usermod -s /bin/false mage
[root@centos8 ~]#getent passwd mage
mage:x:1001:1001::/home/mage:/bin/false
[root@centos8 ~]#su - mage
Last login: Fri Mar 27 09:18:57 CST 2020 on pts/0
[root@centos8 ~]#whomai
-bash: whomai: command not found
[root@centos8 ~]#whoami
root

范例:

[root@centos8 ~]#su -s /sbin/nologin wang
This account is currently not available.
[root@centos8 ~]#whoami
root
[root@centos8 ~]#su -s /bin/false wang
[root@centos8 ~]#whoami
root

范例:

[wang@centos8 ~]$su - root -c "getent shadow"

范例:

[root@centos8 ~]#su - wang -c 'touch wang.txt'
[root@centos8 ~]#ll ~wang/
total 0
-rw-rw-r-- 1 wang wang 0 Mar 27 09:31 wang1.txt
-rw-rw-r-- 1 wang wang 0 Mar 27 09:32 wang2.txt

范例:

[root@centos8 ~]#su bin
This account is currently not available.
[root@centos8 ~]#su -s /bin/bash bin
bash-4.4$ whoami
bin
bash-4.4$
[root@centos8 ~]#getent passwd tss
tss:x:59:59:Account used by the trousers package to sandbox the tcsd
daemon:/dev/null:/sbin/nologin
[root@centos8 ~]#su - -s /bin/bash tss
Last login: Fri Mar 27 09:46:43 CST 2020 on pts/0
su: warning: cannot change directory to /dev/null: Not a directory
-bash: /dev/null/.bash_profile: Not a directory
[tss@centos8 root]$pwd
/root
[tss@centos8 root]$whoami
tss


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM