Ejemplo n.º 1
0
 def _openSecureConnection(self):
     h2 = None
     try:
         if not self.proxy:
             h2 = httplib.HTTPS(self.DYNDNS_HOST)
         else:
             h2 = httplib.HTTPS(self.DYNDNS_HOST, self.alt_port)
         self.logger.logDebug("HTTPS connection successful")
     except:
         self.logger.logDebug("HTTPS connection error %s: %s" %
                              (sys.exc_info()[0], sys.exc_info()[1]))
     return h2
Ejemplo n.º 2
0
    def upload_patch(self, host, ref, filename):
        import httplib, os
        task_uuid = self.connection.task.create(
            self.session_uuid, "Uploading Patch",
            "Uploading Patch %s " % (filename.filename))
        self.track_tasks[task_uuid['Value']] = "Upload.Patch"
        conn = httplib.HTTPS(host)
        conn.putrequest(
            'PUT', '/pool_patch_upload?session_id=%s&task_id=%s' %
            (self.session_uuid, task_uuid['Value']))
        conn.putheader('Content-Type', 'text/plain')
        conn.endheaders()
        fp = filename.file
        blocknum = 0
        uploaded = 0
        blocksize = 4096
        while not self.halt_import:
            bodypart = fp.read(blocksize)
            blocknum += 1
            if blocknum % 10 == 0:
                uploaded += len(bodypart)

            if not bodypart: break
            conn.send(bodypart)

        fp.close()
        print "Finish upload.."
Ejemplo n.º 3
0
    def test_post_multipart(self):
        alphabet = "abcdefghijklmnopqrstuvwxyz"
        # generate file contents for a large post
        contents = "".join([c * 65536 for c in alphabet])

        # encode as multipart form data
        files = [('file', 'file.txt', contents)]
        content_type, body = encode_multipart_formdata(files)

        # post file
        if self.scheme == 'https':
            c = httplib.HTTPS('%s:%s' % (self.interface(), self.PORT))
        else:
            c = httplib.HTTP('%s:%s' % (self.interface(), self.PORT))
        c.putrequest('POST', '/post_multipart')
        c.putheader('Content-Type', content_type)
        c.putheader('Content-Length', str(len(body)))
        c.endheaders()
        c.send(body)

        errcode, errmsg, headers = c.getreply()
        self.assertEqual(errcode, 200)

        response_body = c.file.read()
        self.assertEquals(", ".join(["%s * 65536" % c for c in alphabet]),
                          response_body)
Ejemplo n.º 4
0
def delete_from_nexus(nexus_repository, items):
    global NEXUSHOST, NEXUSPORT, GLOBAL_TOTAL_REMOVED, PUSHGATEWAY_INSTANCE, mon, GLOBAL_DELETE_ERRORS
    if not GLOBAL_DELETE_ERRORS:
        return 3
    format_args = {"instance": PUSHGATEWAY_INSTANCE, "repo": nexus_repository}
    for item in items:
        url = NEXUSBASEURL + nexus_repository + "/content" + item['path']
        print("Sending HTTP DELETE request to https://{}:{}{}".format(
            NEXUSHOST, NEXUSPORT, url))
        auth = string.strip(
            base64.encodestring(NEXUSUSERNAME + ':' + NEXUSPASSWORD))
        service = httplib.HTTPS(NEXUSHOST, NEXUSPORT)
        service.putrequest("DELETE", url)
        service.putheader("Host", NEXUSHOST)
        #service.putheader("User-Agent", "Nexus cleaner")
        service.putheader("User-Agent", "DevOps ([email protected]) cleaner")
        service.putheader("Content-type", "text/html; charset=\"UTF-8\"")
        service.putheader("Authorization", "Basic %s" % auth)
        service.endheaders()
        service.send("")
        statuscode, statusmessage, header = service.getreply()
        print("Response: {} {}.".format(statuscode, statusmessage))
        if statuscode == 401:  #Unauthorized
            GLOBAL_DELETE_ERRORS = False
            return 2
        if statuscode == 204:
            GLOBAL_TOTAL_REMOVED += 1
            mon.push(
                "nexus_cleaner_versions_list", GLOBAL_TOTAL_REMOVED, {
                    "job": "nexus_cleaner",
                    "list": "removed",
                    "repo": format_args["repo"]
                })
    return 0
