Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏多维度架构

14.7. sudo, sudoedit - execute a command as another user

		
debian:~# apt-get install sudo		
		
		

14.7.1. /etc/sudoers

sudo的配置文件是/etc/sudoers,visudo修改时会锁住sudoers文件,保存修改到临时文件,然后检查文件格式,确保正确后才会覆盖sudoers文件. 必须保证sudoers格式正确,否则sudo将无法运行.

/etc/sudoers

		
# /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.
#

Defaults        env_reset

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL) ALL

# Uncomment to allow members of group sudo to not need a password
# (Note that later entries override this, so you might need to move
# it further down)
%sudo ALL=NOPASSWD: ALL
		
			
			

sudo group

		
neo@debian:/etc/mysql$ cat /etc/group | grep 'sudo'
sudo:x:27:neo		
			
			

14.7.2. /etc/sudoers

visudo调用的默认编辑器是vi,如果要临时使用其他编辑器,在该命令前加上EDITOR环境变量即可.

				
[root@netkiller ~]# EDITOR=vim visudo
			
			

14.7.3. 设置示例

		
			
>1 允许neo用户从任何主机登录,以root的身份执行/usr/sbin/useradd命令

neo   ALL=(root) /usr/sbin/useradd 

>2 允许jam用户从任何主机登录,以root的身份无密码使用sudo执行/sbin/iptables -n -t filter -L 

jam   ALL=(ALL) NOPASSWD: /sbin/iptables -n -t filter -L 

>3 neo用户从任何主机登录,以root的身份执行自定义命令链里面的命令

Cmnd_Alias USERCOMMAND = /sbin/route,/sbin/ifconfig,/bin/ping,/sbin/dhclient,/usr/bin/net,/sbin/iptables,/usr/bin/rfcomm,/usr/bin/wvdial,/sbin/iwconfig
neo   ALL=(root)    USERCOMMAND
			
			
			

14.7.4. NOPASSWD

ubuntu NOPASSWD sudo的时候不需要输入密码

		
%admin ALL=(ALL)ALL
改为
%admin ALL=(ALL) NOPASSWD: NOPASSWD: ALL	
			
			

用户

		
www localhost=NOPASSWD: /bin/cat, /bin/ls			
			
			

14.7.5. 允许或禁止命令

命令前面加‘!’可以禁止用户运行该命令

		
neo ALL = (root) /bin/mount, /bin/umount, !/bin/mount /data0
dba ALL = /bin/mount /u0[1-5], /bin/umount /u0[1-5]
			
			

14.7.6. Cmnd_Alias 用法

Cmnd_Alias 定义命令别名

		
Cmnd_Alias WEBMASTER = /srv/nginx/sbin/nginx, /srv/php/sbin/php-fpm, !/srv/mysql/bin/mysql
www localhost = NETWORKING, SERVICES, DELEGATING, PROCESSES, WEBMASTER
			
			

自定义用户组(以所有的身份)执行自定义的命令链里的命令

		
Cmnd_Alias USERCOMMAND = /sbin/route,/sbin/ifconfig,/bin/ping,/usr/sbin/mtr,/bin/traceroute,/usr/bin/top,/bin/df,/usr/bin/free,/usr/bin/du,/bin/ls,/bin/date,/usr/bin/less
User_Alias    ADMINS = user1, user2
ADMINS	ALL=(ALL)	USERCOMMAND			
			
			

14.7.7. wheel 组

		
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
neo     ALL=(ALL)       ALL
%wheel  ALL=(ALL)       ALL
			
			

将用户加入到 wheel 组

		
			
[root@localhost ~]# usermod -aG wheel www
			
			
			

14.7.8. 注意事项

		
1 修改sudo记录密码的时间


Defaults:用户名 timestamp_timeout=20
eg:
Defaults:redhat timestamp_timeout=20

2 默认sudo命令只能在tty上执行,注释掉下面选项可以使程序调用sudo命令

Defaults    requiretty