Python CGI Script With Two Submit Buttons - python

I want to use two submit buttons in python CGI. The CGI script then will take different action later in the same script depending on which button is pressed. This code will show 2 buttons, but not waiting for me to press the button. No chance to execute the following print. How to fix it?
import cgi, cgitb
print "Content-Type: text/html\n"
print "<html>"
print "<input type='submit' value='Run from Server' name='Submit1' />"
print "<input type='submit' value='Run from VNC' name='Submit2' />"
print "</html>"
cgitb.enable()
form = cgi.FieldStorage()
if "Submit1" in form:
print "Button 1..."
elif "Submit2" in form:
print "Button 2..."
else:
print "nothing..."

You appear to be missing your form tags...
print "Content-Type: text/html\n"
print "<html>"
print "<form>"
print "<input type='submit' value='Run from Server' name='Submit1' />"
print "<input type='submit' value='Run from VNC' name='Submit2' />"
print "</form>"
print "</html>"

Related

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('&', '&').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.

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: /

KeyError in Python

This is my code:
print """\
<form method="post">
Please enter Viewer Type:<br />
<table>
"""
#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"
print """\
<option value="C">Crowd Funding
<option value="P">Premium
"""
#do it button
print """\
<input type="submit" value="OK" />
"""
print """\
</form>
</body>
<html>
"""
ViewerType=form['ViewerType'].value
And, when I serve it to a browser, this is the error:
Traceback (most recent call last): File "/home/nandres/dbsys/mywork/James/mywork/ViewerForm.py", >line 42, in ViewerType=form['ViewerType'].value File "/usr/lib/python2.7/cgi.py", line 541, in >getitem raise KeyError, key KeyError: 'ViewerType'
And line 42 is the last line of my code.
The error isn't actually affecting functionality, and everything works fine, but I don't really want it popping up. Any advice/insight would be appreciated.
Btw, I have this at the top of my code:
import cgi
form = cgi.FieldStorage()
When your script is first called to render the page, the form dict is empty. The dict will only get filled when the user actually submits the form. So changing your HTML to
<option value="C" selected>Crowd Funding
won't help.
So you need to test the dict before you attempt to access it. Eg,
#! /usr/bin/env python
import cgi
form = cgi.FieldStorage()
print 'Content-type: text/html\n\n'
print "<html><body>"
print """\
<form method="post">
Please enter Viewer Type:<br />
<table>
"""
#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"
print """\
<option value="C">Crowd Funding
<option value="P">Premium
"""
#do it button
print """\
<input type="submit" value="OK" />
"""
print "</table></form>"
if len(form) > 0:
ViewerType = form['ViewerType'].value
print '<p>Viewer Type=' + ViewerType + '</p>'
else:
print '<p>No Viewer Type selected yet</p>'
print "</body></html>"
Simple solution if you don't want it popping:
try:
ViewerType=form['ViewerType'].value
except KeyError:
pass
It'll work but I would recommend you to debug your code and find out why you are getting KeyError. From https://wiki.python.org/moin/KeyError,
Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.

Display python script output to HTML page

I have this hello_world.py script which takes username and password and prints user information. Separately the python executes without any error. But, when I submit from HTML the html page gives internal server 500 error. I have added executable permission to script in file system, in httpd.conf. But, I am not sure why this is not executing when I provide submit.
Thanks for suggestions and help.
<form action="/cgi-bin/hello_world.py" method="post">
IP Address: <input type="text" name="user_name"><br />
Password: <input type="text" name="pass_word" />
<input type="submit" value="Submit" />
</form>
My python script is
#!/usr/bin/python
# Import modules for CGI handling
import cgi, cgitb
import getpass
import sys
import telnetlib
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
user_name = form.getvalue('user_name')
//username will get IP of machine
pass_word = form.getvalue('pass_word')
loginid = 'admin'
tc = telnetlib.Telnet(user_name)
tc.read_until("login: ")
tc.write(loginid + "\n")
tc.read_until("Password: ")
tc.write(pass_word + "\r\n")
tc.write("ls -l\n")
tc.write("exit\n")
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello </title>"
print "</head>"
print "<body>"
print "<h2> %s is IP and %s is passowrd</h2>" % (user_name, pass_word)
print tc.read_all()
print "</body>"
print "</html>"

Python Pass List into Form and Retrieve as List

What is the best way to pass List via form in python (cgi).
ListStr = ['State1', 'State2', 'State3']
TrVListStr = '##'.join(ListStr)
print """
<form method="post">
<input type=hidden name="state_carry" value="""+TrVListStr+"""><br />
<input type="submit" value="Submit" />
</form>
"""
After submission I should have list as it was before submission.
I can do split (based on ## rule) form['state_carry].value again to fetch that. but I think it is not good way.
Is there any way to pass Python List via form and retrieve them later.
Thanks.
You could use the python cgi module. The documentation specifically covers the case where you have multiple values for a certain field name.
The basic idea is that you can have multiple fields in your html form with the same name, and the value for each field is one of the values from the list. You can then use the getlist() method to retrieve all the values as a list. For example:
print "<form method=\"post\">"
for s in ListStr:
print "<input type=hidden name=\"state_carry\" value=\"" + s + "\"><br />"
print "<input type=\"submit\" value=\"Submit\" />"
print "</form>"
Then in your CGI script you'll have something like:
MyList = form.getlist("state_carry")
In python I would do.
###In the form page.
import cgi
#Convert list of values to string before passing them to action page.
ListStr=','.join(['State1', 'State2', 'State3'])
print "<input type=hidden name=\"state_carry\" value=\""+ListStr+"\"><br />"
###In the action page
import cgi
#Return the string passed in the user interaction page and transform it back to a list.
ListStr=cgi.FieldStorage().getvalue('state_carry').split(',')

Categories

Resources