Skip to content Skip to main navigation Skip to footer

CentOS/Linux:如何使用sudo命令

在linux系统中,由于root的权限过大,一般情况都不使用它。只有在一些特殊情况下才采用登录root执行管理任务,一般情况下临时使用root权限多采用su和sudo命令。
一、su和sudo命令对比:
在普通用户下输入su命令后,会提示输入root账户的密码,然后就进入特权模式(跟用root登录系统完全一样),输入exit或者su – user 退出:

$su
Password:
#ls /root
anaconda-ks.cfg  install.log  install.log.syslog
#exit
$ls /root
ls: cannot open directory /root: Permission denied #提示没有权限
 

而采用sudo命令,只需输入当前用户的密码(也可以配置为不输入密码)即可执行需要root权限执行的命令:

$ls /root
ls: cannot open directory /root: Permission denied #提示没有权限
 
$sudo ls /root
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 Oracle:    #输入普通用户oracle的密码
anaconda-ks.cfg  install.log  install.log.syslog
 

通过上面的对比可以看出,sudo比su有很多优点:
1、普通用户不需要知道root的密码即可执行需要root权限的命令;
2、不会因忘记退出而采用root执行了会引起破坏性的命令(初学linux经常犯这个错);
二、配置普通用户有使用sudo命令的权限:
在linux系统中,新建用户并没有执行sudo权限,如新建一个AAA的用户,输入sudo命令会有如下提示:

aaa is not in the sudoers file.  This incident will be reported.
 

这句的意思是在sudoers文件中不存在aaa这个用户,这个时间会被报告给管理员。既然知道问题处于sudoers这个文件,那我们就看看这个文件为何方神圣:

[root@dbs aaa]# vi /etc/sudoers
## Sudoers allows particular users to run various commands as
## the root user, without needing the root password.
##
## Examples are provided at the bottom of the file for collections
## of related commands, which can then be delegated out to particular
## users or groups.
##
## This file must be edited with the 'visudo' command.
## Host Aliases
## Groups of machines. You may prefer to use hostnames (perhaps using
## wildcards for entire domains) or IP addresses instead.
# Host_Alias     FILESERVERS = fs1, fs2
# ost_Alias     MAILSERVERS = smtp, smtp2
## User Aliases
## These aren't often necessary, as you can use regular groups
## (ie, from files, LDAP, NIS, etc) in this file - just use %groupname
## rather than USERALIAS
# User_Alias ADMINS = jsmith, mikem
 

输入i,对文件进行编辑,发现底部有只读提示:
— INSERT — W10: Warning: Changing a readonly file
应该是没有权限,退出编辑状态后查看权限:

[root@dbs aaa]# ll /etc/sudoers
-r--r-----. 1 root root 3825 Jul 22 01:05 /etc/sudoers
 

原来root也只有只读权限,难怪,首先修改权限以让root有完全控制权限:

[root@dbs aaa]#chmod 740 /etc/sudoers
 

再次编辑,这次没有出现只读提示了,找到如下字段:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
Oracle  ALL=(ALL)       ALL
aaa     ALL=(ALL)       ALL
 

添加aaa用户,添加后如aaa ALL=(ALL) ALL
修改完后输入:wq保存,保存后记得把权限修改回去,否则会有错误提示

#chmod 440 /etc/sudoers
 

权限一定是440,否则就会有错误提示。
OK,在aaa用户下就可以正常使用sudo命令咯。

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.