我以身份登录user1
并且有两个脚本,script1 尝试使用sudo -u user2
. 我的问题是,user1
尽管我指定-u
了sudo
. 这是我的设置:
脚本1:
#! /bin/bash
echo "Current user in script1:" $USER
# Call script2
sudo -u user2 /full/path/to/script2
Run Code Online (Sandbox Code Playgroud)脚本2:
#! /bin/bash
echo "Current user in script2:" $USER
# Execute command as user2
some-command-that-works
Run Code Online (Sandbox Code Playgroud)相当于/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
user1 ALL=(ALL:ALL) ALL
# Allow members of group sudo to execute any command
# (Note that later entries override this, so you might need to move
# it further down)
%sudo ALL=(ALL) ALL
#
#includedir /etc/sudoers.d
# Don't ask for user2 password for script2
user2 ALL= NOPASSWD: /full/path/to/script2
# FYI: I experimented with the line below for group1 that user1 is a member of
%group1 ALL= NOPASSWD: /full/path/to/script2
Run Code Online (Sandbox Code Playgroud)ls -blah
输出
drwxrwsr-x 2 user1 group1 4.0K Oct 19 15:22 .
drwxrwsr-x 7 user1 group1 4.0K Oct 18 18:48 ..
-rwxrwxr-x 1 user1 group1 180 Oct 20 17:37 script1
-rwx------ 1 user2 group1 166 Oct 20 16:29 script2
Run Code Online (Sandbox Code Playgroud)我的 shell 尝试运行的示例script1
:
user1@host1 /full/path/to/script1 $ script1
Current user in script1: user1
[sudo] password for user1:
Run Code Online (Sandbox Code Playgroud)
编辑:这是在我连接到的服务器上ssh
。服务器正在运行 Debian 6.0.4Squeeze
sudo -u <user>
授予用户以给定用户身份运行命令的权限。
它与su - <user>
将您切换到给定用户的 不同。 su - <user>
要求您输入给定用户的密码才能以该用户身份打开会话。
sudo -u <user>
除非NOPASSWD:
在 sudoers 文件中给出了标志,否则需要当前用户密码。
要实现您想要的功能,请将其添加到您的 sudoers 文件中
%group1 ALL=(user2) NOPASSWD: /full/path/to/script2
Run Code Online (Sandbox Code Playgroud)
这将允许 group1 以 user2 身份运行 script2,而无需输入密码。