def post(targetURL, params, contentType="text/xml", username=None):
    
    if(type(params) is dict):
        paramStr = ""
        for aKey in params.keys():
            paramStr+=aKey+"="+URLEncoder.encode(params[aKey], "UTF-8")+"&"
        paramStr=paramStr[:-1]
    else:
        paramStr = params
        
    url = URL(targetURL)
    print targetURL
    print paramStr
    print contentType
    connection = url.openConnection()
    if username!=None:    
        userpass = username
        basicAuth = "Basic " + base64.b64encode(userpass);
        connection.setRequestProperty ("Authorization", basicAuth);
    connection.setRequestMethod("POST")
    if contentType != None:
        connection.setRequestProperty("Content-Type", contentType)
    connection.setRequestProperty("Content-Length", str(len(paramStr)))
    connection.setRequestProperty("Content-Language", "en-GB")
    connection.setUseCaches(0)
    connection.setDoInput(1)
    connection.setDoOutput(2)
    
    wr= DataOutputStream(connection.getOutputStream())
    wr.writeBytes(paramStr)
    wr.flush()
    wr.close()
    return getResponse(connection);
Beispiel #2
0
def runJob(cmdArray, hosts, sleepTime=60, maxWaits=60, interimResult=None):
    finished = HashSet()
    failures = HashSet()
    pb = ProcessBuilder(cmdArray)
    done = False
    # first wait is short in case job finishes quickly
    waitTime = 10
    while not done:
        p = pb.start()
        dataOut = DataOutputStream(p.getOutputStream())
        try:
            for host in hosts:
                dataOut.writeBytes(host + "\n")
        finally:
            dataOut.close()
        p.waitFor()
        (curFinished, curFailures) = processJobResults(p.getInputStream(), interimResult)
        finished.addAll(curFinished)
        failures.addAll(curFailures)
        done = finished.size() == len(hosts)

        if not done:
            maxWaits = maxWaits - 1
            done == maxWaits == 0

        if not done:
            time.sleep(waitTime)
            waitTime = sleepTime
    return failures
def post(targetURL, params, contentType="text/xml", username=None):

    if (type(params) is dict):
        paramStr = ""
        for aKey in params.keys():
            paramStr += aKey + "=" + URLEncoder.encode(params[aKey],
                                                       "UTF-8") + "&"
        paramStr = paramStr[:-1]
    else:
        paramStr = params

    url = URL(targetURL)
    print targetURL
    print paramStr
    print contentType
    connection = url.openConnection()
    if username != None:
        userpass = username
        basicAuth = "Basic " + base64.b64encode(userpass)
        connection.setRequestProperty("Authorization", basicAuth)
    connection.setRequestMethod("POST")
    if contentType != None:
        connection.setRequestProperty("Content-Type", contentType)
    connection.setRequestProperty("Content-Length", str(len(paramStr)))
    connection.setRequestProperty("Content-Language", "en-GB")
    connection.setUseCaches(0)
    connection.setDoInput(1)
    connection.setDoOutput(2)

    wr = DataOutputStream(connection.getOutputStream())
    wr.writeBytes(paramStr)
    wr.flush()
    wr.close()
    return getResponse(connection)
Beispiel #4
0
 def sendResponseBody(self):
     """
     Send the previously specified request body.
     
     """
     os = DataOutputStream(self.__native_req.getResponseBody())
     os.writeBytes(self.__response_body)
     os.flush()
     os.close()
 def testEncryptedPassword(self):
     credential_string = 'AES}0vlIcO+I+VWV9aQ1wzQUa1qtByh4D9d0I1dJHa7HsdE='
     try:
         bos = ByteArrayOutputStream()
         dos = DataOutputStream(bos)
         dos.writeBytes(credential_string)
         byte_array = bos.toByteArray()
         dos.close()
     except IOException, ioe:
         self.fail('Unexpected exception writing out credential : ',
                   str(ioe))
