sudo 以不同用户身份运行命令

sudo 以不同用户身份运行命令

我正在尝试设置一个将以“maint”用户身份运行的脚本。该脚本基本上是一个菜单,允许维护人员在服务器上执行不同的操作。
但是,maint 菜单将执行的某些脚本必须以特定用户身份运行才能正常工作。

我的问题是如何使用 sudo 执行上述命令并且不需要密码。请记住,从菜单内执行的脚本实际上必须以不同的用户身份运行。这是我尝试过并试图完成的演示。

文件“sudoTest”位于 /home/user1/ 文件“testSudo”位于 /home/maint

“sudoTest”目前看起来像这样:

#!/bin/bash

echo "I am in sudoTest"
whoami

“testSudo”目前看起来像这样:

#!/bin/bash

sudo -u user1 /home/user1/sudoTest

我的目标基本上是,当我以用户 maint 身份登录并运行“testSudo”时,whoami 命令的输出将是“user1”

当我使用 visudo 命令时,文件当前的样子如下

#
# This file MUST be edited with the 'visudo' command as root.
#
# Please consider adding local content in /etc/sudoers.d/ instead of
# directly modifying this file.
#
# See the man page for details on how to write a sudoers file.
#
Defaults        env_reset
Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL
maint   ALL= NOPASSWD: /home/user1/*

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d        

另一件奇怪的事情是,当我从命令行执行此操作时:

sudo /home/user1/sudoTest

它允许我运行脚本并得到输出:

我在 sudoTest root

但是当我尝试执行“testSudo”时,它会要求输入密码,当我输入密码时,我得到以下返回:

抱歉,用户 maint 无权以 user1 身份执行“/home/user1/testSudo”

谢谢你的帮助!

答案1

我发现了这个问题。

问题是 sudoers 文件缺少一部分

# User privilege specification
root    ALL=(ALL:ALL) ALL
maint   ALL= NOPASSWD: /home/user1/*

应该

# User privilege specification
root    ALL=(ALL:ALL) ALL
maint   ALL=(ALL) NOPASSWD: /home/user1/*

答案2

我相信您是以调用脚本的用户身份运行该脚本的,而不是以 sudo 用户身份运行。以下是 sudo 手册页的摘录。

 -i [command]
                   The -i (simulate initial login) option runs the shell
                   specified in the passwd(5) entry of the target user as a
                   login shell.  This means that login-specific resource files
                   such as .profile or .login will be read by the shell.  If a
                   command is specified, it is passed to the shell for
                   execution.  Otherwise, an interactive shell is executed.
                   sudo attempts to change to that user's home directory
                   before running the shell.  It also initializes the
                   environment, leaving DISPLAY and TERM unchanged, setting
                   HOME, MAIL, SHELL, USER, LOGNAME, and PATH, as well as the
                   contents of /etc/environment on Linux and AIX systems.  All
                   other environment variables are removed.

相关内容