Working Python script does not work when run via PHP - php

I am trying to run a Python script on a web server. I have been unable to run the script directly in the cgi-bin folder (kept getting 500 server errors) so I am currently attempting to call the script via a PHP script placed in the cgi-bin folder.
I am using a php script that executes a shell command on my server:
<?php
shell_exec('python /home/stevesloane8/www/cgi-bin/test.py');
?>
This method works on a few test python scripts which I have tried, but will not work on my script.
Here a portion of my script:
#!/usr/bin/python
CATEGORIES_INDEXED = ["36"]#, "6000", "6002",]
NUMBER_TO_INDEX = 25
import requests
import mysql.connector
import datetime
import time
def get_today():
today = datetime.date.today()
return today.strftime("%Y-%m-%d")
def get_start_date():
today = datetime.date.today()
start_date = today - datetime.timedelta(weeks=2)
return start_date.strftime("%Y-%m-%d")
def get_today_underscore():
today = datetime.date.today()
return today.strftime("%Y_%m_%d")
def get_token(client, secret):
payload = {"Content-Type" : "application/x-www-form-urlencoded", "client" : client, "secret" : secret}
auth = requests.post('https://integrations.apptopia.com/api/login', params=payload)
return auth.json()['token']
def get_cat_ids():
r = requests.get('https://integrations.apptopia.com/api/itunes_connect/categories', headers={"Authorization":TOKEN})
cat_dict = {}
for cat in r.json():
cat_dict[cat['id']] = cat['name'].replace(" ", "_").replace("&", "and").replace("-", "to")
return cat_dict
def pull_top_chart(cat, kind, quant):
today = time.strftime("%Y-%m-%d")
top_chart = requests.get("https://integrations.apptopia.com/api/itunes_connect/rank_lists", params={"id":cat, "date":today, "country_iso":"US", "kind":kind}, headers={"Authorization":TOKEN})
top_app_ids = top_chart.json()[0]['app_ids']
top_app_ids = top_app_ids[:quant]
rank_dict = {i:k for k, i in enumerate(top_app_ids)}
I went through it line by line and the script worked when called by the above PHP script up until I pasted in the last line:
rank_dict = {i:k for k, i in enumerate(top_app_ids)}
After I insert this line, the Python script does not run through the PHP script. It still runs when I call it from the command line.
Because this script works when I call it from the command line, is there something particular about the operation of the PHP shell_exec function that prevents this from working. Or is there some kind of permissions issue with this being run on a web server? The script permissions of both files are set to 755.
Thanks

Technically you must have certain OS privileges to Run such type of script through php.
If you good at php then
Recently I develop a script for such type of issues kindle have a look, I hope it will help
Run Complex Shell scripts through php
Happy Coding

I finally figured out what the problem was. Apache was not using my user PATH so it was calling the wrong version of Python (2.4) rather than 3.6. When I substituted the full path to the right version of Python, it worked perfectly.

Related

python script executed from php won't read saved model

