探索 Linux 中 sudo 和 su 命令之间的区别
本文探讨了Linux 中sudo
和su
命令之间的区别。您还可以观看此视频以了解这些命令。使用 永久成为 root 是su
*nix 世界中众所周知的“禁忌”。为什么?因为使用 成为 rootsu
意味着您是 root,这等同于使用 root 密码以 root 用户身份登录终端。出于多种原因,这很危险。
[ 你可能还喜欢: Linux 命令行基础知识:sudo ]
以 root 身份工作意味着您有以下权限:
- 删除任意或所有文件
- 更改任何或所有文件的权限
- 更改系统的运行级别
- 修改用户账户
- 挂载或卸载文件系统
- 删除或安装软件
- 创建、删除和更改文件系统
基本上,您可以以 root 用户身份对系统执行任何操作。它是全能的管理帐户。而且,与其他更繁琐的操作系统不同,您不会看到“您确定吗?”对话框,以确保您rm -rf *
刚刚发出的命令是在/opt/tmp
而不是 at /
。您可以想象,以 root 用户身份犯下的错误可能是不可逆转的,而且是毁灭性的。还有另一种选择:sudo
。
须藤
sudo
是superuser do 或 substitute user do的首字母缩写,是运行提升提示符而无需更改身份的命令。根据文件中的设置/etc/sudoers
,您可以以 root 或其他用户身份发出单个命令。要继续以 root 权限运行命令,您必须始终使用 sudo 命令。例如,如果要安装 Nginx 包,请运行:
$ dnf install nginx
但是,如果您不是 root 或不属于 sudo 组,则会看到错误。相反,如果您运行以下命令:
$ sudo dnf install nginx
系统将要求您输入密码,然后如果您属于 sudo 组的一部分,您就可以运行该命令。
以 root 用户身份切换到交互式会话的简单方法如下:
$ sudo -i
使用 sudo 背后的理论是,在运行任何命令之前发出 sudo 命令的行为会让您更多地考虑您正在做的事情,并希望使用拥有无限权力的帐户犯更少的错误。
苏
su
另一方面,是切换用户或替代用户的首字母缩写。您基本上是切换到特定用户,并且需要要切换到的用户的密码。通常,您切换到的用户帐户是 root 帐户,但它可以是系统上的任何帐户。
例如,如果您输入:
$ su -
In the above example, you are switching to root and you need the root password. The (-
) switch provides you with root's environment (path and shell variables) rather than simply giving you root user power for a single command while keeping your own environment.
$ su bryant
For the second example, you are switching to bryant, and so you need bryant's password unless you are root.
If you want to switch to the bryant user account including bryant's path and environment variables, use the (-
) switch:
$ su - bryant
The (-
) switch has the same effect as logging into a system directly with that user account. In essence, you become that user.
Wrap up
Recapping what you've learned.
sudo
lets you issue commands as another user without changing your identity- You need to have an entry in
/etc/sudoers
to execute these restricted permissions sudo -i
brings you to an interactive session as rootsu
means to switch to a particular user- Just typing
su
switches to the root user sudo
will ask for your password, whilesu
will ask for the password for the user whom you are switching to
[ Want to learn more about security? Check out the IT security and compliance checklist. ]
But when do you use one, not another? Since the sudo
policy is defined in /etc/sudoers
, this can give powerful permission controls. Since sudo
can pretty much do everything that su
can, I would say it is best to stick with sudo
unless you are working with some legacy codes that require the su
command.