I have a VPS server with Apache on it. I want to execute simple CGI script. I created a python script, saved it as .cgi file and placed it to the folder cgi-bin, but it only displays error message: "End of script output before headers".
However when I saved this script as .py file and did not place it into cgi-bin folder, it worked, but whenever there was an error, it did not show any error message, just server error. Command cgitb.enable() did not show any error.
I tried to give the file 755 permission, but that still did not solve my problem.
Where could be a problem?
Source code:
#!/usr/local/bin/python3
print("Content-type:text/html")
print("")
print ("<html><head><title>CGI</title></head>")
print ("<body>")
print ("hello cgi")
print ("</body>")
print ("</html>")
Thank you for your answers.
It might be more useful to use sys.stdout.write and add \n so that you know exactly what gets written to standard output:
#!/usr/bin/env python
import sys
import os
sys.stdout.write('Status: 200 OK\n')
sys.stdout.write('Content-Type: text/html; charset=utf-8\n\n')
sys.stdout.write('<html><body>Hello, world!</body></html>\n')
sys.exit(os.EX_OK)
Run the script with python script.py | cat -e so that you can verify line endings.
Make sure you aren't sending any more HTTP headers after you start sending content.
Related
I want to build an interface for browsing an Apache2 server using python scripts.
I spent the past days learning python and today getting familiar with CGI. I want to test out some stuff, like the possibility for the user to navigate to the path he wants from the base directory
/var/www/cgi-bin
by inputting the path he wants to visit, for example
/etc/httpd/conf.d.
For that i have the change_path.py script which looks like this:
import os
def changePath(path):
os.chdir(path)
I already got this script running to make sure everything is set up properly:
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb, os
cwd = os.getcwd()
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>TestScript</title>"
print "</head>"
print "<body>"
print "<h2> Current working directory is: %s</h2>" % cwd
print "</body>"
I have a script test.py which is used for server automation task and have other script server.py which list out all server name.
server.py list all sevrer name in text.log file and this log file is used by test.py as a input.
I want one single script test.py to execute server.py from inside it and also redirect server.py script output to text.log file as well.
So far i have tried with execfile("server.py") >text.log in test.py which didn't worked.
Use subprocess.call with stdout argument:
import subprocess
import sys
with open('text.log', 'w') as f:
subprocess.call([sys.executable, 'server.py'], stdout=f)
# ADD stderr=subprocess.STDOUT if you want also catch standard error output
I find a sample code in "programming python", whose output is different from my test.
My platform is Ubuntu + python 2.7.
In the html, a POST request is made:
<form method=POST action="test.py">
In test.py, a HTTP response is made like this:
print 'Content-type: text/html\n'
print '<title>Reply Page</title>'
print 'Who are you?'
After form submission in HTML page, chrome displays code of text.py rather than a html page. However the book shows the output as a html page.
Is the book wrong?
Turn on UNIX execution bit on test.py
Start it test.py with line
#!/usr/bin/env python
And then run UNIX command
chmod u+x test.py
This turns to file to executable UNIX script.
Also you might need to change your web server settings to allow the execution of cgi-bin style scripts.
Thanks in advance for any help. I am fairly new to python and even newer to html.
I have been trying the last few days to create a web page with buttons to perform tasks on a home server.
At the moment I have a python script that generates a page with buttons:
(See the simplified example below. removed code to clean up post)
Then a python script which runs said command and outputs to an iframe on the page:
(See the simplified example below. removed code to clean up post)
This does output the entire finished output after the command is finished. I have also tried adding the -u option to the python script to run it unbuffered. I have also tried using the Python subprocess as well. If it helps the types of commands I am running are apt-get update, and other Python scripts for moving files and fixing folder permissions.
And when run from normal Ubuntu server terminal it runs fine and outputs in real time and from my research it should be outputting as the command is run.
Can anyone tell me where I am going wrong? Should I be using a different language to perform this function?
EDIT Simplified example:
initial page:
#runcmd.html
<head>
<title>Admin Tasks</title>
</head>
<center>
<iframe src="/scripts/python/test/createbutton.py" width="650" height="800" frameborder="0" ALLOWTRANSPARENCY="true"></iframe>
<iframe width="650" height="800" frameborder="0" ALLOWTRANSPARENCY="true" name="display"></iframe>
</center>
script that creates button:
cmd_page = '<form action="/scripts/python/test/runcmd.py" method="post" target="display" >' + '<label for="run_update">run updates</label><br>' + '<input align="Left" type="submit" value="runupdate" name="update" title="run_update">' + "</form><br>" + "\n"
print ("Content-type: text/html")
print ''
print cmd_page
script that should run command:
# runcmd.py:
import os
import pexpect
import cgi
import cgitb
import sys
cgitb.enable()
fs = cgi.FieldStorage()
sc_command = fs.getvalue("update")
if sc_command == "runupdate":
cmd = "/usr/bin/sudo apt-get update"
pd = pexpect.spawn(cmd, timeout=None, logfile=sys.stdout)
print ("Content-type: text/html")
print ''
print "<pre>"
line = pd.readline()
while line:
line = pd.readline()
I havent tested the above simplified example so unsure if its functional.
EDIT:
Simplified example should work now.
Edit:
Imrans code below if I open a browser to the ip:8000 it displays the output just like it was running in a terminal which is Exactly what I want. Except I am using Apache server for my website and an iframe to display the output. How do I do that with Apache?
edit:
I now have the output going to the iframe using Imrans example below but it still seems to buffer for example:
If I have it (the script through the web server using curl ip:8000) run apt-get update in terminal it runs fine but when outputting to the web page it seems to buffer a couple of lines => output => buffer => ouput till the command is done.
But running other python scripts the same way buffer then output everything at once even with the -u flag. While again in terminal running curl ip:800 outputs like normal.
Is that just how it is supposed to work?
EDIT 19-03-2014:
any bash / shell command I run using Imrans way seems to output to the iframe in near realtime. But if I run any kind of python script through it the output is buffered then sent to the iframe.
Do I possibly need to PIPE the output of the python script that is run by the script that runs the web server?
You need to use HTTP chunked transfer encoding to stream unbuffered command line output. CherryPy's wsgiserver module has built-in support for chunked transfer encoding. WSGI applications can be either functions that return list of strings, or generators that produces strings. If you use a generator as WSGI application, CherryPy will use chunked transfer automatically.
Let's assume this is the program, of which the output will be streamed.
# slowprint.py
import sys
import time
for i in xrange(5):
print i
sys.stdout.flush()
time.sleep(1)
This is our web server.
2014 Version (Older cherrpy Version)
# webserver.py
import subprocess
from cherrypy import wsgiserver
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
proc = subprocess.Popen(['python', 'slowprint.py'], stdout=subprocess.PIPE)
line = proc.stdout.readline()
while line:
yield line
line = proc.stdout.readline()
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8000), application)
server.start()
2018 Version
#!/usr/bin/env python2
# webserver.py
import subprocess
import cherrypy
class Root(object):
def index(self):
def content():
proc = subprocess.Popen(['python', 'slowprint.py'], stdout=subprocess.PIPE)
line = proc.stdout.readline()
while line:
yield line
line = proc.stdout.readline()
return content()
index.exposed = True
index._cp_config = {'response.stream': True}
cherrypy.quickstart(Root())
Start the server with python webapp.py, then in another terminal make a request with curl, and watch output being printed line by line
curl 'http://localhost:8000'
I am excuting myfile.py and I want to redirect the output to a file, so I did this:
python2.5 myfile.py > affiche.txt
However, when I display affiche.txt, I see that the output has been duplicated.
Why are the messages duplicated in this file? the main of myfile.py contains this:
print "\n[BG:INFO] Automatic generation of the machine features\n"
hostname = socket.gethostname()
rep=DeletePoints(hostname)
if exists(rep)==False:
print "\n[BG:INFO] The directory of work is: ", rep, "\n"