Linux中sudo之后无需输入密码

前言

在Linux和其他类Unix操作系统中,只有root用户可以运行所有命令并在系统上执行某些关键操作,如安装和更新,删除包,创建用户和组,修改重要的系统配置文件等。同时,承担root用户角色的系统管理员可以允许其他正常系统用户在sudo命令和几个配置的帮助下运行某些命令以及执行包括上述的一些重要系统操作。sudo 表示 "superuser do"。 它允许已验证的用户以其他用户的身份来运行命令。在执行玩sudo之后需要输入当前用户的密码,这在日常操作中不是很方便。比如说,我们在shell脚本中执行sudo,这时候手动输入密码,这肯定是难以接受的。

普通用户配置NOPASSWD

Linux下/etc/sudoers配置文件,我们可以给指定用户或者用户组设置权限。我们通过visudo来编辑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
# Host_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

## Command Aliases
## These are groups of related commands...

## Installation and management of software
# Cmnd_Alias SOFTWARE = /bin/rpm, /usr/bin/up2date, /usr/bin/yum

## Services
# Cmnd_Alias SERVICES = /sbin/service, /sbin/chkconfig

## Updating the locate database
# Cmnd_Alias LOCATE = /usr/bin/updatedb

## Delegating permissions
# Cmnd_Alias DELEGATING = /usr/sbin/visudo, /bin/chown, /bin/chmod, /bin/chgrp

## Processes
# Cmnd_Alias PROCESSES = /bin/nice, /bin/kill, /usr/bin/kill, /usr/bin/killall

## Drivers
# Cmnd_Alias DRIVERS = /sbin/modprobe

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

## Allows members of the 'sys' group to run networking, software,
## service management apps and more.
# %sys ALL = NETWORKING, SOFTWARE, SERVICES, STORAGE, DELEGATING, PROCESSES, LOCATE, DRIVERS

## Allows people in group wheel to run all commands
# %wheel        ALL=(ALL)       ALL

## Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL
%test_group  ALL=NOPASSWD:/bin/kill,/usr/sbin/tcpdump

## Allows members of the users group to mount and unmount the
## cdrom as root
# %users  ALL=/sbin/mount /mnt/cdrom, /sbin/umount /mnt/cdrom

## Allows members of the users group to shutdown this system
# %users  localhost=/sbin/shutdown -h now

## Read drop-in files from /etc/sudoers.d (the # here does not mean a comment)
#includedir /etc/sudoers.d
tom  ALL=(ALL) NOPASSWD:ALL
lina  ALL=(ALL) NOPASSWD

我们可以在上述配置文件中新增执行用户或者用户组能执行哪些命令,可以NOPASSWD执行。

echo 密码 | sudo 命令

如果我们确实没有root权限,修改不了sudoers。我们也可以通过管道符在脚本中自动输入密码,比如说下面的启动java程序

echo 'testpassword' | sudo -S   nohup /usr/bin/java -jar test.jar &

这样我们就不用在启动脚本的时候还手动输入密码了。

你可能感兴趣的:(linux)