Activate virtualenv from python or php script not SSH - php

I am trying to activate my virtualenv using a php script or a python script but without using SSH.
This is to allow my website.com/something.py file to access certain libraries (if this can be done in another simpler way please let me know)
My PHP code is:
<?php
echo "A";
$result = exec("source ENV/bin/activate");
if ($result){
echo "Worked";
}
else{
echo "didnt work";
}
echo "B";
$result = system("python test.py");
?>
and I have test.py =
def main():
print "hello"
try:
import xlrd
except:
try:
print "xlrd didnt load"
import MySQLdb
except:
print "mdb,xlrd didnt load"
main()
The virtualenv I have setup has xlrd installed.
This is the output I get on the webpage:
Adidnt workBhello xlrd didnt load
It makes sense that xlrd didnt load but why is the source command not working? This all works in SSH

According to the docs, sourcing the activate script inside a shell just tweaks the $PATH environment variable to point to the virtualenv's bin directory. This script can't work from PHP, because an external executable can never modify the caller's environment for security reasons.
The documentation also tells you what you can do instead:
If you directly run a script or the python interpreter from the
virtualenv's bin/ directory (e.g. path/to/env/bin/pip or
/path/to/env/bin/python script.py) there's no need for activation.
So you can just specify the full path to the Python installation instead:
$result = system("ENV/bin/python test.py");

Related

PHP exec() to compile VB6 from CMD

i'm pretty new to PHP and i need to compile a vb6 project from windows command prompt.
I've tried everythig but nothing seems to work, even creating a batch and execute from PHP code, no way... (the batch works if launched from cmd itself).
I also defined variables with various paths with no success.
i.e.:
$cmd = ('vb6.exe -MAKE D:\Websites\devopservices\dlledit\portaleeditorisen\NewSecurity\Data\NewSecurity_data.vbp D:\Websites\devopservices\dlledit\compiled\test.dll');
echo exec($cmd);
or inserting paths with variables:
$proj = 'D:\Websites\devopservices\dlledit\portaleeditorisen\NewSecurity\Data\NewSecurity_data.vbp';
$dll = 'D:\Websites\devopservices\dlledit\compiled\test.dll';
here it is the full command i need to execute:
<?php
echo exec('"C:\Program Files (x86)\Microsoft Visual Studio\VB98\VB6.EXE" /MAKE D:\Websites\devopservices\dlledit\portaleeditorisen\NewSecurity\Data\NewSecurity_Data.vbp D:\Websites\devopservices\dlledit\compiled\NewSecurity_Data.dll');
?>
Thanks for your help.
I resolved, it was not a php issue but related to identity in IIS appilcation pool :-)

Run Python Script from PHP on IIS Server

I've got IIS 8.5 installed, with PHP installed and running. I've also added a handler mapping (with the %s %s at the end of the python.exe path) to the website. I can run the python script directly from the browser successfully (prints "Hello World").
This is all just configured on the Default Web Site for testing purposes. When I attempt to set a PHP variable to the output of a python script, the variable does not appear to receive the value. IUSR and IIS_IUSRS have modify permissions on the root directory (C:\inetpub\wwwroot), which is where all HTML, PHP and Python files are located.
My code is as follows:
PHP:
<?php
$coutput = shell_exec("/test.py > ~debug.log 2>&1");
include 'header.html';
echo "</br>Python Output:</br>" . $coutput;
var_dump($coutput);
include 'footer.html';
?>
NOTE: I've also tried "python test.py > ~debug.log 2>&1" in the shell_exec function to no avail.
Python (blank print is to display properly in browser when run directly):
print("")
print("Hello World")
Initially, I thought this was a permissions issue with PHP, so I ran the python script from PHP via command line and get the python code:
c:\inetpub\wwwroot>"c:\program files\php\v7.3\php.exe" c:\inetpub\wwwroot\test.py
print("")
print("Hello World")
PHP is not in safe mode.
What am I missing? Any help would be appreciated!

Change permissions to allow PHP script in browser to execute matplotlib operations in a python script

