Soul torture! Difference between Linux command su and sudo?

Source: Jun Tao

Address: https://tanjuntao.github.io/

I have been confused about suand sudothese two commands before. I recently searched for information on this, and finally figured out the relationship and usage of the two. This article will summarize it systematically.

1. Preparations

Because user switching is involved in this blog, I need to prepare several test users in advance to facilitate subsequent switching.

The command for creating a new user in Linux is useraddthat the path corresponding to this command in the general system is in the PATHenvironment variable. If the direct input useradddoes not work, the absolute path name is used: /usr/sbin/useradd.

useraddThe new user command can only be executed by the root user. We first switch from the ordinary user ubuntu to the root user (how to switch will be introduced later):

ubuntu@VM-0-14-ubuntu:~$ su -
Password:                                         # 输入 root 用户登录密码
root@VM-0-14-ubuntu:~# useradd -m test_user       # 带上 -m 参数
root@VM-0-14-ubuntu:~# ls /home
test_user  ubuntu                                 # 可以看到 /home 目录下面有两个用户了

Because the login password has not been set for the newly created test_useruser , we cannot switch from the normal user ubuntu to test_user, so next, we need to use root to set the login password of test_user. You need to use passwdthe command :

root@VM-0-14-ubuntu:~# passwd test_user
Enter new UNIX password:                          # 输出 test_user 的密码
Retype new UNIX password:       
passwd: password updated successfully
root@VM-0-14-ubuntu:~#

Then we enter exitto exit the root user to the ordinary user ubuntu:

root@VM-0-14-ubuntu:~# exit
logout
ubuntu@VM-0-14-ubuntu:~$

As you can see, the front of the command prompt has changed from rootto ubuntu, indicating that our current identity is the ubuntuuser .

2. suCommand introduction and main usage

First you need suto what it means.

I always thought it suwas super usertrue before, but only after I checked the information did I find out what it said switch user.

suAfter knowing what abbreviation is from, then the function it provides is obvious, which is to switch users .

2.1 -Parameters

suThe general usage is:

su  <user_name>

or

su - <user_name>

The difference between the two methods is only one character -, and there will be a big difference:

The light explanation will be more abstract, and it will be easier to understand if we look at an example.

We first switch from the ubuntu user to the root user in non-login-shellthe way, and compare PWDthe values ​​of the environment variables in the two user states (the sucommand does not follow any <user_name>, and the default switch to the root user):

ubuntu@VM-0-14-ubuntu:~$ env | grep ubuntu
USER=ubuntu
PWD=/home/ubuntu                                         # 是 /home/ubuntu
HOME=/home/ubuntu
# 省略......
ubuntu@VM-0-14-ubuntu:~$ su                              # non-login-shell 方式
Password:                                                # 输入 root 用户登录密码
root@VM-0-14-ubuntu:/home/ubuntu# env | grep ubuntu
PWD=/home/ubuntu                                         # 可以发现还是 /home/ubuntu
root@VM-0-14-ubuntu:/home/ubuntu#

We did switch to the root user, but the variables in the shell environment have not changed, and the environment variables of the previous ubuntu user are still used.

Then we switch from the ubuntu user to the root user in login-shellthe way, and also compare PWDthe values ​​of the environment variables under the two user turntables:

ubuntu@VM-0-14-ubuntu:~$ env | grep ubuntu
USER=ubuntu
PWD=/home/ubuntu                               # 是 /home/ubuntu
HOME=/home/ubuntu
# 省略.......
ubuntu@VM-0-14-ubuntu:~$ su -                  # 是 login-shell 方式
Password:
root@VM-0-14-ubuntu:~# env | grep root
USER=root
PWD=/root                                      # 已经变成 /root 了
HOME=/root
MAIL=/var/mail/root
LOGNAME=root
root@VM-0-14-ubuntu:~#

It can be seen that if the user is switched using login-shellthe method, the environment variables in the shell are also changed.

Summary : Which method to use to switch users depends on personal needs:

  • If you do not want your settings under the current user to be unavailable due to switching to another user, use non-login-shellthe method;

  • If you need to use various environment variables of the user after switching users (the environment variable settings of different users are generally different), then use login-shellthe method.

2.2 Switch to the specified user

As mentioned earlier, if the sucommand is not followed by any <user_name>, the default is to switch to the root user:

ubuntu@VM-0-14-ubuntu:~$ su -
Password:                                       # root 用户的密码
root@VM-0-14-ubuntu:/home/ubuntu#

Since we have created a new test_user user in the 1. 准备工作section , and we also know the login password of the test_user user (set by the root user), we can switch from the ubuntu user to the test_user user:

ubuntu@VM-0-14-ubuntu:~$ su - test_user
Password:                                       # test_user 用户的密码
$