Ejemplo n.º 5
0
def getRecommendedEvents(username):
    # a "as lighter as possible" soap message:
    SM_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getRecommendedEvents xmlns="http://tempuri.org/">
      <username>""" + username + """</username>
    </getRecommendedEvents>
  </soap12:Body>
</soap12:Envelope>
"""
    SoapMessage = SM_TEMPLATE % ()
    ###construct and send the header
    webservice = httplib.HTTPS("192.168.56.102")
    webservice.putrequest("POST", "/uiinter/Service.asmx")
    webservice.putheader("Host", "192.168.56.100")
    webservice.putheader("User-Agent", "Python post")
    webservice.putheader("Content-type",
                         "application/soap+xml; charset=\"UTF-8\"")
    webservice.putheader("Content-length", "%d" % len(SoapMessage))
    webservice.putheader("SOAPAction", "\"\"")
    webservice.endheaders()
    webservice.send(SoapMessage)
    ## get the response
    statuscode, statusmessage, header = webservice.getreply()
    res = webservice.getfile().read()
    # for node in xmldoc.getElementsByTagName('DataTable'):  # visit every node <loginResult />
    #  print node.getElementsByTagName('name')[0].firstChild.nodeValue
    # # hold=node.firstChild.nodeValue
    # output=xmldoc.getElementsByTagName('loginResult')[0].firstChild.nodeValue
    # res="""<result><D><n>pharma</n></D></result>"""
    return res
Ejemplo n.º 6
0
 def _put_or_post_multipart(self, method, url, data):
     """
     encodes the data as a multipart form and PUTs or POSTs to the url
     the response is parsed as JSON and the returns the resulting data structure
     """
     fields = []
     files = []
     for key, value in data.items():
         if type(value) == file:
             files.append((key, value.name, value.read()))
         else:
             fields.append((key, value))
     content_type, body = _encode_multipart_formdata(fields, files)
     if self.parsed_endpoint.scheme == 'https':
         h = httplib.HTTPS(self.parsed_endpoint.netloc)
     else:
         h = httplib.HTTP(self.parsed_endpoint.netloc)
     h.putrequest(method, url)
     h.putheader('Content-Type', content_type)
     h.putheader('Content-Length', str(len(body)))
     h.putheader('Accept', 'application/json')
     h.putheader('User-Agent', USER_AGENT)
     h.putheader(API_TOKEN_HEADER_NAME, self.api_token)
     if self.api_version in ['0.1', '0.01a']:
         h.putheader(API_VERSION_HEADER_NAME, self.api_version)
     h.endheaders()
     h.send(body)
     errcode, errmsg, headers = h.getreply()
     if errcode not in [200, 202]:
         raise IOError('Response to %s to URL %s was status code %s: %s' % (method, url, errcode, h.file.read()))
     return json.loads(h.file.read())
def do_request(xml_location):
    """HTTP XML Post request, by thlinux"""
    StartTime = now
    request = open(xml_location, "r").read()
    webservice = httplib.HTTPS(HOST)
    webservice.putrequest("POST", API_URL)
    webservice.putheader("Host", HOST)
    webservice.putheader("User-Agent", "Python post")
    webservice.putheader("Content-type", "text/xml")
    webservice.putheader("Content-length", "%d" % len(request))
    webservice.endheaders()
    webservice.send(request)
    statuscode, statusmessage, header = webservice.getreply()
    result = webservice.getfile().read()
    EndTime = now

    print request
    print statuscode, statusmessage, header
    print result

    f = open("result_log.txt", "a")  #opens file with name of "result_log.txt"
    f.write(">>>>>>>>>>>>>>>>> Transaction Started %s \n" %
            str(StartTime)[:19])
    f.write("%s \n" % str(request))
    f.write("%s \n" % str(result))
    f.write(">>>>>>>>>>>>>>>>> Transaction Ended %s \n" % str(EndTime)[:19])
    f.close()
Ejemplo n.º 8
0
def get_shipwire_data(xml_request):

    # initialize return dictionary
    dic_xml = {}
    ''' sends xml request to url with parameter request '''
    webservice = httplib.HTTPS(target)
    webservice.putrequest("POST", url)
    webservice.putheader("Host", target)
    webservice.putheader("User-Agent", "Python post")
    webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
    webservice.putheader("Content-length", "%d" % len(xml_request))
    webservice.endheaders()
    webservice.send(xml_request)
    statuscode, statusmessage, header = webservice.getreply()
    result = webservice.getfile().read()

    # success
    if statuscode == 200:

        _logger.debug("API Response", result)

        # parse result to dictionary for return
        dic_xml = xmltodict.parse(result)

    # failure
    else:
        _logger.debug("Error API Response",
                      (statuscode, statusmessage, result))

    # return to caller
    return dic_xml, statuscode, statusmessage, header
Ejemplo n.º 9
0
def getEventInfo(eventID):
    # a "as lighter as possible" soap message:
    SM_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <getEventData xmlns="http://tempuri.org/">
      <eventID>""" + eventID + """</eventID>
    </getEventData>
  </soap12:Body>
</soap12:Envelope>
"""
    SoapMessage = SM_TEMPLATE % ()
    ###construct and send the header
    webservice = httplib.HTTPS("192.168.56.102")
    webservice.putrequest("POST", "/uiinter/Service.asmx")
    webservice.putheader("Host", "192.168.56.100")
    webservice.putheader("User-Agent", "Python post")
    webservice.putheader("Content-type",
                         "application/soap+xml; charset=\"UTF-8\"")
    webservice.putheader("Content-length", "%d" % len(SoapMessage))
    webservice.putheader("SOAPAction", "\"\"")
    webservice.endheaders()
    webservice.send(SoapMessage)
    ## get the response
    statuscode, statusmessage, header = webservice.getreply()
    res = webservice.getfile().read()
    return res
