Permission Denied when Calling Shell Script from a Python Subprocess in Browser - python

I am calling a python script through an ajax call
$.ajax({
url: "http://localhost/username/test.py",
type: "post",
data: JSON.stringify({'param':{"hello":"world"}}),
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
The python script kicks off (have set up the conf files and have an apache server running) but then the python script is supposed to loop through a bunch of subprocess calls calling various shell files. Something like this:
for line in reader:
var=line["A"]
var2=var[:-4]
var3=line["B"]
print(var2)
subprocess.call(["sh","dummy.sh",var,var2,var3])
The same python scripts works fine in terminal. But when I run through the web browser, I get permission a 500 error in the browser. Going into the apache logs, shows me its running into a permission error
[Thu Jul 23 18:13:55.958161 2015] [cgi:error] [pid 19878] [client ::1:54132] AH01215: dummy.sh: line 37: inputFile.xml: Permission denied, referer: http://localhost/username/
How do I pass permissions? or am I doing something completely wrong here?

When you run the python script at the terminal, it runs as a process with your user ID, I assume?
If you can open the input file by doing this, then it is most likely a permission issue.
The apache process just isn't privileged enough to open the file.
I'd suggest:
Check the owner and permission of the file - make sure it is readable by the Apache process userID. This requires the file to at least have read permission, ie. -rw-r--r-- (chmod 644).
Also don't forget the directory path permission and/or ownership.
eg. if the file is in /home/foo/bar/inputFile.xml, you need to check that the whole path /home/foo/bar is accessible by the Apache user. This requires at least drwx--x--x (chmod 711) on the directories.

Thanks Maelstrom, Revolt and rici. inputFile.xml is actually created within dummy.sh and then other steps within dummy.sh operate on inputFile.xml. I also anticipate that since I have already given other files in the folder 755 access, its these new formed xml files that are restricted. How do I ensure that all files created by dummy.sh have enough permissions that they can be executed upon? Thanks a lot.

Related

Error while running python with xammp server

I am new in running python with xammp server. I have done all the required setup to run python in xammp server by following this link Running Python scripts with Xampp. While trying to running my code i always get an error.
**Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.
Please contact the server administrator at postmaster#localhost to
inform them of the time this error occurred, and the actions you
performed just before this error.
More information about this error may be available in the server error
log.**
My error log says this:
[Tue Jan 19 10:29:34.529875 2021] [cgi:error] [pid 11652:tid 1860] [client ::1:50570] malformed header from script 'python.py': Bad header: Hello World
i am attaching the code for my file too.
#! C:\Users\"UserName"\AppData\Local\Programs\Python\Python39\python.exe
print("Content-Type: text/html\n\n")
import cgi
print("Hello Python")
i have tried everything i could to search for the solution but nothing is helping. Please help me finding a solution. Thank you
Update the \n\n to use a carriage return (\r\n\r\n), and add another in.
This should make your HTTP headers valid, as they may not be terminating correctly.
Edit: You can also try multi-line print instructions such as
print "Content-type: text/html"
print ""
This is interpreting the body as the header (never terminated) so terminating this correctly should fix it.

Apache Permission Error on open file in Python

I am new to web design, and I'm trying to setup an Apache web interface to some python code.
I am running a test python script that just opens a new file in /var/www/html/ called output.txt and attempts to write to it. When the web page is loaded, I use shell_exec('/usr/bin/python3 /var/www/html/ptest.py'); to run my python script. The python script does run and outputs some print messages, but trying to open output.txt fails with:
Traceback (most recent call last): File "/var/www/html/ptest.py", line 8, in f=open("/var/www/html/output.txt", "w") PermissionError: [Errno 13] Permission denied: '/var/www/html/output.txt'. It will also fail if the file already exists and I open to read.
I have confirmed that the script is being run by apache with getpass.getuser(), and I have tried as many different permission combinations as I can think of for /var/www/html/, including 777. I have set apache as the group for every directory from /var/ to html/. I have tried creating the file ahead of time with 777 permissions. I have checked that /var/ to html/ has group execution permission.
I have tried creating and using another folder completely owned by apache.
I have looked through the apache directives to see if there is a directive I need to have, but I haven't found one yet.
I've included the code for my python script and my php page below.
EDIT: I've tried running ptest.py as apache using su -s /bin/bash apache.
ptest.py successfully runs this way, so the problem doesn't seem to be a permission associated with the apache user/group.
ptest.py
#!/usr/bin/python3
import sys
import getpass
import os
sys.stderr = sys.stdout
print(getpass.getuser())
print(os.getgid())
f = open("/var/www/html/output.txt", "w")
f.write("banana")
f.close()
print("I wrote banana, which is a berry")
banana.php
<html>
<head></head>
<body>
<h2>Welcome to the Program Test</h2>
<?php
echo "Created Command", "<br>";
$output = shell_exec('/usr/bin/python3 /var/www/html/ptest.py');
echo "Executed Command", "<br>";
echo $output, "<br>";
echo "End of output", "<br>";
$output = shell_exec('ls /var/www/html/');
echo $output;
?>
</body>
</html>
Credit to domino_pl leaving a comment.
It looks like typical selinux problem. Try selinux setenforce 0 – domino_pl

file sourcing within cgi failed

My cgi file:
#!/bin/sh -f
source /Users/sfma/sastbx/build/setpaths_all.sh
python processQuery.py
Then "Internal Server Error" arises. I checked the error_log, and it says:
[Thu Jun 23 15:02:39.809441 2016] [cgi:error] [pid 1327] [client ::1:52131] AH01215: /Users/sfma/sastbx/build/bin/libtbx.path_utility: line 63: /Users/sfma/sastbx/build/../../Library/Enthought/Canopy_64bit/User/bin/python: Permission denied: /Library/WebServer/CGI-Executables/web.cgi, referer: http://localhost/modelRetrieval/query.html
Remove the source statement, it works fine. But I need to source this file for further use.
Edit
According to the error message, I think the error may be due to the python permission.
#!/bin/sh -f
#python processQuery.py #this works fine
/Users/sfma/Library/Enthought/Canopy_64bit/User/bin/python processQuery.py #this does not work. Permission denied.
This really puzzles me because /Users/sfma/Library/Enthought/Canopy_64bit/User/bin/python is exactly the python I'm using:
$which python
/Users/sfma/Library/Enthought/Canopy_64bit/User/bin/python
I finally solved this problem.
Since python works fine while /Users/sfma/Library/Enthought/canopy_64bit/User/bin/python leads to a problem, I hard coded some variables in files libtbx.path_utility and sastbx.python to "python" instead of what they used to be: "/Users/sfma/sastbx/build/../../Library/Enthought/canopy_64bit/User/bin/python"
Update
The reason why /Users/sfma/Library/Enthought/Canopy_64bit/User/bin/python is permission denied is that _www is now allowed to visit my Library folder. Check this. After making that directory available to all, this problem is finally solved.

Python CGI script permission denied when writing file

I've got a python script named test.cgi in /Library/WebServer/CGI-Executables. I have an index.html file in /Library/WebServer/Documents. My html file contains a form that posts to the CGI script and that works fine. When my script attempts to write a file I get the following error:
It doesn't matter what I specify as the output dir, I get the same error message. I've tried changing the permissions on the cgi-bin folder and the script but that doesn't work either. Any suggestions?
On Linux, a web server normally runs as an unprivileged user and group. Often user=www-data and group=www-data, but it depends on your setup. The CGI inherits this user and group.
To create a file as www-data you need to ensure the directory is writable to that user.
One common way is to make sure that the directory is in group www-data and writable. The following commands are an example:
$ chgrp www-data /Users/user/Documents/pictures
$ chmod g+rwx /Users/user/Documents/pictures
This will only work if you are yourself in group www-data (or root).
You might want to make existing files in that directory writable:
$ chgrp www-data /Users/user/Documents/pictures/*
$ chmod g+rw /Users/user/Documents/pictures/*
You also need to check that all the directories above /Users/user/Documents/pictures are accessible to www-data. So chgrp/chmod them as well if they are not open to anyone.
Looks like you don't have the write permissions at some point along the way to /Users/user/Documents/pictures/lol.jpg - you should modify permissions in there accordingly (whilst bearing in mind security implications)

call python from nodejs on AWS lambda - permission denied

I am able to call my python from nodejs on AWS Lambda using the below function. However, because I need specific python libraries, I created a virutalenv in the env directory. I zipped everything up and pushed to Lambda. But when I try and call python from the virtual directory I get a Permission Denied error.
I attempted to modify the chmod permissions on Lambda before calling python but got Operation Not Permitted. How can I get this to run?
console.log('Loading event');
var exec = require('child_process').exec;
exports.handler = function(event, context) {
exec('env/bin/python district.py \'' + JSON.stringify(event) + '\'', function(error, stdout) {
var obj = stdout.toString();
context.done(error, obj);
});
};
Here's the error:
{
"errorMessage": "Command failed: /bin/sh: env/bin/python: Permission denied\n",
"errorType": "Error",
"stackTrace": [
"",
"ChildProcess.exithandler (child_process.js:658:15)",
"ChildProcess.emit (events.js:98:17)",
"maybeClose (child_process.js:766:16)",
"Process.ChildProcess._handle.onexit (child_process.js:833:5)"
]
}
The error most likely signals that python.exe does not have the executable bit set. Note, however, that even if you set the x bit, it won't work: .exe files are Windows executables, and they won't work.
Note, this virtual env was created in windows. I also attempted from Linux in the i.e. env/bin/python district.py with no help.
env/bin/python is the correct command. If you still get the Permission Denied error, the it means that the file python is missing the executable bit.
In the AWS Lamba runtime environment, you are not allowed to change permissions of files, nor to change user, therefore you must set the executable bit (or any other permission bit you need) when creating the .zip archive.
To sum up:
On Linux machines, use Linux executables.
Set the executable bit of the executables before creating archive.
Try this out:
exec('python district.py "'+ JSON.stringify(event) +'"', function(error, stdout) {
console.log('Python returned: ' + stdout + '.');
context.done(error, stdout);
});
Amazon has a tutorial on using Python in Lambda here

Categories

Resources