Executing a python file from PHP - Linux - php

I have a python file that I would want to execute whenever a php page is called. The python file is in the same folder as the php file. The python script on execution edits a textfile that the php file accesses.
I have the following code:
<?php
exec("python somefile.py",$output);
$file = fopen("test.txt",'r');
....
For some reason, the python script never gets executed. I know this certainly as I can see it from the changes in the text file.
Since I was not sure if the script was made executable, so I included "python" on the command.
I also ran:
chmod +x somefile.py
just to make sure this was not the reason. But this did not help too.
What should I change to make the php page execute the python script whenever it is called?

This is most likely a permission issue.
Try
echo exec("whoami");
This will let you know who php is running as. Then you need to verify this user can run the python script. If the file was not created by the same daemon that runs python, you will most likely be denied permission.
Update
This will let you know who owns all the files you are working with. The file being written to needs to be writable by the user that is running python. If you are running python from ssh, that is most likely not the same user as when you run python from exec.
echo exec('whoami') . "<br>";
echo exec("ls -l test.txt") . "<br>";
echo exec("ls -l somefile.py") . "<br>";
Update 2
Because I constantly forget this exists.
passthru('python somefile.py 1 2>&1');
This will exec your python file, and output stderr to stdout.

Related

Trigger script on html form submit [duplicate]

I'm trying to run a Python script from PHP using the following command:
exec('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
However, PHP simply doesn't produce any output. Error reporting is set to E_ALL and display_errors is on.
Here's what I've tried:
I used python2, /usr/bin/python2 and python2.7 instead of /usr/bin/python2.7
I also used a relative path instead of an absolute path which didn't change anything either.
I tried using the commands exec, shell_exec, system.
However, if I run
if (exec('echo TEST') == 'TEST')
{
echo 'exec works!';
}
it works perfectly fine while shutdown now doesn't do anything.
PHP has the permissions to access and execute the file.
EDIT: Thanks to Alejandro, I was able to fix the problem. If you have the same problem, don't forget that your webserver probably/hopefully doesn't run as root. Try logging in as your webserver's user or a user with similar permissions and try to run the commands yourself.
Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.
In PHP use shell_exec function:
Execute command via shell and return the complete output as a string.
It returns the output from the executed command or NULL if an error
occurred or the command produces no output.
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
Into Python file test.py, verify this text in first line: (see shebang explain):
#!/usr/bin/env python
If you have several versions of Python installed, /usr/bin/env will
ensure the interpreter used is the first one on your environment's
$PATH. The alternative would be to hardcode something like
#!/usr/bin/python; that's ok, but less flexible.
In Unix, an executable file that's meant to be interpreted can indicate
what interpreter to use by having a #! at the start of the first line,
followed by the interpreter (and any flags it may need).
If you're talking about other platforms, of course, this rule does not
apply (but that "shebang line" does no harm, and will help if you ever
copy that script to a platform with a Unix base, such as Linux,
Mac, etc).
This applies when you run it in Unix by making it executable
(chmod +x myscript.py) and then running it directly: ./myscript.py,
rather than just python myscript.py
To make executable a file on unix-type platforms:
chmod +x myscript.py
Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl)
and/or must be "executable". Also all commands into .py file must have correct privileges.
Taken from php manual:
Just a quick reminder for those trying to use shell_exec on a
unix-type platform and can't seem to get it to work. PHP executes as
the web user on the system (generally www for Apache), so you need to
make sure that the web user has rights to whatever files or
directories that you are trying to use in the shell_exec command.
Other wise, it won't appear to be doing anything.
I recommend using passthru and handling the output buffer directly:
ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean();
If you want to know the return status of the command and get the entire stdout output you can actually use exec:
$command = 'ls';
exec($command, $out, $status);
$out is an array of all lines. $status is the return status. Very useful for debugging.
If you also want to see the stderr output you can either play with proc_open or simply add 2>&1 to your $command. The latter is often sufficient to get things working and way faster to "implement".
To clarify which command to use based on the situation
exec() - Execute an external program
system() - Execute an external program and display the output
passthru() - Execute an external program and display raw output
Source: http://php.net/manual/en/function.exec.php
Alejandro nailed it, adding clarification to the exception (Ubuntu or Debian) - I don't have the rep to add to the answer itself:
sudoers file:
sudo visudo
exception added:
www-data ALL=(ALL) NOPASSWD: ALL
In my case I needed to create a new folder in the www directory called scripts. Within scripts I added a new file called test.py.
I then used sudo chown www-data:root scripts and sudo chown www-data:root test.py.
Then I went to the new scripts directory and used sudo chmod +x test.py.
My test.py file it looks like this. Note the different Python version:
#!/usr/bin/env python3.5
print("Hello World!")
From php I now do this:
$message = exec("/var/www/scripts/test.py 2>&1");
print_r($message);
And you should see: Hello World!
The above methods seem to be complex. Use my method as a reference.
I have these two files:
run.php
mkdir.py
Here, I've created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>
<body>
<head>
<title>
run
</title>
</head>
<form method="post">
<input type="submit" value="GO" name="GO">
</form>
</body>
</html>
<?php
if(isset($_POST['GO']))
{
shell_exec("python /var/www/html/lab/mkdir.py");
echo"success";
}
?>
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:
sh: blabla.py: command not found
If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:
$command = escapeshellcmd('python blabla.py');
All the options above create new system process. Which is a performance nightmare.
For this purpose I stitched together PHP module with "transparent" calls to Python.
https://github.com/kirmorozov/runpy
It may be tricky to compile, but will save system processes and will let you keep Python runtime between PHP calls.
Inspired by Alejandro Quiroz:
<?php
$command = escapeshellcmd('python test.py');
$output = shell_exec($command);
echo $output;
?>
Need to add Python, and don't need the path.

