Search code examples
pythonbashpostbasehttpserver

BaseHTTPServer, extracting variable from POST single value


I want to know how to get variables form content POSTed with a html form, located on an external server.

I have this code :

myserver.py

import BaseHTTPServer

HOST_NAME = ''
PORT_NUMBER=8000

postVars = ''

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):

    def do_POST(s):
        global postVars
        s.send_response(200)
        s.end_headers()
        varLen = int(s.headers['Content-Length'])
        postVars = s.rfile.read(varLen)
        print postVars

server_class = BaseHTTPServer.HTTPServer
httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)

try:
    httpd.handle_request()
except KeyboardInterrupt:
    pass

print postVars
httpd.server_close()
postVars is valued during the Handler, but not after MyHandler

It currently print this on the console

user=jhon&domain=domain.com&pass=mypassword

I wnat to extract each variable and use them to call a subsequent bash script.

example of what I want to accomplish :

import os
value1="user"
value2="domain"
value3="pass"
os.system("./usersprivetes.sh %s %s %s" % (value1,value2,value3))

thank for your comment and assistance.


Solution

  • hello solved by adding some code, one that only serves me once, after that variables are passed back to no longer function, I think that is the order in which I have

    #cat server.py
    import BaseHTTPServer
    import urlparse
    import os
    
    HOST_NAME = ''
    PORT_NUMBER=8000
    
    postVars = ''
    
    class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    
        def do_POST(s):
            global postVars
            s.send_response(200)
            s.end_headers()
            varLen = int(s.headers['Content-Length'])
            postVars = s.rfile.read(varLen)
            #print postVars
    
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    
    try:
        httpd.handle_request()
    except KeyboardInterrupt:
        pass
    
    #print postVars
    
    qs = dict( (k, v if len(v)>1 else v[0] )
               for k, v in urlparse.parse_qs(postVars).iteritems() )
    #print qs
    
    pase = qs['pass']
    dominio = qs['domain']
    usuario = qs['user']
    
    os.system("./createuser.sh %s %s %s" % (pass,user,domain))
    httpd.serve_forever()
    

    thank you this made the magic

    qs = dict( (k, v if len(v)>1 else v[0] )
               for k, v in urlparse.parse_qs(postVars).iteritems() )