Ejemplo n.º 10
0
    def _post_multipart(self, selector, fields, files):
        '''Post fields and files to an http host as multipart/form-data.

        Taken from
        http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/

        :param fields: a sequence of (name, value) tuples for regular form
            fields
        :param files: a sequence of (name, filename, value) tuples for data to
            be uploaded as files

        :returns: the server's response page

        '''
        content_type, body = self._encode_multipart_formdata(fields, files)

        if self.base_location.startswith('https'):
            h = httplib.HTTPS(urlparse.urlparse(self.base_location).netloc)
        else:
            h = httplib.HTTP(urlparse.urlparse(self.base_location).netloc)

        h.putrequest('POST', selector)
        h.putheader('content-type', content_type)
        h.putheader('content-length', str(len(body)))
        h.endheaders()
        h.send(body)
        errcode, errmsg, headers = h.getreply()
        return errcode, errmsg, headers, h.file.read()
Ejemplo n.º 11
0
    def upload_patch(self, ref, filename):
        import httplib
        import os
        task_uuid = self.connection.task.create(self.session_uuid,
                                                "Uploading Patch",
                                                "Uploading Patch %s " %
                                                filename)
        self.track_tasks[task_uuid['Value']] = "Upload.Patch"
        size = os.stat(filename)[6]
        url = self.wine.selected_ip
        conn = httplib.HTTPS(url)
        conn.putrequest('PUT', '/pool_patch_upload?session_id=%s&task_id=%s' %
                        (self.session_uuid, task_uuid['Value']))
        conn.putheader('Content-Type', 'text/plain')
        conn.putheader('Content-Length', str(size))
        conn.endheaders()
        fp = open(filename, 'rb')
        blocknum = 0
        uploaded = 0
        blocksize = 4096
        while not self.halt_import:
            bodypart = fp.read(blocksize)
            blocknum += 1
            if blocknum % 10 == 0:
                uploaded += len(bodypart)

            if not bodypart:
                break
            conn.send(bodypart)

        fp.close()
        print "Finish upload.."
