web-dev-qa-db-ja.com

別のユーザーとしてコマンドを実行するsudo

「maint」ユーザーとして実行されるスクリプトをセットアップしようとしています。スクリプトは基本的に、保守担当者がサーバー上でさまざまなことを実行できるようにするメニューです。
ただし、maintメニューが実行するスクリプトの一部は、正しく機能するために特定のユーザーとして実行する必要があります。

私の質問は、Sudoを使用してパスワードを必要とせずに上記のコマンドを実行するにはどうすればよいかということです。メニュー内から実行されるスクリプトは、実際には別のユーザーとして実行する必要があることに注意してください。これは私が試し、達成しようとしていることのデモです。

ファイル「sud​​oTest」は/ 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ルートにいます

しかし、「testSudo」を実行しようとするとパスワードを要求され、入力すると次のようになります。

申し訳ありませんが、ユーザーmaintはuser1として '/ home/user1/testSudo'を実行できません。

助けてくれてありがとう!

2
Dan

問題を見つけました。

問題は、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
Dan

スクリプトは、Sudoユーザーとしてではなく、スクリプトを呼び出したユーザーとして実行していると思います。これはSudoのmanページからの例外です。

 -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.
0
DragonZero