Problemas con CGI

Daniel Cabrera cabrerachaparro en gmail.com
Jue Nov 9 22:29:07 CET 2006


lo que me bota el error log del apache es lo siguiente:

[Mon Nov 06 19:30:13 2006] [error] (2)No such file or directory: exec of
'/usr/lib/cgi-bin/dba.py' failed
[Mon Nov 06 19:30:13 2006] [error] [client 127.0.0.1] Premature end of
script headers: dba.py, referer: http://localhost/dba.html

el codigo del archivo dba.py es el siguiente:

from writeerror import writeError
import cgi, MySQLdb, os, Cookie
import cgitb
cgitb.enable()

def printLogOn(usercomment):
    print "content-type:text/html\n\n"
    print "<html><head><title>%s</title></head>" %usercomment
    print "<body>"
    print "<center>"
    print '<form name="logon" action="http://localhost/cgi-bin/dba.py"
method = "post">'
    print '<center>'
    print '<table width="60%" align="center" cellpadding=2 border=2
cellspacing=2>'
    print '<tr>'
    print '<td><b>User Name</b></td>'
    print '<td><input type="text" name="user" value="root"></td>'
    print '</tr>'
    print '<tr>'
    print '<td><b>Password</b></td>'
    print '<td><input type = "password" name = "pass"></td>'
    print '</tr>'
    print '<tr>'
    print '<td><b>Host Name</b></td>'
    print '<td><input type = "text" name = "host" value = "localhost"></td>'
    print '</tr>'
    print '<tr>'
    print '<td><b>Port</b></td>'
    print '<td><input type = "text" name = "port" value = "3306"></td>'
    print '</tr>'
    print '</table>'
    print '<br><br>'
    print '<input type = "submit" value = "Log On">'
    print '<input type = "reset" value = "Reset">'
    print '</form>'
    print '</body>'
    print '</html>'

def main():
    global username, password, host, port
    form = cgi.FieldStorage()
    if not(form.has_key("user") and form.has_key("host") and
form.has_key("port"))
and (getCookieValue("user") is None or getCookieValue("user")==""):
        printLogOn("Please fill the required fileds to log on")
        return
    if (getCookieValue("user")is None) or (getCookieValue("user"=="")):
        if form.has_key("pass"):
            password=form["pass"].value
        else:
            password = ""
        try:
            port = int(form["port"].value)
        except:
            printLogOn("Please enter the port number in integers.")
            return

            con =