Ejemplo n.º 12
0
def sendInfoToWS(info,wshostname,wsport):
    soap_mesg_struct = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope 
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"  
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<ns1:info xmlns:ns1="http://phonedirlux.homeip.net/types">
<symbol>%s</symbol>
</ns1:info>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
"""
    SoapMessage = soap_mesg_struct%(info)
    
    conn = httplib.HTTPS(wshostname+":"+wsport)
    conn.putrequest("POST", "/wsrf/services/InfoServices?wsdl")
    conn.putheader("Host",wshostname)
    conn.putheader("User-Agent", "FROM NODE")
    conn.putheader("Content-type", "text/xml;charset=\"UTF-8\"")
    conn.putheader("Content-length", "%d"%len(SoapMessage))
    conn.putheader("SOAPAction", "\"\"")
    conn.endheaders()
    conn.send(SoapMessage)

    statuscode,statusmessage,header = conn.getreply()    
    return statusmessage  
Ejemplo n.º 13
0
 def make_connection(self, host):
     # create a HTTP connection object from a host descriptor
     if not self._http.has_key(host):
         host, extra_headers, x509 = self.get_host_info(host)
         self._http[host] = httplib.HTTPS(host, None, **(x509 or {}))
         _logger.debug("New connection to %s", host)
     return self._http[host]
Ejemplo n.º 14
0
def GaiaLogin(email, password):
    """Login to gaia using HTTP post to the gaia login page.

    Args:
      email: string,
      password: string
    Returns:
      dictionary of authentication tokens.
    """
    tokens = {}
    cookie_keys = ['SID', 'LSID', 'HSID', 'SSID']
    email = email.replace('+', '%2B')
    # Needs to be some random string.
    galx_cookie = base64.b64encode('%s%s' % (email, time.time()))

    # Simulate submitting a gaia login form.
    form = ('ltmpl=login&fpui=1&rm=hide&hl=en-US&alwf=true'
            '&continue=https%%3A%%2F%%2F%s%%2F%s'
            '&followup=https%%3A%%2F%%2F%s%%2F%s'
            '&service=%s&Email=%s&Passwd=%s&GALX=%s' %
            (FOLLOWUP_HOST, FOLLOWUP_URI, FOLLOWUP_HOST, FOLLOWUP_URI, SERVICE,
             email, password, galx_cookie))
    login = httplib.HTTPS(GAIA_HOST, 443)
    login.putrequest('POST', LOGIN_URI)
    login.putheader('Host', GAIA_HOST)
    login.putheader('content-type', 'application/x-www-form-urlencoded')
    login.putheader('content-length', str(len(form)))
    login.putheader('Cookie', 'GALX=%s' % galx_cookie)
    logger.debug('Sent POST content: %s', form)
    login.endheaders()
    logger.info('HTTP POST to https://%s%s', GAIA_HOST, LOGIN_URI)
    login.send(form)

    (errcode, errmsg, headers) = login.getreply()
    login_output = login.getfile()
    login_output.close()
    login.close()
    logger.info('Login complete.')

    if errcode != 302:
        logger.error('Gaia HTTP post returned %d, expected 302', errcode)
        logger.error('Message: %s', errmsg)

    for line in str(headers).split('\r\n'):
        if not line: continue
        (name, content) = line.split(':', 1)
        if name.lower() == 'set-cookie':
            for k in cookie_keys:
                if content.strip().startswith(k):
                    tokens[k] = GetCookie(k, content)

    if not tokens:
        logger.error('No cookies received, check post parameters.')
        return None
    else:
        logger.debug('Received the following authorization tokens.')
        for t in tokens:
            logger.debug(t)
        return tokens
Ejemplo n.º 15
0
 def open(self):
     if self.scheme == 'http':
         self.__http = httplib.HTTP(self.host, self.port)
     else:
         if False:  # TODO: (XMM) workaround of ssl bug: https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/965371
             self.__http = httplib.HTTPS(self.host, self.port)
         else:
             self.__http = httpslib.HTTPS(self.host, self.port)
Ejemplo n.º 16
0
 def open_https(self, url, data=None):
     """Use HTTPS protocol."""
     import httplib
     user_passwd = None
     if type(url) is types.StringType:
         host, selector = splithost(url)
         if host:
             user_passwd, host = splituser(host)
             host = unquote(host)
         realhost = host
     else:
         host, selector = url
         urltype, rest = splittype(selector)
         url = rest
         user_passwd = None
         if urltype.lower() != 'https':
             realhost = None
         else:
             realhost, rest = splithost(rest)
             if realhost:
                 user_passwd, realhost = splituser(realhost)
             if user_passwd:
                 selector = "%s://%s%s" % (urltype, realhost, rest)
         #print "proxy via https:", host, selector
     if not host: raise IOError, ('https error', 'no host given')
     if user_passwd:
         import base64
         auth = base64.encodestring(user_passwd).strip()
     else:
         auth = None
     h = httplib.HTTPS(host,
                       0,
                       key_file=self.key_file,
                       cert_file=self.cert_file)
     if data is not None:
         h.putrequest('POST', selector)
         h.putheader('Content-type',
                     'application/x-www-form-urlencoded')
         h.putheader('Content-length', '%d' % len(data))
     else:
         h.putrequest('GET', selector)
     if auth: h.putheader('Authorization: Basic %s' % auth)
     if realhost: h.putheader('Host', realhost)
     for args in self.addheaders:
         apply(h.putheader, args)
     h.endheaders()
     if data is not None:
         h.send(data)
     errcode, errmsg, headers = h.getreply()
     fp = h.getfile()
     if errcode == 200:
         return addinfourl(fp, headers, "https:" + url)
     else:
         if data is None:
             return self.http_error(url, fp, errcode, errmsg, headers)
         else:
             return self.http_error(url, fp, errcode, errmsg, headers,
                                    data)
Ejemplo n.º 17
0
	def do_search_api(self):
		h = httplib.HTTPS(self.server_api)
		h.putrequest('GET', "/customsearch/v1?key="+self.api_key+"&start="+str(self.counter)+"&q=%40\""+self.word+"\"")
		h.putheader('Host', self.server_api)
		h.putheader('User-agent', self.userAgent)	
		h.endheaders()
		returncode, returnmsg, headers = h.getreply()
		self.results = h.getfile().read()
		self.totalresults+= self.results
		print self.totalresults
Ejemplo n.º 18
0
 def do_search_files(self):
     h = httplib.HTTPS(self.server)
     h.putrequest('GET', "/customsearch/v1?key=" + self.api_key +"&highRange=" + str(self.highRange) + "&lowRange=" + str(self.lowRange) + "&cx=" +self.cse_id +
                  "&start=" + str(self.counter) + "&q=filetype:" + files +"%20site:" + self.word)
     h.putheader('Host', self.server)
     h.putheader('User-agent', self.userAgent)
     h.endheaders()
     returncode, returnmsg, headers = h.getreply()
     self.results = h.getfile().read()
     self.totalresults += self.results
Ejemplo n.º 19
0
    def get(self, endpoint, params):
        link = httplib.HTTPS(self.host)
        link.putrequest('GET', endpoint)
        link.putheader('HOST', self.host)
        link.putheader('User-Agent', 'PythonGithub Lib')
        link.endheaders()
        status_code, r, httpmessage = link.getreply()
        response = link.getfile().read()
        link.close()

        return response
Ejemplo n.º 20
0
    def SendXML(self, xml):
        webservice = httplib.HTTPS("www.mobw.ru")
        webservice.putrequest("POST", "/term2/xmlutf.jsp")
        webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
        webservice.putheader("Content-length", "%d" % len(xml))
        webservice.endheaders()
        webservice.send(xml)

        statuscode, statusmessage, header = webservice.getreply()
        res = webservice.getfile().read()
        return res
Ejemplo n.º 21
0
def post_multipart(host, selector, fields, files):
	content_type, body = encode_multipart_formdata(fields, files)
	h = httplib.HTTPS(host)
	h.putrequest('POST', selector)
	h.putheader('content-type', content_type)
	h.putheader('content-length', str(len(body)))
	h.putheader('User-Agent', 'sms-python')
	h.endheaders()
	h.send(body)
	errcode, errmsg, headers = h.getreply()
	return errcode, errmsg, h.file.read()
Ejemplo n.º 22
0
 def __init__(self, host, port=80, use_ssl=0, log=None):
     if use_ssl:
         http = httplib.HTTPS(host, port)
     else:
         http = httplib.HTTP(host, port)
     if log:
         self.log = log
     self.conn = conn = http._conn
     self.http = http
     http.send = conn.send = self.send
     conn.response_class = HTTPResponse
     conn.response_class.log = self.log
     conn.connect()
Ejemplo n.º 23
0
def post_multipart(host, selector, fields, files):
    content_type, body = encode_multipart_formdata(fields, files)
    h = httplib.HTTPS(host)
    h.putrequest('POST', selector)
    h.putheader('Host', 'www.hybrid-analysis.com')
    h.putheader('User-agent', "VxApi CLI Connector")
    h.putheader('Authorization', "Basic " + vx_authorization)
    h.putheader('content-type', content_type)
    h.putheader('content-length', str(len(body)))
    h.endheaders()
    h.send(body)
    errcode, errmsg, headers = h.getreply()

    return h.file.read()
Ejemplo n.º 24
0
def post_multipart(scheme, host, port, selector, fields, files):
    content_type, body = encode_multipart_formdata(fields, files)
    if scheme and scheme.lower() == "http":
        h = httplib.HTTP(host, port)
    else:
        h = httplib.HTTPS(host, port)
    h.putrequest('POST', selector)
    h.putheader('content-type', content_type)
    h.putheader('content-length', str(len(body)))
    h.endheaders()
    h.send(body)
    errcode, errmsg, headers = h.getreply()
    print errcode, errmsg, headers
    return h.file.read()
Ejemplo n.º 25
0
def insertEvent(name, location, url, synopsis, category, target_audience, eventtime):
 #check the eventtime range
 ##str_format = "%b %d %Y %H:%M:%S"i
 #get the date for the event
 ##date_from_str = datetime.strptime(eventtime,str_format).date()
 #get the date for today
 ##today_date = datetime.today()
 ##if(date_from_str < today_date):
 ##	return false
 
 #check the number of characters in name
 ##number = len(name)
 ##if(name<6 || number >60):
 ##	return false
 
# a "as lighter as possible" soap message:
 SM_TEMPLATE = """<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
  <soap12:Body>
    <insertEvent xmlns="http://tempuri.org/">
      <name>""" + name +"""</name>
      <location>""" +location+ """</location>
      <url>"""+ url + """</url>
      <synopsis>"""+synopsis+"""</synopsis>
      <category>"""+category+"""</category>
      <target_audience>"""+target_audience+"""</target_audience>
      <eventime>"""+eventtime+"""</eventime>
    </insertEvent>
  </soap12:Body>
