Use Python CGI to display file contents in <div> - python

I am trying to display the contents of /etc/postfix/transport.in in a <div> via python & cgi. When I run the script from the command line it works as I would expect, however, when called from the webpage it does not display the file contents. This is what I have in my CGI:
#!/usr/bin/env python
import cgi, os.path
# fileName = "/etc/postfix/transport.in"
form = cgi.FieldStorage()
fileName = form['file'].value
def safePlainText(s):
newString = s.replace('&', '&').replace('<', '<')
return newString
def fileLinesToHTMLLines(fileName):
safeLines = list()
if os.path.exists(fileName): # test if the file exists yet
lines = fileToStr(fileName).splitlines()
for line in lines:
safeLines.append(safePlainText(line))
return safeLines
def fileToStr(fileName):
fin = open(fileName);
contents = fin.read();
fin.close()
return contents
lines = fileLinesToHTMLLines(fileName)
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Data File %s</title>" % fileName
print "</head>"
print "<body>"
print "<ul>"
for line in lines:
print "<li> %s </li>" % str(cgi.escape(line))
print "</ul>"
print "</body>"
print "</html>"
Everything (HTML Tags incl. title) comes through as expected with the exception of the lines of the file I am trying to display. Firebug shows the response from the server as being:
<html>
<head>
<title>Data File transport.in</title>
</head>
<body>
<ul>
</ul>
</body>
</html>
However if I run the script from the command line I get:
# sudo -u apache ./test3.py
Content-type:text/html
<html>
<head>
<title>Data File /etc/postfix/transport.in</title>
</head>
<body>
<ul>
<li> host.domain.com relay:[mailhub.domain.corpnet1] </li>
<li> * relay:[host.mailrelay.com] </li>
</ul>
</body>
</html>
I am sure that it is something simple, but for the life of me I cannot figure it out...
I am running Python 2.7.5 / Apache 2.4.6 on RHEL7.

The "Data File" are different.
Data File transport.in
Data File /etc/postfix/transport.in
Please paste the url when you called from the webpage.

Related

Transition my results from python to html file

