Display python script output to HTML page - python

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>"

Related

How do I accept post requests with a python script using cgi?

I want to submit text to an HTML form and send it to a Python script. When I press the submit button it takes me to an error page that says:
Error code: 501 Message: Unsupported method ('POST'). Error code explanation: HTTPStatus.NOT_IMPLEMENTED - Server does not support this operation.
I'm not exactly sure what the issue is. I've googled the error message and have looked through different documentation and watched some videos but they are seem to gloss over how to set up the server correctly.
I'm running Python 3.7.
<form action="www/cgi-bin/hello.py" method="post">
First Name:
<input type="text" name="first_name" placeholder="e.g. Barack" required="required"/>
Last Name:
<input type="text" name="last_name" placeholder="e.g. Obama" required="required"/>
<input type="submit" name="submitprompt" value="Submit"/>
</form>
#!/usr/bin/python
import cgi, cgitb
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print("Content-type:text/html")
print("")
print("")
print("Hello - Second CGI Program")
print("")
print("")
print(" Hello %s %s" % (first_name, last_name))
print("")
print("")
I'm expecting to be taken a page that has the text: Hello first_name last_name. Instead, I receive the aforementioned error.
Using the command "python3 -m http.server --cgi 8000" and configuring from there solved my issue.

Python CGI Script With Two Submit Buttons

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>"

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.

Problem with python cgi in Firefox

I have written an html form and am trying to incorporate a python cgi script with it. I have already configured my apache server to execute cgi scripts from the cgi-bin directory. Here's the html form:
<html>
<body>
<form name="input" action="c:/xampp/cgi-bin/test2.py" method="post">
<input type="text" name="qry" />
<input type="submit" value="GO!" />
</form>
</body>
</html>
And here's the test2.py cgi script:
#!c:/Python27/python.exe -u
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
qry = form["qry"].value
print "Content-Type: text/html"
print
print "<html"
print "<body>"
print qry
print "</body>"
print "</html>"
The html page is located in my htdocs folder and the cgi script is in the cgi-bin directory. However, when I enter something into the form and submit, firefox returns an error message saying: "Firefox doesn't know how to open this address, because the protocol (c) isn't associated with any program". Why is this error occurring? Does it have something to do with my path to the cgi script in my html page? Thanks in advance!
You are correct: it has something to do with the path to the CGI script on the HTML page. The form's action attribute should refer to the path where the CGI script is getting interpreted on the server, e.g., /cgi-bin/test2.py.
Since you made this mistake, I'm assuming you are new to web development. Consider using mod_wsgi and a framework like Django instead of CGI, especially if you expect a lot of traffic or you are making a web application and not just handling a single form.

Categories

Resources