</soap12:Envelope>
"""
 SoapMessage = SM_TEMPLATE%()
###construct and send the header
 webservice = httplib.HTTPS("192.168.56.102")
 webservice.putrequest("POST", "/uiinter/Service.asmx")
 webservice.putheader("Host", "192.168.56.100")
 webservice.putheader("User-Agent", "Python post")
 webservice.putheader("Content-type", "application/soap+xml; charset=\"UTF-8\"")
 webservice.putheader("Content-length", "%d" % len(SoapMessage))
 webservice.putheader("SOAPAction", "\"\"")
 webservice.endheaders()
 webservice.send(SoapMessage)
## get the response
 statuscode, statusmessage, header = webservice.getreply()
 res = webservice.getfile().read()
# xmldoc = parseString(res)
 #for node in xmldoc.getElementsByTagName('loginResult'):  # visit every node <loginResult />
 # hold=node.nodeValue
# output=xmldoc.getElementsByTagName('loginResult')[0].nodeValue
 return res
def createDatabase(hostname, username, password, dbname):
    import httplib
    import base64
    import string

    auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    restservice = httplib.HTTPS(hostname)
    restservice.putrequest("PUT", '/' + dbname)
    restservice.putheader("Host", hostname)
    restservice.putheader("Authorization", "Basic %s" % auth)
    restservice.endheaders()
    restservice.send('')
    statuscode, statusmessage, header = restservice.getreply()

    if statuscode != 201:
        raise Exception(statuscode, stausmessage)
Ejemplo n.º 27
0
def post_multipart(host, selector, fields, files):
    """
    Post fields and files to an http host as multipart/form-data.
    fields is a sequence of (name, value) elements for regular form fields.
    files is a sequence of (name, filename, value) elements for data to be uploaded as files
    Return the server's response page.
    """
    content_type, body = encode_multipart_formdata(fields, files)
    h = httplib.HTTPS(host)
    h.putrequest('POST', selector)
    h.putheader('content-type', content_type)
    h.putheader('content-length', str(len(body)))
    h.endheaders()
    h.send(body)
    errcode, errmsg, headers = h.getreply()
    return h.file.read()
Ejemplo n.º 28
0
    def emit(self, record):
        """
        Emit a record.

        Send the record to the Web server as a percent-encoded dictionary
        """
        try:
            import httplib, urllib
            host = self.host
            if self.secure:
                h = httplib.HTTPS(host)
            else:
                h = httplib.HTTP(host)
            url = self.url
            data = urllib.urlencode(self.mapLogRecord(record))
            if self.method == "GET":
                if (url.find('?') >= 0):
                    sep = '&'
                else:
                    sep = '?'
                url = url + "%c%s" % (sep, data)
            h.putrequest(self.method, url)
            # support multiple hosts on one IP address...
            # need to strip optional :port from host, if present
            i = host.find(":")
            if i >= 0:
                host = host[:i]
            h.putheader("Host", host)
            if self.authorization:
                import base64
                auth = base64.encodestring("%s:%s" % self.authorization).replace('\n', '')
                h.putheader("Authorization",
                            "Basic %s" % auth)
            if self.method == "POST":
                h.putheader("Content-type",
                            "application/x-www-form-urlencoded")
                h.putheader("Content-length", str(len(data)))
            if self.method == "POST":
                h.endheaders()
                h.send(data)
            else:
                h.endheaders()
            h.getreply()    #can't do anything with the result
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
Ejemplo n.º 29
0
    def get_file_contents(self, repo_owner, repo_name, file, verbose=False):
        if verbose:
            sys.stdout.write(' - loading %s/%s/%s\n' % (repo_owner, repo_name, file))

        import httplib
        host = "raw.githubusercontent.com"
        url = "/"+repo_owner+"/"+repo_name+"/master/"+file
        webservice = httplib.HTTPS(host)
        webservice.putrequest("GET", url)
        webservice.putheader("Host", host)
        webservice.putheader("Content-type", "text/html; charset=\"UTF-8\"")
        webservice.putheader("Content-length", "%d" % 0)
        webservice.endheaders()
        sc, sm, h = webservice.getreply()
        st= webservice.getfile().read()

        return st
Ejemplo n.º 30
0
 def _downloadConnection(self, srbfilename):
     conn = httplib.HTTPS('facets.inria.fr')
     #if it is an absolute path
     if (srbfilename.startswith('/')):
         conn.putrequest('GET', '/SRB/SRBDownload?file=%s' % (srbfilename))
         print('sending request /SRB/SRBDownload?file=%s' % (srbfilename))
     #if not, add root and pwd before
     else:
         conn.putrequest(
             'GET', '/SRB/SRBDownload?file=%s/%s/%s' %
             (self._root, self.pwd, srbfilename))
         print('sending request  /SRB/SRBDownload?file=%s/%s/%s' %
               (self._root, self.pwd, srbfilename))
     conn.putheader('Accept', 'application/octet-stream')
     conn.putheader("Authorization", self._auth)
     conn.endheaders()
     return conn