以特定用户的身份从PHP运行命令行应用程序 [英] Running command-line application from PHP as specific user
问题描述
我在本地主机上运行Apache.通过以www-user身份运行的PHP脚本,我想控制我的机器上Rhythmbox的播放.到目前为止,我的PHP脚本中有一个简单的命令:
I am running Apache on my localhost. From a PHP script run as www-user I would like to control Rhythmbox playback on my machine. So far I have a simple command in my PHP script:
exec('rhythmbox-client --pause');
当我像我一样从命令行运行它时,这很好用,但是如果它以www-user身份运行,我想rhythmbox-client
不知道/无法访问我的Rhythmbox实例.
This works great when I run it from the command-line as me, but if it runs as www-user I guess rhythmbox-client
doesn't know/can't access my instance of Rhythmbox.
有没有一种简单的方法可以让该PHP脚本以我的用户而不是www-user的身份运行,或者告诉rhythmbox-client
要控制哪个实例?
Is there an easy way for that PHP script to run as my user rather than www-user, or to tell rhythmbox-client
which instance to control?
整个应用程序是,当我的电话摘机时,它将调用我的PHP脚本,该脚本暂停音乐,并在电话摘机时恢复播放.我爱VoIP电话!
The overall application is that when my phone goes off-hook it calls my PHP script which pauses music, and resumes playback when the phone is on-hook. I love VoIP phones!
解决方案:
多亏了Carpetsmoker和Tarek,我使用sudo
作为答案,但是存在一些问题.为了克服它们,我做了以下工作:
Solution:
Thanks to Carpetsmoker and Tarek I used sudo
as the answer but there was a couple of problems. To overcome them I did the following:
创建了一个bash脚本来调用rhythmbox-client
.该bash脚本是使用PHP中的sudo
执行的,如下面的答案所述.不幸的是,rhythmbox-client
不知道要控制什么环境,因此bash脚本如下所示:
Created a bash script to call rhythmbox-client
. This bash script was executed using sudo
in PHP as described in the answer below. Unfortunately rhythmbox-client
didn't know what environment to control, so the bash script looks like this:
#! /bin/bash
DBUS_ADDRESS=`grep -z DBUS_SESSION_BUS_ADDRESS /proc/*/environ 2> /dev/null| sed 's/DBUS/\nDBUS/g' | tail -n 1`
if [ "x$DBUS_ADDRESS" != "x" ]; then
export $DBUS_ADDRESS
/usr/bin/rhythmbox-client --pause
fi
现在,bash脚本可以由PHP和wwwuser执行,并且我的手机可以暂停/播放音乐!
Now that bash script can be executed by PHP and wwwuser, and my phone can pause/play my music!
推荐答案
一种解决方案是使用sudo(8)
:
exec('sudo -u myuser ls /');
很明显,您将需要设置sudo(8)
,以允许运行Web服务器的用户调用它.使用visudo(8)
编辑sudoers文件,可以使用类似以下内容的文件:
You will, obviously, need to setup sudo(8)
to allow the user running your webserver to invoke it. Editing the sudoers file with visudo(8)
, you can use something like:
wwwuser ALL=/usr/bin/rhythmbox-client
为了防止Apache能够运行其他命令,并且仅 rythymbox命令.
To prevent Apache from being able to run other commands and only the rythymbox command.
这篇关于以特定用户的身份从PHP运行命令行应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!