I need to transition my results from python to html file. How i can do this. I used format function. I know about split html, hybrid of Python and HTML. Both metod cannot be use. My project is big and i need operate on variables to move results from many function to HTML report file.
The code below is a simplified example of what I need to do
def function(n):
result = n + 5
return result
def main():
n = int(input('n: '))
result = function(n)
report = open('result.html', 'w')
html = """
<!DOCTYPE html>
<html>
<body>
<h1>First Head</h1>
<p>My result: ---> I need my result here <--- </p>
</body>
</html>
"""
report.write(html)
report.close()
if __name__ == '__main__':
main()
So you want the results from that function in the middle? Not that hard um. Really no fan of multiple line strings with """ but here goes...
html = """
<!DOCTYPE html>
<html>
<body>
<h1>First Head</h1>
<p>"""
html += result
html += """</p>
</body>
</html>"""
OR you could make it an easier oneliner... with "{}".format():
html = "<!DOCTYPE html>\n<html>\n<body>\n\n<h1>First Head</h1>\n<p>{}</p>\n\n</body>\n</html>".format(result)

Receiving "end of script output before headers" error even though script works

I created a simple html page to post to python script
<!DOCTYPE html>
<html>
<body>
<h1>Name</h1>
<form action="/cgi-bin/ver1.py" method="get">
<label for="fname">VIN</label>
<input type="text" id="fname" name="searchbox"><br><br>
<button type="submit" formtarget="_blank">Submit to a new window/tab</button>
</form>
</body>
</html>
the ver1.py looks like this:
#!C:\Python\python.exe
import requests
import webbrowser
import cgi
form = cgi.FieldStorage()
vin=form.getvalue('searchbox')
token='withheld'
dr=requests.get("withheld" % (token, vin))
window_stkr=(dr.json()["car"]["sticker"]["pdf"])
webbrowser.open_new_tab(window_stkr)
It all works correctly, except for the part where instead of just opening one new tab with window_stkr it also opens a second tab with the
end of script output before headers
error
when looking at the error log from apache, the only line there is following:
[Fri Sep 11 00:46:21.231868 2020] [cgi:error] [pid 11624:tid 1896]
[client ::1:54144] End of script output before headers: ver1.py,
referer: http://localhost/decoder.html
As #furas pointed out it was because I was not sending any response back to the browser.
I made below changes and instead of 3 tabs, I now have one html page and the pdf opens in a window where the error used to be:
#!C:\Python\python.exe
import requests
import webbrowser
import cgi
form = cgi.FieldStorage()
vin=form.getvalue('searchbox')
token='withheld'
dr=requests.get("withheld" % (token, vin))
window_stkr=(dr.json()["car"]["sticker"]["pdf"])
#webbrowser.open_new_tab(window_stkr)
print('Content-type:text/html\n\n')
print('<html>')
print(' <head>')
print(' <meta http-equiv="refresh" content="0;url='+str(window_stkr)+'" />')
print(' </head>')
print('</html>')

How can I see output from a Brython script on the page? Why doesn't `print` work?

I try to use Brython. I have a Python script (test.py) and I would like to display the result of this script in the browser.
I have tried :
<html>
<head>
<script src="brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python" src="test.py"></script>
</body>
</html>
and my script is :
x = int(input("Value: "))
x = pow(x,2)
print("Result: " + str(x))
Unfortunately, I cannot display the result in the browser. Is there something missing ?
In Brython, print displays in the browser console.
If you want to write the result in the HTML document:
from browser import document
x = int(input("Value: "))
x = pow(x, 2)
document <= "Result: " + str(x)
[edit] Another option is to set sys.stdout to an object with a write() method, for instance document in module browser :
from browser import document
import sys
sys.stdout = document
print("Hello", "world !")
Add an id='fish' whatever for tag and then overwrite it in python:
<body id='fish' onload='brython()'>
and then:
d = document['fish']
d.clear()
d <= "Result: %s" % str(x)
Note that you need to call element .clear() first, <= is the same as Javascript .appendChild(), see the documentation: https://brython.info/static_doc/en/cookbook/content_in_div.html
If you want to see it in proper XHTML page, don't replace the whole body but just one div-element/tag for example. Or overwrite the whole body with all needed XHTML tags.

How to execute external commands with Python using Apache2 and CGI

I have an Apache web server. I have an html file and a Python script located at var/www/myfolder. I am submitting a form through the html file which is handled by my Python script (when the submit button is clicked). But once handling the form, my Python script executes an external command. (see the following code)
webpage.html
<!DOCTYPE html>
<html>
<head>
<title>Webform</title>
</head>
<body>
<h3>Webform</h3>
<form action="myscript.py" method="POST">
<p>Name: <input type="text" name="name"></p>
<input type="submit" value="Submit">
</form>
</body>
</html>
myscript.py
#!/usr/bin/python -W
import cgi, cgitb
import sys
import os
# Get data from fields
form = cgi.FieldStorage()
name = form.getvalue('name')
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2></br></br>'
print '<p>Name: %s</p>' % (name)
print '</body>'
print '</html>'
os.system("./other_script.py") # gives me an error with permission
On my server I am user007 but I know that when I click submit on the html file, the Python script is executed as apache2 user. The problem is I don't know the password for this user (can't us sudo). Are the two ideas possible:
1) change from apache2 to user007 when trying to execute other_script.py from myscript.py
2) I know that you can change users using suEXEC but I have no idea how to use it.
Any suggestions?
I should let you know that locally both the python scripts are executing fine.
Edit 1:
I get this message before the error occurs: WARNING: HOME is not set, using root: /

Using Twitter-Bootstrap in Python 3.3 Server File

I'm currently in the proccess of editing the html in the Python 3.3 http server code. I am doing this so I can access my media files from anywhere in my LAN. The default interface is quite boring, so I wanted to spruce it up a bit with Twitter Bootstrap buttons. The below code is from my edited server.py file, starting on line 740 (please excuse the lack of editing or elegance):
title = 'Media Listing on Computer'
r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
'"http://www.w3.org/TR/html4/strict.dtd">')
r.append('<html>\n<head>')
r.append('<meta http-equiv="Content-Type" '
'content="text/html; charset=%s">' % enc)
r.append('<title>%s</title>\n<link href="file:///C:/Server/bootstrap.css" rel="stylesheet">\n<style type="text/css">a:link {color:grey; text-decoration: none;}</style>\n</head>' % title)
r.append('<body>\n<FONT FACE="arial" COLOR="grey">\n<h1>%s</h1>' % title)
#<body style="background-color:#B4F200;>
#<FONT FACE="courier" COLOR="grey">
r.append('<ul class="nav nav-pills nav-stacked">')
for name in list:
fullname = os.path.join(path, name)
displayname = linkname = name
# Append / for directories or # for symbolic links
if os.path.isdir(fullname):
displayname = name
linkname = name + "/"
if os.path.islink(fullname):
displayname = name + "#"
# Note: a link to a directory displays with # and links with /
r.append('<li class="active">%s</li>'
% (urllib.parse.quote(linkname), html.escape(displayname)))
r.append('</ul>\n</body>\n</html>\n')
encoded = '\n'.join(r).encode(enc)
f = io.BytesIO()
f.write(encoded)
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html; charset=%s" % enc)
self.send_header("Content-Length", str(len(encoded)))
self.end_headers()
return f
This generates a page with the following html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=mbcs">
<title>Media Listing on Computer</title>
<link href="file:///C:/Server/bootstrap.css" rel="stylesheet">
<style type="text/css">a:link {color:grey; text-decoration: none;}</style>
</head>
<body>
<FONT FACE="arial" COLOR="grey">
<h1>Media Listing on Computer</h1>
<ul class="nav nav-pills nav-stacked">
<li class="active">FRAPS</li>
<li class="active">iTunes</li>
<li class="active">Misc videos</li>
<li class="active">Movies</li>
<li class="active">TV</li>
</ul>
</FONT>
</body>
</html>
Now when I open the html in a web browser it works fine, in that it loads the Twitter Bootstrap UI, however, when I run the python server, the UI doesn't load. I would really like to know how I can fix this, so if someone could give me a hand in sorting this out, that would be appreciated.
Does your browser know you are using the correct stylesheet? Maybe try using a relative path for bootstrap instead of an absolute file:///C:/Server/bootstrap.css?
UPDATE (from comments)
You placed bootstrap in a directory outside of the server root directory, so your browser wasn't able to access the css and render it. Move bootstrap into the server directory (e.g. C:\Server\lib\http\bootstrap\) and update the stylesheet path accordingly (e.g. <link href="/bootstrap/bootstrap.css" rel="stylesheet">)

Categories

Resources