2.3 -cParameters

In the previous method, we first switch to another user (root or test_user), execute the command in the state of which user, and finally enter exitto return to the current ubuntu user.

There is another way: you do not need to switch users before executing the command, you can directly execute the command under the current user in the way of another user, and return to the current user after the execution. This requires the use of -cparameters .

In addition, the Linux series of interview questions and answers are all sorted out. Wechat searches the Java technology stack and sends it in the background: interview, which can be read online.

The specific use method is:

su - -c "指令串"                                  # 以 root 的方式执行 "指令串"

Let me see an example:

ubuntu@VM-0-14-ubuntu:~$ cat /etc/shadow
cat: /etc/shadow: Permission denied                # ubuntu 用户不能直接查看 /etc/shadow 文件内容

ubuntu@VM-0-14-ubuntu:~$ su - -c "tail -n 4 /etc/shadow"
Password:                                          # 输入 root 用户密码
ubuntu:$1$fZKcWEDI$uwZ64uFvVbwpHTbCSgim0/:18352:0:99999:7:::
ntp:*:17752:0:99999:7:::
mysql:!:18376:0:99999:7:::
test_user:$6$.ZY1lj4m$ii0x9CG8h.JHlh6zKbfBXRuolJmIDBHAd5eqhvW7lbUQXTRS//89jcuTzRilKqRkP8YbYW4VPxmTVHWRLYNGS/:18406:0:99999:7:::
ubuntu@VM-0-14-ubuntu:~$                            # 执行完马上返回 ubuntu 用户而不是 root 用户

This execution method is sudovery similar . It is a temporary application for the permission of the root user. But there are still differences, and we'll see later.

3. sudoCommand introduction and main usage

First, let's explain what the sudocommand means.

sudoThe full English name is super user do, that is, to execute commands as a super user (root user). sudoHere issu different from what was represented before, which needs attention and is easy to confuse.switch user

We first describe what sudocommands can do, then explain why and how.

Let's start.

3.1 Main usage

We often encounter Permission deniedthis , such as viewing /etc/shadowcontent as an ubuntu user. Because the contents of this file can only be viewed by the root user.

So what if we want to check it out? Then you can use sudo:

ubuntu@VM-0-14-ubuntu:~$ tail -n 3 /etc/shadow
tail: cannot open '/etc/shadow' for reading: Permission denied      # 没有权限
ubuntu@VM-0-14-ubuntu:~$ sudo !!                                    # 跟两个惊叹号
sudo tail -n 3 /etc/shadow
ntp:*:17752:0:99999:7:::
mysql:!:18376:0:99999:7:::
test_user:$6$.ZY1lj4m$ii0x9CG8h.JHlh6zKbfBXRuolJmIDBHAd5eqhvW7lbUQXTRS//89jcuTzRilKqRkP8YbYW4VPxmTVHWRLYNGS/:18406:0:99999:7:::
ubuntu@VM-0-14-ubuntu:~$

In the example, we use sudo !!this little trick to repeat the command entered above, but add it at the top of the command sudo.

Because I have set the sudocommand to not need to enter a password, the sudo !!content can be output directly here. If it is not set, you need to enter the password of the current user. For example, in this example, I should enter the login password of the ubuntu user.

For two adjacent sudooperations , if the interval 5minis within , you sudodo not need ; if it exceeds 5min, you need to enter the password again sudowhen entering . So a more hassle-free method is to set the sudooperation without a password. How to set it will be described later.

sudoIn addition to executing commands with the authority of the root user, there are several other usages, which are briefly introduced here.

Switch to root user:

sudo su -

This method can also switch to the root user in login-shellthe way, but it su -is different from the method by:

  • sudo su -After entering the former , you need to provide the login password of the current user, that is, the password of the ubuntu user;

  • su -After the latter is entered , the login password of the root user is required.

There is one more command:

sudo -i

This command has the same sudo su -effect . It also switches to the root user, and also needs to provide the login password of the current user (ubuntu user).

We now switch to the test_user user and try to display the contents of the /etc/shadowfile :

ubuntu@VM-0-14-ubuntu:~$ su - test_user
Password:                                       # test_user 的密码
$ sudo cat /etc/shadow
[sudo] password for test_user:                  # test_user 的密码
test_user is not in the sudoers file.  This incident will be reported.
$

We see the error message in the penultimate line, we can't see /etc/shadowthe content of , why? Why ubuntu can be used sudobut test_user can't?

Here sudo's how it works.

3.2 sudoWorking principle

Whether a user can use the sudocommand depends on /etc/sudoersthe settings of the file.

From Section 3.1, we have seen that the ubuntu user can be used normally sudo, but the test_user user cannot be used because the test_user is not configured in the /etc/sudoersfile .

