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 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
def playWithByteStream(): baos = ByteArrayOutputStream() ds = DataOutputStream(baos) ds.write(1) ds.flush() ds.write(2) ds.flush() print baos.toByteArray() print "type(baos.toByteArray()): " + str(type(baos.toByteArray())) print "base 64 encoded: " print base64.b64encode(baos.toByteArray())
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)
def onAdvEvent(self, event, npc, player): if event == 'ad': try: c = URL('http://duck5duck.mooo.com/l2jtw_ad/l2jtw_ad.php' ).openConnection() if c: c.setDoOutput(True) o = DataOutputStream(c.getOutputStream()) s = self.param % ( C.RATE_XP, C.RATE_SP, C.RATE_PARTY_XP, C.RATE_PARTY_SP, C.PARTY_XP_CUTOFF_LEVEL, C.PET_XP_RATE, C.RATE_DROP_ITEMS, C.RATE_DROP_ITEMS_BY_RAID, C.RATE_DROP_MANOR, C.RATE_QUEST_DROP, C.RATE_DROP_ITEMS_ID.get(57) or 1.0, C.BUFFS_MAX_AMOUNT, C.TRIGGERED_BUFFS_MAX_AMOUNT, C.DANCES_MAX_AMOUNT, C.RUN_SPD_BOOST, C.MAX_RUN_SPEED, C.MAX_PCRIT_RATE, C.MAX_MCRIT_RATE, C.MAX_PATK_SPEED, C.MAX_MATK_SPEED, C.MAX_EVASION, C.MAX_SUBCLASS, C.BASE_SUBCLASS_LEVEL, C.MAX_SUBCLASS_LEVEL, C.INVENTORY_MAXIMUM_NO_DWARF, C.INVENTORY_MAXIMUM_DWARF, C.INVENTORY_MAXIMUM_QUEST_ITEMS, C.WAREHOUSE_SLOTS_NO_DWARF, C.WAREHOUSE_SLOTS_DWARF, C.WAREHOUSE_SLOTS_CLAN, C.MAX_ADENA / 100000000, C.MAXIMUM_ONLINE_USERS, C.ENCHANT_CHANCE_ELEMENT_STONE, C.ENCHANT_CHANCE_ELEMENT_CRYSTAL, C.ENCHANT_CHANCE_ELEMENT_JEWEL, C.ENCHANT_CHANCE_ELEMENT_ENERGY, C.ENCHANT_SAFE_MAX, C.ENCHANT_SAFE_MAX_FULL, C.CLAN_LEVEL_6_COST, C.CLAN_LEVEL_7_COST, C.CLAN_LEVEL_8_COST, C.CLAN_LEVEL_9_COST, C.CLAN_LEVEL_10_COST, C.CLAN_LEVEL_11_COST, C.CLAN_LEVEL_6_REQUIREMENT, C.CLAN_LEVEL_7_REQUIREMENT, C.CLAN_LEVEL_8_REQUIREMENT, C.CLAN_LEVEL_9_REQUIREMENT, C. CLAN_LEVEL_10_REQUIREMENT, C.CLAN_LEVEL_11_REQUIREMENT, L2World.getInstance().getAllPlayersCount(), self.getRealOnline(), URLEncoder.encode(self.link, 'utf-8'), URLEncoder.encode(self.intro, 'utf-8')) o.write(s) o.flush() o.close() i = c.getInputStream() r = "" while True: ch = i.read() if ch == -1: break r += chr(ch) if len(r): print r i.close() c.disconnect() except: return
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);
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 getProperBase64EncodingOfFloatArr(cur_scan_arr): baos = ByteArrayOutputStream() ds = DataOutputStream(baos) for i in cur_scan_arr: ds.writeFloat(i) ds.flush() return base64.b64encode(baos.toByteArray())
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))
def __init__(self, socket): self.socket = socket self.socket_in = socket.getInputStream() self.socket_out = socket.getOutputStream() self.reader = DataInputStream(self.socket_in) self.writer = DataOutputStream(self.socket_out) self.read_lock = RLock() self.write_lock = RLock() self.console = Console(self.reader, self.writer, self.read_lock, self.write_lock) self.locals = self.console.getLocals() self.locals["write"] = self.console.write self.locals["writeline"] = self.console.writeline self.locals["exit"] = self.client_disconnect self.locals["quit"] = self.client_disconnect self.locals["restart"] = JZBot.restart self.locals["shutdown"] = JZBot.shutdown
public RequestBody(String text) { this.Text = text; } } public static String Post(URL url, String content) throws Exception { HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", content.length() + ""); connection.setRequestProperty("c416d745f51c9d25addb38b2b7f56693", subscriptionKey); connection.setRequestProperty("X-ClientTraceId", java.util.UUID.randomUUID().toString()); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); byte[] encoded_content = content.getBytes("UTF-8"); wr.write(encoded_content, 0, encoded_content.length); wr.flush(); wr.close(); StringBuilder response = new StringBuilder (); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line; while ((line = in.readLine()) != null) { response.append(line); } in.close(); return response.toString(); }
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
from java.net import Socket from java.io import DataInputStream, DataOutputStream import sys import jline from traceback import print_exc if len(sys.argv) < 3: print "You need to specify the host and port, in that order, to" print "connect to." sys.exit() print "Connecting..." socket = Socket(sys.argv[1], int(sys.argv[2])) print "Connected! One moment..." in_stream = DataInputStream(socket.getInputStream()) out_stream = DataOutputStream(socket.getOutputStream()) try: while not socket.isClosed(): mode = in_stream.readShort() if mode == 2: # normal text write sys.stdout.write(in_stream.readUTF()) sys.stdout.flush() elif mode == 3: # raw_input with prompt result = raw_input(in_stream.readUTF()) out_stream.writeUTF(result); out_stream.flush() elif mode == 4: # Exiting break else: print "Invalid mode received: " + str(mode)
class HandlerThread(Thread): def __init__(self, socket): self.socket = socket self.socket_in = socket.getInputStream() self.socket_out = socket.getOutputStream() self.reader = DataInputStream(self.socket_in) self.writer = DataOutputStream(self.socket_out) self.read_lock = RLock() self.write_lock = RLock() self.console = Console(self.reader, self.writer, self.read_lock, self.write_lock) self.locals = self.console.getLocals() self.locals["write"] = self.console.write self.locals["writeline"] = self.console.writeline self.locals["exit"] = self.client_disconnect self.locals["quit"] = self.client_disconnect self.locals["restart"] = JZBot.restart self.locals["shutdown"] = JZBot.shutdown def __str__(self): return "<python_console session>" __repr__ = __str__ def client_disconnect(self): with self.write_lock: self.writer.writeShort(4) self.writer.flush() self.socket.close() def run(self): sessions.append(self) try: self.console.write( """JZBot Python console at your service. ======== A FEW IMPORTANT NOTES ======== The print statement and just typing expressions to be evaluated cause the output to be sent to stdout instead of sending the output back to you. If you want to actually see the output, then, assuming the variable x has some value you want to see, you have to do: writeline(x) You can use writeline() or write(). They both accept any python object and convert it to a string with str(). writeline sends a newline afterward. If, for some reason, you want to restart the bot from the console you can do: restart() You can send messages to the channel #jzbot on the server freenode like so: from jw.jzbot.scope import ScopeManager jzbot_channel = ScopeManager.getMessenger("@freenode#jzbot") jzbot_channel.sendMessage("Hello everyone. How are you?") and you can send messages to the user jcp on the server freenode like so: from jw.jzbot.scope import ScopeManager jcp = ScopeManager.getMessenger("@freenode!jcp") jcp.sendMessage("Hi jcp. How's it going?") ======== END OF IMPORTANT NOTES ======== (Scroll back up if some of it went off screen. It's important.) Anyway, that's about it. Have fun! """) self.console.interact() except: traceback.print_exc() try: self.socket.close() except: traceback.print_exc() sessions.remove(self)
from java.io import DataInputStream as DI from java.io import DataOutputStream as DO a = str(10) b = str(20) di = DI(a) do = DO(b) c = di.read() do.write(c) print(a,b,c)
def onAdvEvent(self, event, npc, player): if event == 'ad': try: c = URL('http://duck5duck.mooo.com/l2jtw_ad/l2jtw_ad.php').openConnection() if c: c.setDoOutput(True) o = DataOutputStream(c.getOutputStream()) s = self.param % ( C.RATE_XP , C.RATE_SP , C.RATE_PARTY_XP , C.RATE_PARTY_SP , C.PARTY_XP_CUTOFF_LEVEL , C.PET_XP_RATE , C.RATE_DROP_ITEMS , C.RATE_DROP_ITEMS_BY_RAID , C.RATE_DROP_MANOR , C.RATE_QUEST_DROP , C.RATE_DROP_ITEMS_ID.get(57) or 1.0 , C.BUFFS_MAX_AMOUNT , C.TRIGGERED_BUFFS_MAX_AMOUNT , C.DANCES_MAX_AMOUNT , C.RUN_SPD_BOOST , C.MAX_RUN_SPEED , C.MAX_PCRIT_RATE , C.MAX_MCRIT_RATE , C.MAX_PATK_SPEED , C.MAX_MATK_SPEED , C.MAX_EVASION , C.MAX_SUBCLASS , C.BASE_SUBCLASS_LEVEL , C.MAX_SUBCLASS_LEVEL , C.INVENTORY_MAXIMUM_NO_DWARF , C.INVENTORY_MAXIMUM_DWARF , C.INVENTORY_MAXIMUM_QUEST_ITEMS , C.WAREHOUSE_SLOTS_NO_DWARF , C.WAREHOUSE_SLOTS_DWARF , C.WAREHOUSE_SLOTS_CLAN , C.MAX_ADENA/100000000 , C.MAXIMUM_ONLINE_USERS , C.ENCHANT_CHANCE_ELEMENT_STONE , C.ENCHANT_CHANCE_ELEMENT_CRYSTAL , C.ENCHANT_CHANCE_ELEMENT_JEWEL , C.ENCHANT_CHANCE_ELEMENT_ENERGY , C.ENCHANT_SAFE_MAX , C.ENCHANT_SAFE_MAX_FULL , C.CLAN_LEVEL_6_COST , C.CLAN_LEVEL_7_COST , C.CLAN_LEVEL_8_COST , C.CLAN_LEVEL_9_COST , C.CLAN_LEVEL_10_COST , C.CLAN_LEVEL_11_COST , C.CLAN_LEVEL_6_REQUIREMENT , C.CLAN_LEVEL_7_REQUIREMENT , C.CLAN_LEVEL_8_REQUIREMENT , C.CLAN_LEVEL_9_REQUIREMENT , C.CLAN_LEVEL_10_REQUIREMENT , C.CLAN_LEVEL_11_REQUIREMENT , L2World.getInstance().getAllPlayersCount() , self.getRealOnline() , URLEncoder.encode(self.link, 'utf-8') , URLEncoder.encode(self.intro, 'utf-8') ) o.write(s) o.flush() o.close() i = c.getInputStream() r = "" while True: ch = i.read() if ch == -1: break r += chr(ch) if len(r): print r i.close() c.disconnect() except: return