Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
164
Help us understand the problem. What is going on with this article?
@akito1986

sudo時にPATHを引き継ぐ方法

More than 5 years have passed since last update.

背景

sudoしたときにせっかく設定したrubyやらrubygemが見つからないよって、言われて嫌な気持ちになったので対処方法を残しておく、

以下環境情報。

  • ubuntu: 12.04

デフォルト設定

デフォルトの設定ではsudo実行ユーザのPATHは引き継がれずに、ユーザ固有のPATHに指定したコマンドは失敗する。

path_not_found
$ gem list | head -5
bigdecimal (1.2.4)
fluent-logger (0.4.9)
hirb (0.7.2)
httpclient (2.3.4.1)
io-console (0.4.2)
$ sudo gem list | head -5
sudo: gem: command not found
$ env | grep PATH
PATH=/usr/local/rbenv/shims:/usr/local/rbenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
$ sudo env | grep PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

これはデフォルトの/etc/sudoersが以下のようにsecurity_pathを指定してPATHを固定しているため。

/etc/sudoers
#
# 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

設定変更

visudoコマンドで以下のようにsecure_pathをコメントアウトして、env_keepPATHを追加すれば、sudo実行ユーザが使っていたコマンドが使えるようになる。

visudo(/etc/sudoers)
#
# 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"
Defaults    env_keep += "PATH"

env_keepにはPATHだけでなく環境変数で指定しているものはなんでも入れて良さげ。

ここで注意することは、PATHを引き継いでしまうとsecurity_pathで指定されていた/sbinなどの管理系のコマンドのPATHが設定されなくなってしまうので注意。

変更確認

以下のコマンドでPATHが引き継がれていることを確認。

check_path
$ env | grep PATH
PATH=/usr/local/rbenv/shims:/usr/local/rbenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
$ sudo env | grep PATH
PATH=/usr/local/rbenv/shims:/usr/local/rbenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
$ 
$ sudo gem list | head -5
bigdecimal (1.2.4)
fluent-logger (0.4.9)
hirb (0.7.2)
httpclient (2.3.4.1)
io-console (0.4.2)
$ 

おしまい。

164
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
164
Help us understand the problem. What is going on with this article?