在php中使用sudo运行程序

Running program with sudo in php

本文关键字:sudo 运行 程序 php      更新时间:2023-10-16

我正在尝试通过PHP运行"lightled.py"(按钮RON)和"lightledoff.py"。这两个程序都包含GPIO库,并且需要root访问权限。按钮"ON"answers"OFF"直接打开和关闭led。按钮ON和OFF正常工作,但RON和ROFF不正常。如何运行需要root访问权限的python或c++程序?

<!doctype html>
<html>
    <head>
        <title>LED Test</title>
        <meta charset="UTF-8"/>
    </head>
    <body>
        <h1>Light Led</h1>
        <form method=GET action="index.php">
            <h3>Radio Led</h3>
            <input name="button" type="submit" value="RON">
            <input name="button" type="submit" value="ROFF">
            <h3>On Board Led for Test</h3>
            <input name="button" type="submit" value="ON">
            <input name="button" type="submit" value="OFF">
        </form>
        <?php
        if ($_GET["button"] == "RON") {
            system("echo raspberry | sudo -S python ./lightled.py");
        };
        if ($_GET["button"] == "ROFF") {
            system("echo raspberry | sudo -S python ./lightledoff.py");
        };
        if ($_GET["button"] == "ON") {
            system("gpio -g mode 17 out");
            system("gpio -g write 17 1");
        };
        if ($_GET["button"] == "OFF") {
            system("gpio -g mode 17 out");
            system("gpio -g write 17 0");
        };
        ?>
    </body>
</html>

您要做的是从没有权限的用户运行sudo命令,即使在以root身份运行PHP框架时,生成的用户(框架用户)也不会被sudo提升为root权限。

您必须将运行PHP脚本的框架添加到sudoers文件中,并且您应该能够通过sudo命令以root身份执行这些文件,就像您已经尝试过的那样。要做到这一点,您需要以root身份运行命令visudo,并向用户添加一个条目,如下所示:

# User Privilege Specification
root   ALL=(ALL) ALL
PHPFramework ALL=(ALL) ALL

如果你不想给PHP框架所有的根权限(我建议你这样做,即使它只是本地运行的一个小RPi),你必须编辑sudo文件,更具体地说,要阅读主题谷歌"visudo-privaleges",这是我发现的第一个点击:https://www.garron.me/en/linux/visudo-command-sudoers-file-sudo-default-editor.html

通过sudo只允许运行python脚本的示例:

# User Privilege Specification

PHPFramework ALL=/path/to/file/lightled.py; /path/to/python_install

其中PHPFramework是部署方法的名称,对于apache,它将是"apache"(没有qoutes)。

''我最近发布了一个项目,该项目允许PHP获得真正的Bash shell并与之交互。在这里获取:https://github.com/merlinthemagic/MTS

下载后,您只需使用以下代码:

    $shell    = MTSFactories::getDevices()->getLocalHost()->getShell('bash', true);
   //insert command 
    $strCmd = 'echo raspberry | sudo -S python ./lightled.py';
    $return  = $shell->exeCmd($strCmd);
    //handle any return and issue next command into the shell