su 切換使用者

  1. su:轉換帳號身份。
    [root@kvm8 ~]# su --help
    
    Usage:
     su [options] [-] [<user> [<argument>...]]
    
    Change the effective user ID and group ID to that of <user>.
    A mere - implies -l.  If <user> is not given, root is assumed.
    
    Options:
     -m, -p, --preserve-environment      do not reset environment variables
     -w, --whitelist-environment <list>  don't reset specified variables
    
     -g, --group <group>             specify the primary group
     -G, --supp-group <group>        specify a supplemental group
    
     -, -l, --login                  make the shell a login shell
     -c, --command <command>         pass a single command to the shell with -c
     --session-command <command>     pass a single command to the shell with -c
                                       and do not create a new session
     -f, --fast                      pass -f to the shell (for csh or tcsh)
     -s, --shell <shell>             run <shell> if /etc/shells allows it
     -P, --pty                       create a new pseudo-terminal
     -T, --no-pty                    do not create a new pseudo-terminal (bad security!)
    
     -h, --help                      display this help
     -V, --version                   display version
    
    For more details see su(1).
    
    參數:
    -, -l, --login username :變換身份為 username,沒指定 username 則為 root,
           取得一個新的 shell,且使用 username 的所有相關環境設定檔。
    -m, -p, --preserve-environment :使用目前的環境設定,而不重新讀取新使用者的設定檔。
    -c, --command <command>  :僅進行一次指令 command。
    
  2. su - 登入 deyu1,使用 deyu1 的環境變數,所在目錄為 deyu1 的家目錄。
    [root@kvm8 ~]# su --login deyu1
    Last login: Wed Oct 22 14:14:00 CST 2025 from 192.168.122.8 on pts/1
    [deyu1@kvm8 ~]$ pwd
    /home/deyu1
    [deyu1@kvm8 ~]$
    logout
    
  3. su 切換為帳號 deyu1,使用原帳號 root 的環境變數,所在目錄為 root 的家目錄。
    [root@kvm8 ~]# su deyu1
    [deyu1@kvm8 root]$ pwd
    /root
    [deyu1@kvm8 root]$
    exit
    
  4. 由帳號 deyu1 使用 su 變換身份為 root,使用原帳號 deyu1 的環境變數,所以所在目錄為 deyu1 的家目錄。
    [deyu1@kvm8 ~]$ su
    Password: 
    [root@kvm8 deyu1]# pwd
    /home/deyu1
    [root@kvm8 deyu1]# exit
    exit
    
  5. 由帳號 deyu1 使用 su - 變換身份為 root,使用帳號 root 的環境變數,所以所在目錄為 root 的家目錄。
    [deyu1@kvm8 ~]$ su -
    Password:
    Last login: Wed Oct 22 13:35:12 CST 2025 from 192.168.122.1 on pts/0
    [root@kvm8 ~]# pwd
    /root
    [deyu1@kvm8 ~]$ exit
    logout