I am trying to run 'lightled.py'(button RON) and 'lightledoff.py'(button ROFF) through PHP. Both programs include GPIO library and needs root access. Button 'ON' and 'OFF' directly switches the led on and off. Button ON and OFF works properly but RON and ROFF doesn't. How do i run python or c++ programs that need root access?
<!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>
What you are trying to do is run the sudo command from a user that has no privileges, even when running the PHP framework as root, the user that is made (the framework user) is not elevated to root privileges by sudo.
You will have to add the framework that is running your PHP script to the sudoers file, and you should be able to execute the files as root through the sudo command, like you already tried to do. to do this you need to run the command visudo as root, and add an entry to the users that look like this:
# User Privilege Specification
root ALL=(ALL) ALL
PHPFramework ALL=(ALL) ALL
If you want not to give the PHP framework all root privileges (which I recommend even if it's just a little RPi running locally), you will have to edit the sudo file more specifically, to read up on the subject google 'visudo priveleges', this is one of the first hits I found: https://www.garron.me/en/linux/visudo-command-sudoers-file-sudo-default-editor.html
an example of just giving permission to run the python script via sudo:
# User Privilege Specification
PHPFramework ALL=/path/to/file/lightled.py; /path/to/python_install
where PHPFramework is the name of your deployment method, for apache this would be 'apache' (without qoutes).
''I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
$shell = \MTS\Factories::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