Issues executing python script from HTML button using PHP

I cannot get a button on my webpage to execute a python3 script that is also inside the same folder in the server as the rest of the html and php files.
exec();
system();
escapeshellcmd();
shell_exec()
all of these commands are not working for me right now. I have chmod +x my .py file and included #!/usr/bin/env python3 at the very beginning of my python file.
<?php
if( isset($_POST['runScript'])){
$command = escapeshellcmd('/nfs/nfs7/home/team51/cgi-
pub/dataProcess.py');
$output = shell_exec($command);
echo $output;
}
?>
<form method="post">
<input type="submit" name="runScript" value="runScript">
</form>
In the end the python script should place a csv file in the same folder as the rest of the files. But I am getting nothing.
Some functions just print back "Array()"
You are running pythin script from apache user. Python path may not be accessible by apache user
Use full python installation path to execute script.
exec("/usr/bin/python /nfs/nfs7/home/team51/cgi-
pub/dataProcess.py");
To find out exact error check apache error log. If error logs give permission denied , it means apache is not having permission to execute script.
You can get access from sudoers file.
Try Make a sh file to execute the python script and use PHP to execute this sh file

executing a script via php exec which creates a file on the server

I have a php script which calls a shell script as below -
#!/bin/bash
timestamp=$(date +"%d-%m-%Y %H:%M:%S")
echo $timestamp >> results
The php script -
<?php
$mycmd = exec('/bin/bash exectest.sh',$op,$er);
var_dump($mycmd);
var_dump($op);
echo $er."\n";
?>
The php script returns error code 1 for $er but when i tried to modify the shell script to just print instead of writing to a file. the Php script then returns 0 and succeeds.
Any ideas of where I need to fix this?
I have tried giving the full path for the script and also this is the same case when i tried using a python script in place of a shell script.
Your observation indicates that this is most likely a permission problem, e.g. the user running PHP does not have write permission to either the results file in its current working directory or the directory itself (if the file does not exist yet).
It happened to be running on an AFS machine hence required afs priviledges for httpd.
fs sa . http write
sorted the issue.

Running a Python script from PHP

I'm trying to run a Python script from PHP using the following command:
exec('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
However, PHP simply doesn't produce any output. Error reporting is set to E_ALL and display_errors is on.
Here's what I've tried:
I used python2, /usr/bin/python2 and python2.7 instead of /usr/bin/python2.7
I also used a relative path instead of an absolute path which didn't change anything either.
I tried using the commands exec, shell_exec, system.
However, if I run
if (exec('echo TEST') == 'TEST')
{
echo 'exec works!';
}
it works perfectly fine while shutdown now doesn't do anything.
PHP has the permissions to access and execute the file.
EDIT: Thanks to Alejandro, I was able to fix the problem. If you have the same problem, don't forget that your webserver probably/hopefully doesn't run as root. Try logging in as your webserver's user or a user with similar permissions and try to run the commands yourself.
Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.
In PHP use shell_exec function:
Execute command via shell and return the complete output as a string.
It returns the output from the executed command or NULL if an error
occurred or the command produces no output.
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
Into Python file test.py, verify this text in first line: (see shebang explain):
#!/usr/bin/env python
If you have several versions of Python installed, /usr/bin/env will
ensure the interpreter used is the first one on your environment's
$PATH. The alternative would be to hardcode something like
#!/usr/bin/python; that's ok, but less flexible.
In Unix, an executable file that's meant to be interpreted can indicate
what interpreter to use by having a #! at the start of the first line,
followed by the interpreter (and any flags it may need).
If you're talking about other platforms, of course, this rule does not
apply (but that "shebang line" does no harm, and will help if you ever
copy that script to a platform with a Unix base, such as Linux,
Mac, etc).
This applies when you run it in Unix by making it executable
(chmod +x myscript.py) and then running it directly: ./myscript.py,
rather than just python myscript.py
To make executable a file on unix-type platforms:
chmod +x myscript.py
Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl)
and/or must be "executable". Also all commands into .py file must have correct privileges.
Taken from php manual:
Just a quick reminder for those trying to use shell_exec on a
unix-type platform and can't seem to get it to work. PHP executes as
the web user on the system (generally www for Apache), so you need to
make sure that the web user has rights to whatever files or
directories that you are trying to use in the shell_exec command.
Other wise, it won't appear to be doing anything.
I recommend using passthru and handling the output buffer directly:
ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean();
If you want to know the return status of the command and get the entire stdout output you can actually use exec:
$command = 'ls';
exec($command, $out, $status);
$out is an array of all lines. $status is the return status. Very useful for debugging.
If you also want to see the stderr output you can either play with proc_open or simply add 2>&1 to your $command. The latter is often sufficient to get things working and way faster to "implement".
To clarify which command to use based on the situation
exec() - Execute an external program
system() - Execute an external program and display the output
passthru() - Execute an external program and display raw output
Source: http://php.net/manual/en/function.exec.php
Alejandro nailed it, adding clarification to the exception (Ubuntu or Debian) - I don't have the rep to add to the answer itself:
sudoers file:
sudo visudo
exception added:
www-data ALL=(ALL) NOPASSWD: ALL
In my case I needed to create a new folder in the www directory called scripts. Within scripts I added a new file called test.py.
I then used sudo chown www-data:root scripts and sudo chown www-data:root test.py.
Then I went to the new scripts directory and used sudo chmod +x test.py.
My test.py file it looks like this. Note the different Python version:
#!/usr/bin/env python3.5
print("Hello World!")
From php I now do this:
$message = exec("/var/www/scripts/test.py 2>&1");
print_r($message);
And you should see: Hello World!
The above methods seem to be complex. Use my method as a reference.
I have these two files:
run.php
mkdir.py
Here, I've created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>
<body>
<head>
<title>
run
</title>
</head>
<form method="post">
<input type="submit" value="GO" name="GO">
</form>
</body>
</html>
<?php
if(isset($_POST['GO']))
{
shell_exec("python /var/www/html/lab/mkdir.py");
echo"success";
}
?>
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:
sh: blabla.py: command not found
If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:
$command = escapeshellcmd('python blabla.py');
All the options above create new system process. Which is a performance nightmare.
For this purpose I stitched together PHP module with "transparent" calls to Python.
https://github.com/kirmorozov/runpy
It may be tricky to compile, but will save system processes and will let you keep Python runtime between PHP calls.
Inspired by Alejandro Quiroz:
<?php
$command = escapeshellcmd('python test.py');
$output = shell_exec($command);
echo $output;
?>
Need to add Python, and don't need the path.

shell_exec to run a Perl file

$cmdOutput = shell_exec("perl run_single_test/hello.pl");
echo "the command output = $cmdOutput";
This causes the file hello.pl to execute and print "hello world back to page". But
shell_exec("perl run_single_test/test_single_run.pl -s \"$testSuiteName\" -t \"$testName\" -i $time");
does not get executed. I echoed the command to screen and ran it on terminal, the Perl script executed perfectly. test_single_run.pl creates a log file and copies a few files.
What am I missing?
Finally figured out the answer.
The test_single_run.pl was modifying a few files in other directories.
I got to know that apache runs the perl script as a different user . In my case it was wwwrun and thus lacked the permissions to operate on other files.
Changed the configuration file uid.conf to make apache run the perl script as my user. And it worked

Categories