Here is what I'm trying to do:
I'm sending an Ajax request with an image as data to a php script that uploads it and execute a python script with the image name the python script loads a gender detection model and predict the gender on the person on the image.
The problem is the model doesn't load, I tried it with the php and python script in the same directory and it worked fine but I'm trying to use it in laravel so I can't do that anymore.
when I try running the python script manually like that :
python path/to/script.py
It throws this error : OpenCV(3.4.1) Error: Unspecified error (File can't be opened for reading!)
but when I do this it works:-
cd path/to/script.py ; python script.py
Here is my php:-
$file = $this->upload_Image($request->get('image'));
$path =public_path().'/app/Http/Controllers';
$command='cd '.$path.';';
$path= 'python '.$path.'/facifier.py '.storage_path('app').$file;
$command .= $path;
return exec($command);
Storage::disk('local')->delete($file);
return json_encode($orderedData);
The command ends up like this : cd absolute/path/to/script.py ; python script.py absolute/path/to/image.jpg
when I use it on a command prompt it works fine.
Here is where I get the error on my python script:-
fisher_face_gender = cv2.face.FisherFaceRecognizer_create()
fisher_face_gender.read('models/gender_classifier_model_kdef.xml')
does anyone know whats causing this, I'm on windows by the way.
thanks to bruno desthuilliers comment i got it working. The problem was in the path to model i used,its relative to the python script because i thought that the script executes on its own path not on the command promt's path .
I just changed the path to the model to the absolute path and it worked fine

PHP-invoked python script cannot write

I've set up a small web app that passes user data to a python script. Python is supposed to go to work, create a file on the webserver, and allow the user to download it. However, the script execution seems to stop where the Python write() command is issued.
Python:
print("Writing to '" + filename + "'")
f = open('backups/' + filename, 'w')
f.write(self.output())
f.close()
print("Done!")
PHP:
$user = escapeshellarg($_POST['user']);
$password = escapeshellarg($_POST['password']);
$command = './backup.py '.$user.' '.$password;
print(exec($command));
Actual result:
Python does create a file in the desired directory but it remains empty. 2. Python never outputs "Done!" (Because permissions are denied)
Expected result:
Python creates a file with data
Python proceeds to print "Done!" which is output to the calling PHP script
I've done the following:
www-data has group write permissions (drwxrwsr-x) for the directory ./backup
The #!/usr/bin/env python3 shebang is present in the python file
The python file is executable
When I change to user www-data with sudo su www-data and then start the php commandline, and enter the above command invoking my Python script, the file is created correctly!
If I start a builtin php server, it also works fine, only if the php script is handled through apache, it doesn't work
I have officially wasted an entire day of my life on this.
The permissions were all right.
What was happening is that the python script failed ONLY if it was being invoked through my php script and ONLY if that was being served by Apache.
Looking through the Apache error log revealed that the python script failed because it could not write bytes to the file and ascii conversion failed because there was unicode data in the output.
So doing f = open(filename, 'wb') solved the issue.
This behaviour was not observed on my development machine or through the built-in PHP server. Still wonder why there's a difference in file handling. Would appreciate an answer if anyone has one.

Python script not executing properly from Php

I'm trying to run a python script with Php but it's not running properly when I launch it with Php. This script, here "bot.py" interracts with the instagram api and writes the output as a text file in 'bot1.txt'.
Here is the Php code :
shell_exec("python automation/bot.py");
And here is the python snippet that writes in the file :
with open('../botlog/bot1.txt', 'a') as the_file:
the_file.write('Followed')
My problem is that when I launch it with Php the script runs but doesn't write in the file bot1.txt. When I run the python script with the command line everything works perfectly so I don't understand what's the deal here.
I'm working with MAMP on a local server.
Thank you !
Maybe you should specify your path to php.
$myPHPScriptPath = realpath(dirname(__FILE__));
Then specify the relative path to your python script.
Hope it helps

Not getting output from python script when run through PHP

I have a python script that prints out the program names that are currently in the volume mixer in Windows 10.
This works fine when I run it in the cmd.
C:\wamp\www\Volume>py test.py
firefox.exe,Spotify.exe,Microsoft.Photos.exe,Steam.exe,
and here is my python script.
import sys
from pycaw.pycaw import AudioUtilities
def main():
list = ''
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
volume = session.SimpleAudioVolume
if session.Process and session.Process.name():
list += session.Process.name() + ','
sys.stdout.write(list)
if __name__ == "__main__":
main()
And my PHP:
$python = "py";
$script = "test.py";
exec("$python $script 2>&1", $output);
print_r($output);
But when I run it in PHP using WAMP, I don't get any output from that script, nothing is outputted.
If I change my python script to only contain "print("TESTING")" then I can read that output fine in PHP which makes me think that my python code is failing perhaps due to permissions. So I changed the user from SYSTEM to my own user so when I use:
echo exec("whoami") // Outputs my user account name
I thought maybe my PHP script was off, so I tried running it though the command line, but the results are what I want:
C:\wamp\www\Volume>php index.php
Array
(
[0] => firefox.exe,Spotify.exe,Microsoft.Photos.exe,Steam.exe,
)
So I'm at a loss as to why when I execute my PHP code through my browser, I am not getting any output unless my python script only contains :
print("TESTING")
What could possibly be going wrong?
EDIT
So I decided to debug this further by altering my python script to create a .txt file on my desktop, this works fine when running it through the command line. But again, when I run it through my browser/PHP, that file isn't created. So maybe I need to grant special permissions to my python script? I'm not sure why I need to do that though as I have given PHP my user account
So I think I found out why I'm not getting any output from my python script, thanks to #Torxed.
It seems like when I run the Python script through WAMP/PHP it must run as a different user/environment which doesn't have any Audio.
This is odd however as I've set 'wampapache64' to run as my user account, even after a restart I'm still getting the same results.
I've even tried
runas /savecred /noprofile /user:<USER>
But that just returns the password prompt which I won't be able to fill out in PHP.
This project looks like a dead end for now.

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