Beispiel #6
0
def doService(httpMethod, url, credential, requestBody=None):
    
    Security.addProvider(MySSLProvider())
    Security.setProperty("ssl.TrustManagerFactory.algorithm", "TrustAllCertificates")
    HttpsURLConnection.setDefaultHostnameVerifier(MyHostnameVerifier())
    
    urlObj = URL(url)
    con = urlObj.openConnection()
    con.setRequestProperty("Accept", "application/xml")
    con.setRequestProperty("Content-Type", "application/xml")
    con.setRequestProperty("Authorization", credential)
    con.setDoInput(True);
    
    if httpMethod == 'POST':
        con.setDoOutput(True)
        con.setRequestMethod(httpMethod)
        output = DataOutputStream(con.getOutputStream()); 
        if requestBody:
            output.writeBytes(requestBody); 
        output.close();
        
    responseCode = con.getResponseCode()
    logger.info('response code: ' + str(responseCode))
    responseMessage = con.getResponseMessage()
    logger.info('response message: ' + str(responseMessage))
    contentLength = con.getHeaderField('Content-Length')
    logger.info('content length: ' + str(contentLength))        
    
    stream = None
    if responseCode == 200 or responseCode == 201 or responseCode == 202:
        stream = con.getInputStream()
    elif contentLength:
        stream = con.getErrorStream()
        
    if stream:
        dataString = getStreamData(stream)
        logger.info(httpMethod + ' url: ' + url)
        if not url.endswith('.xsd') and len(dataString) < 4096: 
            xmlStr = Util.prettfyXmlByString(dataString)
            logger.info(httpMethod + ' result: \n\n' + xmlStr)
        else:
            logger.info('response body too big, no print out')
        if responseCode == 200 or responseCode == 201 or responseCode == 202:
            return dataString
        else:
            ''' to mark the case failed if response code is not 200-202 '''
            return None
    else:
        logger.error('')
        logger.error('---------------------------------------------------------------------------------------------------')
        logger.error('-------->>>  Input or Error stream is None, it may be a defect if it is positive test case')
        logger.error('---------------------------------------------------------------------------------------------------')
        logger.error('')
        return None
Beispiel #7
0
def getSSHEnv(connection):
    """ Get the environment variables of an ssh remote server """
    print "Getting Environment Variables ..."
    '''
    sess = connection.openSession()
    sess.requestDumbPTY()
    sess.startShell()
    instr = StreamGobbler(sess.getStdout())
    stdin = BufferedReader(InputStreamReader(instr))
    # get the login shell information.
    #stdin.readLine()    # just delay it so as to be synchronized
    #stdin.readLine()    # just delay it so as to be synchronized
    while(1):
      c = stdin.read()
      if chr(c) == "]":
        c = stdin.read()
        if chr(c) == "$":
          break
    stdin.read()
    out = DataOutputStream(sess.getStdin())
    out.writeBytes("printenv\n")
    input = []
    flag = 0
    line = ""
    while 1:
      c = stdin.read()
      if chr(c) == "\n":
        input.append(line)
        line = ""
      else:
        line = line + chr(c);

      if chr(c) == "]":
        c = stdin.read()
        if chr(c) == "$":
          break
    environ = "".join(input)
    env = re.findall('(\S+)=(\S+)',environ)
    instr.close()
    out.close();
    out = None
    instr = None
    stdin = None
    sess.close()
    sess = None
    return env
    '''

    sess = connection.openSession()
    sess.requestDumbPTY()
    sess.startShell()
    instr = StreamGobbler(sess.getStdout())
    stdin = BufferedReader(InputStreamReader(instr))

    #wait
    while 1==1:
      c = stdin.read() # read the rest bytes before issueing cmd
      if chr(c) == "]":
        c = stdin.read()
        if chr(c) == "$":
          break

    out = DataOutputStream(sess.getStdin())
    #issue the command plus echo something(FINISH) to know when to unblock
    out.writeBytes("printenv && echo FINISH\n")
    input = []
    flag = 0
    while 1:
        line = stdin.readLine()
        if line is None:
            break
        line = line + "\n"
        input.append(line)
        if line.endswith("FINISH\n"):
            if flag == 1:
                break
            else:
                flag +=1
    environ = "".join(input)
    env = re.findall('(\S+)=(\S+)\n',environ)
    instr.close()
    instr = None
    stdin = None
    sess.close()
    sess = None
    return env