/etc/sudoersIt is also a text file, but because of its specific syntax, we do not directly use vimor vito edit it, we need to use visudothis command. After entering this command, you can directly edit /etc/sudoersthe file.

It should be noted that only the root user has permission to use visudocommands .

Let's first look at what is displayed after entering the visudocommand .

Enter (root user):

root@VM-0-14-ubuntu:~# visudo

output:

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d
ubuntu  ALL=(ALL:ALL) NOPASSWD: ALL

Explain the format of each line:

We also ubuntunoticed that there is a NOPASSWDkeyword in the corresponding line, which means that the ubuntu user does not need to enter a password sudowhen and the previous problem is explained here.

At the same time, we noticed that there is no test_usercorresponding , which explains why test_user cannot use the sudocommand.

Next, we try to add test_user to the /etc/sudoersfile so that test_user can also use the sudocommand. We add on the last line:

test_user  ALL=(ALL:ALL)  ALL       # test_user 使用 sudo 需要提供 test_user 的密码

Next we execute it under the test_user account sudo:

ubuntu@VM-0-14-ubuntu:~$ su - test_user
Password:
$ tail -n 3 /etc/shadow
tail: cannot open '/etc/shadow' for reading: Permission denied
$ sudo tail -n 3 /etc/shadow                   # 加上 sudo
ntp:*:17752:0:99999:7:::
mysql:!:18376:0:99999:7:::
test_user:$6$.ZY1lj4m$ii0x9CG8h.JHlh6zKbfBXRuolJmIDBHAd5eqhvW7lbUQXTRS//89jcuTzRilKqRkP8YbYW4VPxmTVHWRLYNGS/:18406:0:99999:7:::
$

As you can see, it is now ready sudoto .

3.3 Thinking

We have already seen that if a user is in the /etc/sudoersfile , then it has sudopermission, and sudo su -can sudo -iswitch to the root user through or other commands, then the user becomes the root user, which does not cause great damage to the system. Threat?

In fact it is. Therefore, when editing a /etc/sudoersfile to grant a certain user sudoauthority, it must be determined that the user is trustworthy and will not cause malicious damage to the system, otherwise it will be very dangerous to grant all root authority to this user.

Of course, the root user can also edit /etc/sudoersso that the user only has some permissions, that is, only a small number of commands can be executed. Interested readers can refer to the second article in the Reference section, which will not be repeated in this article. In addition, the Linux series of interview questions and answers are all sorted out. Wechat searches the Java technology stack and sends it in the background: interview, which can be read online.

4. Comparison of the differences between the two

We have seen:

  • Use su -, provide the password of the root account, you can switch to the root user;

  • Use sudo su -, provide the password of the current user, or switch to the root user

The difference between the two methods is also obvious: if our Linux system has many users who need to use it, the former requires all users to know the password of the root user, which is obviously very dangerous; the latter does not need to expose the password of the root account, the user You only need to enter your own account password, and which users can switch to root, this is completely controlled by root (root is /etc/sudoersimplemented ), so the system is much safer.

It is generally recommended sudoto . In addition, pay attention to the Java technology stack of the public account, and reply in the background: Interview, you can get the Java and Linux series of interview questions and answers that I have compiled, which are very complete.

References

  • https://www.rootusers.com/the-difference-between-su-and-sudo-commands-in-linux/

  • "Brother Bird's Linux Private Kitchen" Section 13.4: User Identity Switching

  • https://github.com/ustclug/Linux101-docs/blob/master/docs/Ch05/index.md

  • https://www.maketecheasier.com/differences-between-su-sudo-su-sudo-s-sudo-i/

  • https://stackoverflow.com/questions/35999671/whats-the-difference-between-sudo-i-and-sudo-su?r=SearchResults

  • https://www.zhihu.com/question/51746286

  • https://www.linuxidc.com/Linux/2017-06/144916.htm

 
  
 
  
 
  

Interested students can quickly join our planet

3 weeks zero basic introduction provides 10 lessons

12 interesting practical projects throughout the year including source code,

Reward outstanding Top3 students every month to send books

Professional Q&A group, nanny-style teaching by Dachang teachers

If you are not satisfied, feel free to refund within three days! 88 a year, now 16 yuan off

1bdf1bdb4c2450ffc255e2a566233817.png

Scan the code to join, get started with zero basics in 3 weeks

推荐阅读:
入门: 最全的零基础学Python的问题  | 零基础学了8个月的Python  | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 |   从万众期待到口碑扑街!唐探3令人失望  | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏  | 九宫格  | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!|  再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|

The year's hottest copy

Click to read the original text to see 200 Python cases!

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326956559&siteId=291194637
Recommended