I am running Ubuntu 14.04 with a locally hosted webpage running on Apache2. I can access index.php fine through my browser, but I want that page to display a graph that is prepared in a python script called graph.py. graph.py will execute fully when the I execute index.php from the terminal, and it will PARTIALLY execute when I access it from the browser. commands from pyplot, used within the graph.py file will not execute when called from the browser.
I have simplified the contents of the files for this question.
Contents of index.php:
<?php
echo exec('whoami');
echo "</br>";
$r = `python graph.py`;
echo($r);
?>
Contents of graph.py:
#!/usr/bin/python2.7
import cgi
import matplotlib.pyplot as plt
print("Initial file parsing successful")
plt.plot([1,2,3,4])
print("File completed operation using pyplot")
The output of index.php from the terminal has what I would expect:
MYUSERNAME</br>Initial file parsing successful
File completed operation using pyplot
The browser never completed the PyPlot operation as shown by its output:
www-data
Initial file parsing successful
After scouring the internet for answers, this post appears to be the most similar to my issue:
Why cannot PHP execute a command from web browser?
As suggested in the responses, it makes sense that I may be dealing with a permissions issue. I used "updatedb" and "locate pyplot" to find every instance the pyplot module appears. On my machine, there are three files in two directories:
/usr/lib/pymodules/python2.7/matplotlib/pyplot.py
/usr/lib/pymodules/python2.7/matplotlib/pyplot.pyc
/usr/share/pyshared/matplotlib/pyplot.py
Since pyplot has other dependencies in the matplotlib directory, I set permissions for every file in both of these directories with "chmod 777." I know I will have to restore these for security reasons once I find where I can scale permissions back, but even allowing that level of access, the php file will not execute when accessed from the browser. Does anyone have any ideas what could be catching this?
AFAIK, when you execute python from the browser the user is www-data. Thus you should change the python script's permissions to a+x. You don't need cgi unless you run PHP in cgi that is unusual. Just put 'graph.py' into the same folder where you keep your index.php. Save your plot into am image and open it in your browser via PHP. That's it.
Python script
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.savefig('img.png')
PHP code
<?php
$r = '/usr/bin/python ./graph.py';
exec($r);
$im = imagecreatefrompng("img.png");
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
Output:
I was able to make a plot with Python in cgi. No problems. http://wiki.scipy.org/Cookbook/Matplotlib/Using_MatPlotLib_in_a_CGI_script
PHP
<?php
header('Location: cgi-bin/graph.py');
?>
PYTHON
#!/usr/bin/python
import os,sys
import cgi
import cgitb; cgitb.enable()
os.environ[ 'HOME' ] = '/tmp/'
import matplotlib
matplotlib.use( 'Agg' )
import pylab
form = cgi.FieldStorage()
pylab.plot([1,2,3])
print "Content-Type: image/png\n"
pylab.savefig( sys.stdout, format='png')
And here's without cgi. Since PHP is pretty much executable, we don't actually need cgi. I moved the graph.py from cgi-bin to html folder and deleted all the cgi modules from it and even os.environ[ 'HOME' ] = '/tmp/'.
PHP
<?php
$r = '/usr/bin/python ./graph.py';
exec($r);
$im = imagecreatefrompng("img.png");
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
PYTHON
#!/usr/bin/python
import matplotlib
matplotlib.use( 'Agg' )
import pylab
pylab.plot([1,2,3])
pylab.savefig('img.png')
AS you see the difference is
matplotlib.use( 'Agg' )
I have no idea what it means. Something important, maybe. Without this opting the script doesn't run.
As per my understanding you will need to configure your webserver to work with python compiler. Any of the web server will by default will not be able to use any compiler installed on your system. Your webserver should understand for a particular file extension which program should be used to run it.
Below is the link where you can find information for it here:
[How do you set up Python scripts to work in Apache 2.0?
But in your case you may need just to run python scripts from php. You can find information about it here : Running a Python script from PHP

Running a python code with php

I have a python script which is needed to be run by php:
<?php
$command = escapeshellcmd('/home/Desktop/test.py');
$output = shell_exec($command);
echo $output;
?>
The out put of the python script is a binary file but I get the following error in the log:
Unable to access the X Display, is $DISPLAY set properly?
The php code works fine from the terminal but no luck when I try to run it from the browser. Any idea what is going on? Ideally, I don't want to change my program. I want to know how you can rectify the X Display error. Is there a way to check if $DISPLAY is set properly? ( I am working with Ubuntu)
I tried this : pidof X && echo "yup X server is running" on my terminal and it is saying yup x server is running!
Add the following text as the first line of your Python script:
#!/usr/bin/python
Without this, the kernel doesn't know what interpreter to run your script with, and may end up trying to launch it using /usr/bin/import (because that word probably appears on the first line of the script). The import utility requires access to the X11 display (it's a screenshot utility, basically), which is why you're getting this error.
The python file you need may need to open a window to run. You say you saw it run in terminal though? What's test.py? Is it propitiatory?
If you try using this as a command in your PHP: (not 100% that the shell escape won't strip this so may need to comment that out)
python -c \'print \"Test\"\'
and see if you get the output text back. If so it's a python issue not PHP and the test.py file may be instantiating something that needs the $DISPLAY var set. PHP doesn't set the $DISPLAY var as it is shell commands not GUI.
try popen
$command = "/usr/bin/python /home/Desktop/test.py";
$handle = popen($command, "r");
"r" for read
$read = fread($handle, 10);
10 is the size of output you want to take,
echo $read ;
hope it helps,

PHP exec python not working

hey yall. Im running python on a webserver from dreamhost. I am using their install of python and am using a lastfm module that can be found here: http://code.google.com/p/python-lastfm/
to get it to import properly i do this
import sys
sys.path.append("/home/myusername/build/Python-2.5/Lib/site-packages/")
import lastfm
since the lastfm module is installed there.
When I use putty to ssh into my server, i can simply run python test.py and it works perfectly. But when i run it from a php script with
exec("python test.py");
it suppossedly does not work and the script doesnt run. it runs perfectly fine when i do
import lastfm
and then have other things after,
but when i actually try to do something with the module like:
import lastfm
api=lastfm.Api(api_key)
it does not run. once again i can run the script using the same python install in a shell and it executes fine. So something must be happening that goes wrong when i run it from the php script. I figured it would be running the exact same python and everything. I checked other posts and they say it may be something with file permissions, but ive put every file to 777 and it still doesnt work. idk what the problem could be. thanks in advance everyone.
Try using the full path to the python executable. For example:
exec("/usr/bin/python test.py")
You can find the full path from the command line using the which command:
$ which python
/usr/bin/python
Whatever error python is raising would be going to the child's stderr. Try either telling php to read from stderr, or (in python) do this:
import sys
sys.stderr = sys.stdout
For Windows users:
$output = null;
exec('C:\\Python27\\python.exe C:\\sud.py', $output);
echo var_export($output, TRUE);
The code i was searching whole day ^^
That's why - hope it'll help somebody.
For Windows User -
Thanks to Karlisup my PHP file could read python.
I'm using BITNAMI WAMP in EC2 Amazon, my python file (leadatos.py) and php file are on htdocs folder.
My calling was
<?php
passthru('C:\\Python27\\python.exe leadatos.py');
?>
The last line of my Python file was print "message".
Hope it words!

Categories