connect(username=form["user"].value,password=password,dbhost=form["host"].value,dbport=form["dbport"].value,)
            user=form["user"].value
            host=form["host"].value
            port=form["port"].value
            if con is None:
                printLogOn("Unable to log on. Please ensure that the log on
information is correct.")
                return
            else:
                closeConnection(con)
                print setCookie("user", form["user"].value)
                print setCookie("pass", password)
                print setCookie("host", form["host"].value)
                print setCookie("port", form["port"].value)
                printMainPage(user, password, host, port)
    else:
        if form.has_key("name") and form.has_key("drop") and
form["drop"].value=="yes":
            result=dropDatabase(form["name"].value)
            if result==-1:
                prinMainPage(msg="Could not connect to the database server
while dropping database.")
                return
            else:
                prinMainPage(msg="The selected database is dropped.")
                return
        else:
            printMainPage()

def connect(username,password,dbhost,dbport):
    if username is None or password is None:
        return None
    try:
        con=MySQLdb.connect(host=dbhost,port=int(dbport),user=username,passwd=password)

    except MySQLdb.OperationalError,(errnum,errmsg):
        #writeError("An error occurred while connecting to the
server\n"+str(errnum)+": "+errmsg) return None
        writeError("An error occurred while connecting to the
server\n"+str(errnum)+": "+errmsg)
        return None
    except Exception,err:
           writeError("An error occurred while connecting to the
server\n"+str(err))
           return None
    else:
        return con

def closeConnection(con):
    if con is None:
        return 1
    try:
        con.close()
    except MySQLdb.OperationalError, (errnum,errmsg):
        print "Error", errnum, ": ", errmsg
        return 0
    except Exception,err:
        print "Error:",err
        return 0
    else:
        return 1

def createDatabase(username, password,
dbName,dbhost='localhost',dbport=3306):
    con = connect(dbhost=dbhost, dbport=dbport,
username=username,password=password)
    if con is None:
        return 0
    try:
        cur=con.cursor()
        if isDatabaseExists(username, password, dbName, dbhost, dbport):
            cur.execute("drop database %s" %dbName)
        strqry="create database %s" %dbName
        cur.execute(strqry)
    except MySQLdb.OperationalError,(errnum,errmsg):
        writeError("Error creating database.\n"+str(errnum)+": "+errmsg)
        print "Error",errnum,": ",errmsg
        closeConnection(con)
        return 0
    except Exception, err:
        writeError("Error creating database.\n"+str(err))
        print "Error", err
        closeConnection(con)
        return 0
    else:
        closeConnection(con)
        return 1

def setCookie(tag,value):
    ck=Cookie.Cookie()
    ck[tag]=value
    ck[tag]["version"]=1
    return ck

def getCookieValue(tag):
    try:
        ck=os.environ["HTTP_COOKIE"]
    except KeyError, e:
        return None
    else:
        ck=Cookie.Cookie()
        ck.load(os.environ["HTPP_COOKIE"])
        if ck.has_key(tag) :
            return ck[tag].value
        else:
            return None

def getDatabases(user=None,password=None,host=None,port=None ):
    if user is None:
        user = getCookieValue("user")
        password = getCookieValue("pass")
        host = getCookieValue("host")
        port = getCookieValue("port")
    con = connect(username=user,password=password,dbhost=host,dbport=port)
    if con is None :
        print 'Unable to connect.'
        return None
    else:
        try:
            cur=con.cursor()
            cur.execute("show databases")
            rst=cur.fetchall()
            lstData=[]
            for r in rst :
                lstData.append(r[0])
            cur.close()
            closeConnection(con)
            return lstData
        except Exception,e :
            writeError("Error: "+str(e))
            print "An error occurred while retrieving the database
names.<br>",e
            return None

def dropDatabase (dbname ):
    user = getCookieValue("user")
    password = getCookieValue("pass")
    host = getCookieValue("host")
    port = getCookieValue("port")
    con = connect(username=user,password=password,dbhost=host,dbport=port)
    if con is None :
        return -1
    else:
        try:
            cur=con.cursor()
            cur.execute("drop database %s" %dbname)
            cur.close()
            closeConnection(con)
            return 1
        except Exception,e:
            writeError("Error: "+str(e))
            return 0
            return None

def printMainPage (user=None,password=None,host=None,port=None,msg=None ):
    print "content-type:text/html\n\n"
    print "<html><head><title>Welcome to MySQL DBA
Application</title></head>"
    print "<body>"
    print "<center>"
    print '<font size=4><b><i>Welcome to MySQL DBA
Application</i></b></font><br>'
    if msg is not None :
        print '<br><font size=4><b>%s</b></font>' %msg
    print '<br><b>Click any database to view its details</b>'
    print '<br><br><font size=3><em><b>Available Databases</em><b></font>'
    if user is None :
        lstData=getDatabases()
    else:
        lstData=getDatabases(user, password, host, port)

    if lstData is not None :
        print '<table width="60%" border=0 cellpadding=2>'
        for l in lstData :
            print '<tr><td><a href="showData.py?name=%s">%s</a></td>' %(l,
l.upper())
            print '<td><a href="dba.py?name=%s&drop=yes">Drop
Database</a></td></tr>' %l
        print '</table>'

    print '<br><br><b>Other Options</b>'
    print '<br><a href="create.py"><font size=2><i>Create
Database</i></font></a>'
    print '<br><a href="logout.py"><font size=2><i>Log Off</i></font></a>'
    print '</center>'
    print '</body></html>'

if __name__=="__main__" :
    main()

el codigo del writeerror.py es el siguinte:

def writeError (errMsg ):
    try:
        import time
        f=open("dbaerror.log","a")
        lst=time.localtime()
        tmNow="%d/%d/%d %d:%d:%d -->"
%(lst[2],lst[1],lst[0],lst[3],lst[4],lst[5])
        f.write(tmNow+errMsg+"\n")
        f.close()
    except Exception,e :
        print "<h3>An Exception occurred while trying to log error: %s .
Exception description: %s. </h3>", errMsg,str(e)
        return

y el codigo del dba.html es:

<!-- dba.html -->
<html>
<head>
<title>The MySQL DBA Page</title></head>
<body>
<form name="logon" action="dba.py" method="post">
<center>
<table width="60%" align="center" cellpadding=2 border=2 cellspacing=2>
<tr>
<td><b>User Name</b></td>
<td><input type="text" name="user" value="root"></td>
</tr>
<tr>
<td><b>Password</b></td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td><b>Host Name</b></td>
<td><input type="text" name="host" value="localhost"></td>
</tr>
<tr>
<td><b>Port</b></td>
<td><input type="text" name="port" value="3306"></td>
</tr>
</table>
<br><br>
<input type="submit" value="Log On">
<input type="reset" value="Clear">
</form>
</body>
</html>




El día 9/11/06, Andrés Ignacio Martínez Soto <al084070 en alumail.uji.es>
escribió:
>
> Hola... repito por si el mail no llegaron a leerlo.
> En la cabecera del tipo mime hay que poner "\n\n" , es decir,
> "Content-Type: text/html\n\n" .
> Si no, Apache, Cherokee, IIS, Python.HTTPBaseServer ... dan errores del
> tipo "Premature end of headers", ya que NO saben el tipo MIME del
> fichero puesto que no se está siguiendo el estándar RFC correspondiente,
> y el servidor no sabe como interpretar esos datos.
>
> Los permisos UNIX derían ser:
> u: rwx
> g: r-x
> o: ---
> (750);
> En caso que el usuario www-data de Apache perteneciese al grupo ...
>
> Logs de Apache2 en /var/log/apache2/error.log
>
>
> Saludos
>
>
>
> Daniel Cabrera escribió:
> > segui nuevamente sus consejos y no me bota ningun error en la consola,
> > tambien estan las ordenes para que bote los erroes en el browser y en el
> > browser no me bota ningun error, tampoco encontre la ruta
> > /etc/httpd/logs/error_log. Cuando usaba apache1 ahi si funcionaba, lo
> > que si
> > pude es correr un script de prueba pero cuando llamo a este desde la
> > pagina
> > html me bota error.
> >
> > Les serviria que adjunte el codigo del .py?
> >
> > 2006/11/8, aNgel rEsendiz g. <sonajadiabolica en gmail.com>:
> >>
> >> Que tal.
> >>
> >>     El problema es de tu script, no de configuración. Intenta
> >> ejecutarlo desde consola, haber que errores te da.
> >>
> >> También puedes intentar poner esta linea debajo de "import cgi":
> >> "import cgitb; cgitb.enable()"
> >>
> >> Con ello, se te mostrarán los mensajes de error en el browser.
> >>
> >> Saludos
> >>
> >>
> >> On 11/8/06, Daniel Cabrera <cabrerachaparro en gmail.com> wrote:
> >> > Hola,
> >> > segui sus consejos y coloque el archivo .py en /usr/lib/cgi-bin y
> >> le di
> >> > permiso de ejecucion, ahora cuando lo ejecuto me sale un error en el
> >> Browser
> >> > numero 500, voy al error.log de apache y me aparece estas lineas
> >> >
> >> > [Mon Nov 06 19:30:13 2006] [error] (2)No such file or directory:
> >> exec of
> >> > '/usr/lib/cgi-bin/dba.py' failed
> >> >
> >> > [Mon Nov 06 19:30:13 2006] [error] [client 127.0.0.1] Premature end
> of
> >> > script headers: dba.py, referer: http://localhost/dba.html
> >> >
> >> > Por favor alguna sugerencia al respecto? ya me pase todo el dia
> >> buscando
> >> la
> >> > solucion pero no la pude hallar
> >> >
> >> > Gracias
> >> >
> >> > 2006/11/6, aNgel rEsendiz g. <sonajadiabolica en gmail.com>:
> >> > >
> >> > > Que tal.
> >> > >    Hace poco tiempo hubo un problema similar, tal vez te pueda
> >> servir
> >> > > leer el hilo, parece que el problema se solucionó, aunque no hubo
> >> > > confirmación, básicamente coloca el archivo.py en /usr/lib/cgi-bin,
> >> > > dale permisos de ejecución y llamalo con
> >> > > http://localhost/cgi-bin/archivo.py.
> >> > >
> >> > > Saludos.
> >> > >
> >> > > On 11/6/06, Daniel Cabrera <cabrerachaparro en gmail.com> wrote:
> >> > > > Hola,
> >> > > > estoy haciendo pruebas con CGI escrito en Python, pero al
> >> momento de
> >> > > llamar
> >> > > > al archivo .py desde el formulario en html me aparece un
> >> mensaje de
> >> > > error
> >> > > > que dice que no encuentra el archivo .py, pero lo curioso es
> >> que al
> >> > > moemnto
> >> > > > de depurar el archivo si me lo leia.
> >> > > > El archivo html y el archivo .py lo tengo en la misma carpeta
> >> > > (/var/www/) y
> >> > > > en el archivo html simplemente pongo action=dba.py
> >> > > >
> >> > > > Estoy usando Ubuntu con Apache2
> >> > > >
> >> > > > Gracias
> >> > > >
> >> > > > --
> >> > > > Daniel Cabrera Chaparro
> >> > > > _______________________________________________
> >> > > > Python-es mailing list
> >> > > > Python-es en aditel.org
> >> > > > http://listas.aditel.org/listinfo/python-es
> >> > > >
> >> > >
> >> > >
> >> > > --
> >> > > aNgel rEsendiz.!
> >> > > _______________________________________________
> >> > > Python-es mailing list
> >> > > Python-es en aditel.org
> >> > > http://listas.aditel.org/listinfo/python-es
> >> > >
> >> >
> >> >
> >> >
> >> > --
> >> > Daniel Cabrera Chaparro
> >> > _______________________________________________
> >> > Python-es mailing list
> >> > Python-es en aditel.org
> >> > http://listas.aditel.org/listinfo/python-es
> >> >
> >>
> >>
> >> --
> >> aNgel rEsendiz.!
> >> _______________________________________________
> >> Python-es mailing list
> >> Python-es en aditel.org
> >> http://listas.aditel.org/listinfo/python-es
> >>
> >
> >
> >
>
> _______________________________________________
> Python-es mailing list
> Python-es en aditel.org
> http://listas.aditel.org/listinfo/python-es
>



-- 
Daniel Cabrera Chaparro




Más información sobre la lista de distribución Python-es