Linux普通用户提权-su、sudo

1、简介

1.1、需求

往往公司的服务器对外都是禁止root用户直接登录,所以我们通常使用的都是普通用户,那么问题来了?当我们使用普通用户执行/sbin目录下部门命令时,会发现没有权限,
这种情况会造成无法正常管理服务器,那如何才能不使用root用户直接登录系统,同时又保证普通用户能完成日常工作呢?

1.2、su、sudo特点

1.2.1、su

su:【全称switch user】身份切换,使用普通用户登录,然后使用su命令切换到root
优点:简单
缺点:需要知道root密码

1.2.2、sudo

sudo 提权,当需要使用root权限时进行提权,而无需切换至root用户
优点:安全、方便、 缺点:需要预先定义规则、较为复杂

2、su

2.1、Shell登陆的分类

登陆shell需要输入用户名和密码才能进入Shell日常接触的最多的一种。
非登陆shell不需要输入用户和密码就能进入Shell ,比如:运行bash 会开启一个新的会话窗口。

2.2、环境变量配置文件

2.2.1、profile、bashrc文件介绍

profile类文件:设定环境变量,登陆前运行的脚本和命令
bashrc类文件:设定本地变量,定义命令别名

2.2.2、环境变量配置文件位置

用户环境变量-配置文件:
~/.bash_profile
~/.bashrc

全局环境变量-配置文件:
/etc/profile
/etc/profile.d/*.sh
/etc/bashrc

2.2.3、Shell配置文件环境变量加载顺序

登录式:
/etc/profile -> /etc/profile.d/*.sh -> ~/.bash_profile -> ~/.bashrc -> /etc/bashrc

非登录式 
shell配置文件加载顺序: /.bashrc -> /etc/bashrc -> /etc/profile.d/*.sh

2.2.4、su与环境变量的关系

命令           解析
su - username  属于登陆式Shell 
su username    属于非登陆式Shell

它们最大的区别就在于加载的环境变量不一样;

2.3、示例

2.3.1、切换为root

[cyc@linux ~]$ su - root
Password: 
Last
login: Wed Apr 19 22:35:06 CST 2023 from 192.168.10.1 on pts/2 Last failed login: Thu Apr 20 10:50:37 CST 2023 on pts/3 There was 1 failed login attempt since the last successful login. [root@linux ~]# pwd /root

2.3.2、使用root身份,以某个用户的身份执行某个服务

[root@linux ~]# su - test -c 'ifconfig'
[root@linux ~]# su - test -c 'pwd'
/home/test

3、sudo

3.1、sudo由来

su命令在用户身份切换时,需要拿到root管理员密码;
在多人协作时,如果当中某个用户不小心泄露了root密码;那系统会变得非常不安全,为了改进这个问题,从而就有了sudo ; 当需要执行一些特权操作时,获取最高权限,但正常情况下还是普通用户,任然会受到系统的约束以及限制;

3.2、示例

3.2.1、创建用户分配wheel组进行提权

# root身份创建目录
mkdir /tmp/test_sudo

# 创建cyc用户,并且附属wheel组,注意:wheel组就拥有sudo权限
[root@linux ~]# useradd cyc
[root@linux ~]# usermod cyc -G wheel

[root@linux ~]# id cyc
uid=1000(cyc) gid=1005(cyc) groups=1005(cyc),10(wheel)

# 切换至cyc用户
[root@linux ~]# su - cyc
Last failed login: Thu Apr 20 10:50:22 CST 2023 from 192.168.10.1 on ssh:notty
There was 1 failed login attempt since the last successful login.
[cyc@linux ~]$ 

# 不能删除root身份的目录
[cyc@linux ~]$ rm -rf /tmp/test_sudo/
rm: cannot remove ‘/tmp/test_sudo/’: Operation not permitted

# 需要sudo提权,不过要输入当前用户的密码,再次确认
[cyc@linux ~]$ sudo rm -rf /tmp/test_sudo/

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for cyc: 

3.3、操作日志的安全审计

[root@linux ~]# tail -f /var/log/secure
...
Apr 20 11:03:28 ansible-control passwd: pam_unix(passwd:chauthtok): password changed for cyc
Apr 20 11:03:35 ansible-control sudo:     cyc : TTY=pts/2 ; PWD=/home/cyc ; USER=root ; COMMAND=/bin/rm -rf /tmp/test_sudo/ # 刚才操作的日志记录
...

 

posted @ 2023-04-20 11:09  小粉优化大师  阅读(485)  评论(0)    收藏  举报