@TOC
一、su命令介绍
su(switch user)命令在Linux系统中用于切换当前用户的身份,通常用来从普通用户切换到超级用户(root),但也支持切换到其他非特权用户。
二、su命令的使用帮助
2.1 su命令的帮助信息
在命令行终端中,我们使用
-h
选项查su命令的基本帮助信息。
root@jeven01:~# su -h
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
-h, --help display this help
-V, --version display version
For more details see su(1).
AI 代码解读
2.2 su命令帮助解释
语法:
su [选项] [-] [<用户> [<参数>...]]
AI 代码解读
功能:
更改有效用户ID和组ID为<用户>的ID。仅提供一个 -
参数时等同于指定了 -l
。如果未指定<用户>, 则默认为root。
选项:
选项 | 描述 |
---|---|
-m , -p , --preserve-environment |
不重置环境变量 |
-w , --whitelist-environment <列表> |
不重置指定的环境变量 |
-g , --group <组名> |
指定主要组 |
-G , --supp-group <组名> |
指定辅助组 |
- , -l , --login |
创建一个登录shell |
-c , --command <命令> |
将单个命令传递给shell执行 |
--session-command <命令> |
将单个命令传递给shell执行,但不创建新会话 |
-f , --fast |
将 -f 参数传递给shell(适用于 csh 或 tcsh) |
-s , --shell <shell> |
如果 /etc/shells 允许,则运行指定的 shell |
-P , --pty |
创建一个新的伪终端 |
-h , --help |
显示此帮助信息 |
-V , --version |
显示版本信息 |
三、su命令的基本使用
3.1 切换到root用户
默认情况下,不指定用户名时,su会尝试切换到root用户,系统将提示你输入root用户的密码。
admin@jeven01:~$ su Password: root@jeven01:/home/admin#
AI 代码解读
3.2 切换到另一个用户
指定用户名以切换到特定的用户账户,例如切换到名为admin的用户:
root@jeven01:/home/admin# su - admin
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
admin@jeven01:~$
AI 代码解读
3.3 保留当前环境
如果你不使用-、-l或--login选项,那么除了UID和GID之外,几乎所有的环境都会保持不变。这可能不是最佳的安全实践,因为某些敏感信息可能会留在环境中。
root@jeven01:~# su admin
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
admin@jeven01:/root$
AI 代码解读
3.4 执行单个命令
使用-c选项可以让你作为另一个用户执行单个命令。完成后,你将返回到原来的用户身份。
root@jeven01:~# su - -c "pwd" admin
/home/admin
AI 代码解读
四、总结
使用su切换到root用户时需要提供root密码,这赋予了对系统最高级别的控制权限。
每次使用su提升权限后,完成任务应立即退出该会话以减少风险暴露时间。
带有-或--login选项的su命令会初始化新的登录环境,这可能改变当前的工作目录和环境变量设置。
不带-或--login选项的su命令会保留原有用户的大部分环境变量,这可能导致安全风险或意外行为。
使用-c选项可以通过su执行单个命令而不需要完全切换用户会话,适合临时操作。
建议在日常操作中优先使用sudo而非su来执行特权命令,因为sudo提供了更细粒度的权限管理和日志记录。