accessing a database from a python cgi - python

I configured the httpd file to run python scripts as given in a website. After the configuration I was amazed to see .py file getting executed when placed in the htdocs folder, but .cgi files are not being executed. The error says an internal error.
Thought of proceeding with .py files but when I try to access mysql database, I am not able to.
My .py file is:
import cgi
import MySQLdb
print "Content-type: text/html"
print
print "<html><head>"
print ""
print "</head><body>"
form=cgi.FieldStorage()
name=form["t1"].value
print "Hello. %s" %name
print "hai"
print '<input type="submit"/>'
Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="root", passwd="pwd", db="db1")
cursor = Con.cursor()
sql="SELECT * FROM rec"
cursor.execute(sql)
data = cursor.fetchone()
print "%s" %data
print "</body></html>"
I am not getting any error, but 'data' is not getting printed
output I got was:
hello name hai submit button
new to python. So can u guys please help me out?
python version-2.7
db-mysql
server-apache 2.2
win32 bit

Put following line at first line, and see what error happened (traceback).
import cgitb; cgitb.enable()

Related

Using OracleDB OS.Environment Password

I am trying to connect to an oracle database with Python code. I am using the OracleDB package but want it so that the user is able to connect to the DB with their own password machine and password rather than coding it into the code itself.
So far I have this,
import oracledb
import os
username=os.environ.get("Username")
pw=os.environ.get("pasword")
conn = oracledb.connect(user=username, password=pw, host="url", port=0000, service_name="service"
Source the environment variables (Make them available to the python process)
$cat env.sh
export USERNAME=app_schema
export PASSWORD=secret
$cat connect.py
import oracledb
import os
username=os.environ.get("USERNAME")
pw=os.environ.get("PASSWORD")
conn = oracledb.connect(user=username, password=pw, host="localhost", port=1521, service_name="XEPDB1")
c = conn.cursor()
c.execute('select dummy from dual')
for row in c:
print (row[0])
conn.close()
$ # source the variables (note the dot)
$. env.sh
$python connect.py
X
Best of luck!

Python pytds - Getting output from Microsoft SQL server commands

I'm attempting to write a quick Python program that executes the "sp_updatestats" command on a Microsoft SQL server. I think I have the actual command working, but I don't know for sure because I don't think I have the logging working properly. I want to get the messages returned from the server from running the command and write them to a log file, but I just can't suss it out.
If I use cur.fetchall(), I get: "Previous Statement didn't produce any results"
If I use cur.messages, I get: []
If I use cur.return_value, I get: 0
I'm expecting a return like I would get if I ran "sqlcmd" from a command prompt with a "-o c:\log.txt" switch.
I'm using python 3.9
Here's my (sanitized) code:
import pytds
import datetime
from pytds.login import NtlmAuth
import pytds.extensions
import time
current_date = datetime.date.today()
date_string = str(current_date)
extention = '.txt'
logname = 'log' + date_string + extention
with pytds.connect('server', 'database', 'username', 'password') as conn:
with conn.cursor() as cur:
cur.execute("sp_updatestats")
#results = cur.fetchall()
#results = cur.get_proc_return_status()
#results = cur.messages
#results = cur.return_value
resultstr = str(results)
with open(logname, 'w') as f:
f.write(resultstr)
cur.close()
quit()

Error in python script running in xampp windows

I am new to PYTHON and usually code on PHP. This is the first script I am trying to run on Windows XAMPP. I enabled addhandler for .py and trying to run the following script:
#!C:\Python33\python.exe
# enable debugging
import cgitb
cgitb.enable()
print ("Content-Type: text/html;charset=utf-8")
print ("Hello World!")
and I am getting the following error while running the code:
The server encountered an internal error and was unable to complete your request.
Error message:
malformed header from script 'test.py': Bad header: Hello World!
If you think this is a server error, please contact the webmaster.
You should separate headers from body printing additional newline:
#!C:\Python33\python.exe
import cgitb
cgitb.enable()
print("Content-Type: text/html;charset=utf-8")
print() # <----------- addtional newlnie for header/body separation.
print("Hello World!")
For anyone who's still getting an error, try replacing print() by print("\r\n") in the following way:
print("Content-Type: text/html;charset=utf-8")
print("\r\n")
print("Hello World!")
This should work!

Python Pages No Rendered

I have created a CGIHTTPServer which works fine, problem is no matter what I do, the python pages are never rendered and the source code is always shown in the browser.
pyhttpd.py
#!/usr/bin/python
import CGIHTTPServer
import BaseHTTPServer
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = [""]
PORT = 8080
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
cgi-bin/hello.py
#!/usr/bin/python
print 'Content-Type: text/html'
print
print '<html>'
print '<head><title>Hello</title></head>'
print '<body>'
print '<h2>Hello World</h2>'
print '</body></html>'
http://some.ip.address:8080/cgi-bin/hello.py:
#!/usr/bin/python
print 'Content-Type: text/html'
print
print '<html>'
print '<head><title>Hello</title></head>'
print '<body>'
print '<h2>Hello World</h2>'
print '</body></html>'
I have set the permission on all files to executable, .html files render fine, even moving the file back to the root folder where the server is running makes no difference, I have tried running as root as well as another normal user, exactly the same results.
Tried googling "python pages not rendered" but have not found anything useful !
EDIT
I have also tried running a simpler server with no overrides, but the result is identical, pything code is never rendered:
pyserv.py
#!/usr/bin/python
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
serve = HTTPServer(("",80),CGIHTTPRequestHandler)
serve.serve_forever()
I believe you're having this issue because you have overridden cgi_directories.
The relevant portion of the documentation reads:
"This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts."
Either place your script in the root directory, or remove the override for cgi_directories and place the scrips in the /cgi-bin directory.
Here is a good link that describes a similar simple setup line by line:
https://pointlessprogramming.wordpress.com/2011/02/13/python-cgi-tutorial-1/
UPDATE:
According to a comment on the above page, it appears that setting cgi_directories = [""] results in disabling the cgi directory feature. Instead, set cgi_directories = ["/"], which sets it to the current directory.

first python program need a bit of help writing to file

I have a small program that I'm trying to create to get ip addresses from an sqlite db and run the whois command on and write it to a data file.
import sqlite3
import os
v_path = os.path.abspath('')
v_db = os.path.abspath("../")+"/logsql.sqlite"
v_ip = v_path+"/Whois.Resources/Who.IP.txt"
print v_ip
try:
f1 = open(v_db)
f2 = open(v_ip, "w")
conn = sqlite3.connect(v_db)
c = conn.cursor()
c.execute("select remote_host from connections group by remote_host;")
for row in c:
print row
#p.write("sts")
c.close()
f1.close()
f2.close()
except IOError as e:
print 'Oh dear, shit just hit the fan.'
The output looks like this
bash$ python WhoIs.Program.py
/Users/frankwiebenga/Documents/Spring 2012/Malware/WhoIs/Whois.Resources/Who.IP.txt
Oh dear, shit just hit the fan.
The issue is opening v_ip, the v_db opens fine. The file is there
bash$ pwd
/Users/frankwiebenga/Documents/Spring 2012/Malware/WhoIs/WhoIs.Resources
bash$ ls
Who.IP.txt
frank-wiebengas-macbook-pro:WhoIs.Resources frankwiebenga$
The directory structure is
logsql WhoIs{directory}
____________
WhoIs.Program.py WhoIs.Resources{directory}
____________
Who.IP.txt
Whois.Resources should be WhoIs.Resources. Linux is case sensitive.
P.S. Thanks for including enough information in your question to figure this out. It's rare for that to happen.

Categories