I am running a PHP web script locally for testing purposes through terminal with command: php -S localhost:8000.
<?php $command = '/usr/bin/python /Users/Jupiter/Desktop/NC/www/createHarbourContainter.py'; exec($command); ?>
I am trying to call this python script that exists in the same directory:
#!/usr/bin/python
import os
import sys
save_path = '/Users/Jupiter/Desktop/NC/harbours/'
name = sys.argv[1]
def newHarbourContainer():
os.makedirs(save_path + name)
def main():
newHarbourContainer()
if __name__ == '__main__':
main()
This python script has chmod x+ set to it.
I am able to run the python script from the terminal :python createHarbourContainter.py
What I am unable to do is get the PHP function exec() to invoke the python script. Help needed!
In PHP you can use backticks ` to execute shell commands, so try this:
<?php
`/usr/bin/python /Users/Jupiter/Desktop/NC/www/createHarbourContainter.py`
?>
See http://php.net/manual/en/language.operators.execution.php for more info
So I have found a solution:
$output = shell_exec('python createHarbourContainer.py')
And to get back an output into the browser:
echo "<pre>$output</pre>";
I was running the server in PHP Development Server.
Using bash command: php -S localhost:8000 from directory where index.php is located.
The server was logging all input and output from browser interface.
I realized that when calling: /usr/bin/python from php the PHP Development Serverwould halt and open python interpreter.
And setting the whole path to the python script I wanted executed didn't work because the PHP script didn't have permission.
How this can help someone else in future.
Related
I have a python script that i want to run from index.php and they both are in the same directory.
The problem is that there's no output shown on the page(index.php).
I am running the page on a CPanel shared hosting from GoDaddy.
I have the permissions -rwx for both the files.
There's no error in running the python3 script file from the terminal.
The same files run smoothly on my computer's localhost but not on the CPanel.
Am able to run bash files using the same php code.
I have tried using system() in php to call the python3 script file but this doesn't seems to work.
index.php:
<?php
$comm = "python3 test.py";
echo $comm;
$output = system($comm);
echo "\n";
print($output);
?>
test.py:
print ("Hello")
Current Output:
python3 test.py
I expect the output to be:
python3 test.py Hello
I think you will need to use shell_exec to run your python code like that
<?php
$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;
?>
and the first line in the python file should be
#!/usr/bin/env python
Don't forget to give your python file the privileges
chmod +x test.py
I am trying to execute a shell script containing python commands from PHP using exec function in Ubuntu 18.04. The issue is Python script is not able to create a file for writing data.
This is my shell script test.sh
python3 p1.py
This is my python script
with open('trial.txt','w') as file:
file.write('Hello world')
This is my PHP script
<?php
try{
$out=exec('test.sh',$output,$status);
print_r($output);
}
catch(Exception $e)
{
echo $e;
}?>
I am getting $status as 1. Is there any problem with apache user permissions? Current apache user is www-data. I have given permissions to python script using chmod +x p1.py. This shell script works correctly and creates a new file if it runs from ubuntu terminal. But when executing from PHP, it doesn't work properly.
So I have hosted a webpage on my apache server and I'm trying to run some python and bash scripts when the user presses a button via PHP and AJAX.
Now my php file executes at python script (located in /var/www/html) which in turn executes a bash file (located in root/files).
On doing this manually in terminal, everything works perfectly fine.
But when I try to this via the webpage, the bash script isn't executed.
(I can't place the bash script in /var/www/html because it has the command to clone a git repository to the server and it gives private key shouldn't be public error when placed there)
I already tried suggestions in this answer by adding www-data to sudoers but it is still not working as expected.
Any help on this would be appreciated.
Thanks
PHP file :
if(isset($_POST['timestamp']))
{
$uid = $_POST['timestamp'];
echo "Please wait while the app is being generated".$uid;
exec("python /var/www/html/appgenserver.py $uid");
appgenserver.py
#! /usr/bin/env python
import os
import json,sys
from firebase import firebase
import requests
import subprocess
arg = sys.argv[1]
# Path to be created
path = "/root/files/"+str(arg)
print path
if not os.path.exists(path):
os.makedirs(path) #Gets executed
subprocess.call(['/root/Final/clone.sh', path) #Not getting executed
Most likeley because a bash script in its self won't be executable, it's just a plain textfile.
Your bash (and perhaps even appgenserver.py?) might be located under /root and apache probably runs as a non-priviliged user such as www-data, that user won't be able to access either your python script and in turn not the bash that the python would run.
Consider instead calling bash with the script as a parameter.
#! /usr/bin/env python
import os
import json,sys
from firebase import firebase
import requests
import subprocess
arg = sys.argv[1]
path = "/root/files/"+str(arg)
print path
if not os.path.exists(path):
os.makedirs(path)
subprocess.call(['/bin/bash', '/root/Final/clone.sh', path)
Now, this is NOT the most pretty of solutions.
But what you got before was probably a generic "Permission denied" error in the background (check your /var/log/apache/error.log).
What this does is start /bin/bash as a subprocess with the first parameter being the script you want to execute.
But you have zero error handling here and you can't interract with the process very much.
Consider doing something like this instead:
import subprocess
handle = subprocess.Popen(['/bin/bash', '/root/Final/clone.sh', 'parameter'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
while handle.poll() is None:
print(handle.stdout.read()) # There's some optimizations here to be done as well so it's not a blocking call etc.
handle.stdout.close()
handle.stdin.close()
And one last tip is not to place stuff in /root/ at all if you're integrating it into a web front-end/backend type of thing.
You're asking for trouble : )
Another way is to make use of sudo
If you modify your exec() in PHP to run exec("sudo ...") and enable your web-user to run the scripts without a password prompt it could work.
Bare in mind, it's not recommended to give www-data sudo access, rather do something like this:
# useradd -m -G www-data -s /bin/bash wwwexec
# echo "myuser ALL=NOPASSWD: /usr/bin/python" >> /etc/sudoers
and change your PHP script to have the following:
exec("sudo -u wwwexec python /var/www/html/appgenserver.py $uid");
That way at least your entire web service isn't given root access via the default username.
The way to do it
Would be to place your appgenserver.py under /var/www/cgi-bin/ instead, and create a CGI hook for .py in your apache configuration and hand over the user to the URL prividing you access to the CGI script.
That way everything should be according to best practices even tho, in theory, you could get your original solution to work.
For instance, this guide should get you started.
Previous Research:
Running a Python script from PHP
error on using exec() to call python script
Php exec python script 'weakness'/downside
Using exec() to run python script in PHP
I am running php version 5.6.6 and python version 3.4.3 on OS X.
Basically, the problem that I am running into is that if I run a python script via command line it works find but if I run it through a PHP script (using exec()) I get this error:
AttributeError: type object 'int' has no attribute 'from_bytes'
I have created and tested a miniature isolated test case to show the problem. I have already done a chmod 777 mypy.py to make sure mypy.py is executable.
myphp.php:
<?php
exec("/usr/bin/python mypy.py 1A", $output, $return);
var_dump($output);
mypy.py:
#!/usr/bin/env python
import string
import array
import binascii
import sys
if __name__ == "__main__":
hexval = sys.argv[1]
binval = binascii.unhexlify(hexval)
binint = int.from_bytes(binval, byteorder='big', signed=False)
print("int: " + str(binint))
(I know there are better ways to accomplish what is being done in this python script, I was just making a test case that would produce the same error)
When I run python mypy.py 1F via command line, I get this printed:
int: 31
But when I run php myphp.php via command line, I get this printed:
Traceback (most recent call last):
File "mypy.py", line 11, in <module>
binint = int.from_bytes(binval, byteorder='big', signed=False)
AttributeError: type object 'int' has no attribute 'from_bytes'
array(0) {
}
(Note: I have also executed whoami from the php script just to verify that my normal user is the one running the python script)
int has no method .from_bytes in python2,/usr/bin/python uses the python 2 interpreter, you need to use /usr/bin/python3 to use your python3 interpreter.
exec("/usr/bin/python3 mypy.py 1A", $output, $return);
Making the file executable is also irrelevant as you are explicitly running it with python.
To run it as an executable and use the python3 interpreter specify the correct python version in your python shebang:
#!/usr/bin/env python3
Then:
exec("./mypy.py 1A", $output, $return);
Sorry for previous edits, I misread the question. Are you sure that python in cli and /usr/bin/python resolve to the same binary? The behavior I see tells me PHP is trying to use Python 2.x (because int object doesn't have method from_bytes).
Using passthru function in PHP I can run an exe e.g hello.exe and get its result but unable to compile e.g hello.c using command tcc hello.c on windows command prompt through php script.
So question is how to run commad tcc hello.c on windows command prompt using php script. php script & cmd.exe are on the came machine.
OS windows XP.
code that i want to compile is hello.c is given below.
php script that is executing hello.exe is also given below.
code from hello.c
#include<stdio.h>
void main(void)
{
printf("hello");
}
php code that is succefully accesing and displaying hello.exe
enter code here
<?php
echo "Remote compilation:";
$path = escapeshellcmd('C:\\TC\\BIN\\HELLO.exe');
passthru( $path, $return_var);
?>
please guide
regards
From the PHP documentation:
The passthru() function is similar to the exec() function in that it
executes a command. This function should be used in place of exec() or
system() when the output from the Unix command is binary data which
needs to be passed directly back to the browser.
But here you are not expecting binary data to be generated from tcc and passed to the browser. A more appropriate function to use would be shell_exec(). E.g.:
<?php
echo "Remote compilation:";
$command = escapeshellcmd('YOUR TCC COMPILE COMMAND HERE');
shell_exec($command);
?>