可能不少情况下,你不一定能得到root用户的密码,或者至少root用户的密码不会广泛传播。但特殊的情况下,会授权给一些用户临时的去做一些只有root能做的事情,就像我们工作中的委托授权这样的事情,不可避免。
那么在linux下如果一个普通用户要执行一些越权的命令怎么来做呢?sudo
[lxf@localhost ~]$ useradd gujian
-bash: /usr/sbin/useradd: Permission denied
[lxf@localhost ~]$ passwd gujian
passwd: Only root can specify a user name.
[lxf@localhost ~]$ shutdown -r now
shutdown: Need to be root
[lxf@localhost ~]$ ls /root
ls: cannot open directory /root: Permission denied
1.1 /etc/sudoers
在man sudo的时候看到sudo的配置文件是/etc/sudoers,这个文件说简单也简单,说复杂也相当复杂。对于初学者,只需知道在此处配置,语法只需了解初步的即可。
文件权限
[root@testing ~]# ll /etc/sudoers
-r--r-----. 1 root root 3729 Dec 8 2015 /etc/sudoers
/etc/sudoers文件的权限是440,只有可读权限,无法写入(会提示read only,但其实还是可以写入wq!)
正确的编辑姿势应该是visudo,直接输入命令即可,之后就是跟vi一样的操作。先只看下91行。
90 ## Allow root to run any commands anywhere
91 root ALL=(ALL) ALL
92 lxf ALL=(ALL) ALL
保存退出的时候提示
visudo: >>> /etc/sudoers: syntax error near line 92 <<<
What now?
这也是为何要用visudo来编辑这个文件的原因之一了,可以检查语法是否正确,此处命令要写完整路径。那我们可以编辑成这样。
90 ## Allow root to run any commands anywhere
91 root ALL=(ALL) ALL
92 lxf ALL=(ALL) ALL
1.2 命令执行
[root@testing ~]# su – lxf
[lxf@localhost ~]$ useradd gujian
-bash: /usr/sbin/useradd: Permission denied
添加了权限,并非意味着可以直接执行useradd的命令了,要执行命令需要加sudo。正确的姿势是这样的:
[lxf@localhost ~]$ sudo useradd gujian
- 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 lxf:
[lxf@localhost ~]$ sudo ls /root
anaconda-ks.cfg Desktop Documents Downloads install.log install.log.syslog Music Pictures Public Templates test test1 Videos
[lxf@localhost ~]$ sudo shutdown -r 10:30
Broadcast message from root@localhost
(/dev/pts/1) at 10:24 ...
The system is going down for reboot in 6 minutes!
1.3 关于/etc/sudoers
90 ## Allow root to run any commands anywhere
91 root ALL=(ALL) ALL
root:表示root用户。
ALL:表示在任何主机上都可以,也可以表示192.168.232.0/24。
(ALL):表示以任何的身份。
ALL:表示可以执行任何命令。
整条语句的意思就是:root用户可以在任何机器上以任何身份执行任何命令。