mardi 21 juin 2016

Use Python CGI to display file contents in <div>

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('&', '&amp;').replace('<', '&lt;')
  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/htmlrnrn"
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.

Aucun commentaire:

Enregistrer un commentaire