RafaelBrianeziDaSilva
RafaelBrianeziDaSilva

Reputation: 97

How to execute a bash script through a CGI script written in Python?

I am trying to use a CGI script written in Python to execute a bash script, however it only works correctly when I run the script python manually. When I run via Browser, the CGI execution returns 200, however the bash script does not run.

Here's an example of what I'm trying to do, but using two simple scripts just to explain, okay?

The cgi script was created in the following apache directory and is accessible without problems: /var/www/cgi-bin/raf_teste.cgi

Below is the content of the raf_teste.cgi script:

#!/usr/bin/python3.5
import subprocess
import cgi, cgitb
cgitb.enable()

print ("Content-type:text/html\r\n\r\n")
command = ['./raf.sh']
subprocess.Popen(command)

Within the same directory "/var/www/cgi-bin/" a BashScript named raf.sh was created: /var/www/cgi-bin/raf.sh

Below is the content of the raf.sh script:

#!/bin/bash
echo "rafael" > "/tmp/rafael.txt"

Note: In the test I did using the python subprocess module to run linux command, everything worked perfectly, but in this case I am trying to run another script through a python CGI, it is not working and no error message is displayed.

Could you help me please?

Upvotes: 1

Views: 2200

Answers (1)

Rob Bricheno
Rob Bricheno

Reputation: 4653

Okay, pretty sure I've got it.

The problem is that you ran your script by hand before you ran it on the web.

That caused "/tmp/rafael.txt" to be created, owned by your user. Now, no other user (including the web server user) can write to that file because the file already exists, owned by you, and that's how /tmp works.

The solution is easy: delete "/tmp/rafael.txt". Then I bet your script works.

Upvotes: 1

Related Questions