CentOS 5.6でPHPのexec(), shell_exec()関数からsudoコマンドを実行するための設定方法を紹介します。
SELinuxの無効化
SELinuxを無効化します。手順については
こちらの記事を参照してください。
apacheユーザーへのパスワード設定
次のコマンドを実行し apache ユーザーにパスワードを設定します。
sudoersファイルの編集
次のコマンドを実行し sudoers ファイルを編集します。visudoコマンドを実行するとviが起動しsudoersファイルの編集になりますので、sudoersファイルの末尾に
apache ALL=(ALL) ALL
を追記します。
またsudoersファイル内の
Defaults requiretty
の行頭に#を付加してコメントアウトします。
#Defaults requiretty
動作確認
以下のphpファイルを用意し実行します。
'パスワード'の部分はapacheユーザーに設定したパスワードを記載します。
<?php
$results = shell_exec("echo 'パスワード' | sudo -S /bin/ls /root -lsa");
echo "<pre>$results</pre>";
?>
実行結果
コマンド実行に成功すると/rootディレクトリの内容が表示されます。
total 324
8 drwxr-x--- 18 root root 4096 May 24 22:36 .
8 drwxr-xr-x 24 root root 4096 May 23 01:25 ..
8 -rw------- 1 root root 2029 May 23 01:26 .ICEauthority
8 drwx------ 2 root root 4096 Apr 28 07:06 .Trash
8 -rw------- 1 root root 240 May 23 01:26 .Xauthority
8 drwx------ 2 root root 4096 Apr 28 08:42 .anthy
16 -rw------- 1 root root 11012 May 23 01:23 .bash_history
8 -rw-r--r-- 1 root root 24 Jan 6 2007 .bash_logout
8 -rw-r--r-- 1 root root 191 Jan 6 2007 .bash_profile
8 -rw-r--r-- 1 root root 176 Jan 6 2007 .bashrc
8 -rw-r--r-- 1 root root 100 Jan 6 2007 .cshrc
8 -rw------- 1 root root 26 Apr 28 07:06 .dmrc
8 drwxr-x--- 2 root root 4096 Apr 28 07:06 .eggcups
8 -rw------- 1 root root 16 Apr 28 07:07 .esd_auth
8 drwx------ 4 root root 4096 May 23 01:26 .gconf
8 drwx------ 2 root root 4096 May 24 21:56 .gconfd
8 drwxr-xr-x 3 root root 4096 Apr 28 07:06 .gnome
8 drwx------ 6 root root 4096 May 20 00:16 .gnome2
8 drwx------ 2 root root 4096 Apr 28 07:06 .gnome2_private
8 drwxr-xr-x 2 root root 4096 Apr 28 07:06 .gstreamer-0.10
8 -rw-r--r-- 1 root root 81 Apr 28 07:06 .gtkrc-1.2-gnome2
8 drwx------ 3 root root 4096 Apr 28 07:06 .metacity
8 drwx------ 4 root root 4096 Apr 28 23:13 .mozilla
8 drwxr-xr-x 3 root root 4096 May 20 00:16 .nautilus
20 -rw-r--r-- 1 root root 12425 May 24 22:36 .recently-used.xbel
8 drwxr-xr-x 3 root root 4096 Apr 28 07:06 .redhat
8 drwx------ 2 root root 4096 Apr 28 07:07 .scim
8 -rw-r--r-- 1 root root 129 Jan 6 2007 .tcshrc
8 drwxr-xr-x 2 root root 4096 May 23 01:26 .vnc
8 drwxr-xr-x 2 root root 4096 Apr 28 07:06 Desktop
8 -rw------- 1 root root 1250 Apr 28 03:18 anaconda-ks.cfg
52 -rw-r--r-- 1 root root 47083 Apr 28 03:18 install.log
4 -rw-r--r-- 1 root root 0 Apr 28 02:56 install.log.syslog
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2024-01-06
作成日: 2011-05-24