def main(): global Conn Conn = Connection(7890, '10.183.1.16', "reader") Conn.s = socket.socket() Conn.s.connect((Conn.host, Conn.port)) Thread(target=listen).start() Thread(target=printMessage).start()
def testSendMail2(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) a = {'foo':'Company secretary', 'bar':42} res = c.post('/bin/sendmail', to='pauline.toy', subject="test", content=a) print(res)
def main(): p = None if len(sys.argv) == 2: binary = sys.argv[-1] p = subprocess.Popen(binary, stdout=devnull) print "Started process", p.pid time.sleep(1) port = int(open("hyrise_server.port").readlines()[0]) assert port != 0 try: test_urls(port) c = Connection(port=port) test_tx(c) test_sockets(port, p.pid) test_perf_flag(port) send_query_and_terminate_before_response(port) time.sleep(2) send_query_and_terminate_before_response(port) subprocess.check_output( ["curl", "-s", "localhost:{0}/shutdown/".format(port)]) c.close() print "=====> No errors <=====" except Exception, e: if p: print "Error'd out: Terminating..." p.terminate() raise
def testSendMail2(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) a = {'foo': 'Company secretary', 'bar': 42} res = c.post('/bin/sendmail', to='pauline.toy', subject="test", content=a) print(res)
class ClientTest(unittest.TestCase): # setup def setUp(self): self.patcher = patch('client.Connection.get_data', fake_get_data) self.patcher.start() self.client = Connection('test_token') # teardown def tearDown(self): self.patcher.stop() # tests # successful response test def test_request_success(self): api_name = 'test_api_name' url = 'test_url' response = self.client.get_data(api_name, url, 'success') self.assertIn('code', response) self.assertEqual(response['code'], 200) print('client.py request success test') # Unsuccessful response test def test_request_fail(self): api_name = 'test_api_name' url = 'test_url' response = self.client.get_data(api_name, url, 'failure') self.assertIn('code', response) self.assertEqual(response['code'], 404) print('client.py request failure test')
def main(): p = None if len(sys.argv) == 2: binary = sys.argv[-1] p = subprocess.Popen(binary, stdout=devnull) print "Started process", p.pid time.sleep(1) port = int(open("hyrise_server.port").readlines()[0]) assert port != 0 try: test_urls(port) c = Connection(port=port) test_tx(c) test_sockets(port, p.pid) test_perf_flag(port) send_query_and_terminate_before_response(port) time.sleep(2) send_query_and_terminate_before_response(port) subprocess.check_output(["curl", "-s", "localhost:{0}/shutdown/".format(port)]) c.close() print "=====> No errors <=====" except Exception, e: if p: print "Error'd out: Terminating..." p.terminate() raise
def run(self): print("Server up and Running") while True: c, a = self.sock.accept() print(c, a) print('run') connection = Connection() connection.addClient(c, a)
def testVraiLogin(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) res = c.get('/home/gritchie') print(res) res = c.get('/home/gritchie/INBOX') print(res) res = c.get('/home/gritchie/INBOX/580') print(res)
def test_sockets(port, pid): i = get_num_sockets(pid) c = Connection(port=port) test_tx(c) assert i + 1 == get_num_sockets(pid) c2 = Connection(port=port) test_tx(c2) assert i + 2 == get_num_sockets(pid) c.close() c2.close()
def main(): # clear test log dir logdir = "./test/log" if (os.path.exists(logdir)): shutil.rmtree(logdir) os.mkdir(logdir) # recreate dummy file open(logdir + "/dummy", 'a').close() p = None if len(sys.argv) == 2: binary = sys.argv[-1] myenv = os.environ.copy() myenv["HYRISE_DB_PATH"] = os.getcwd() + "/test/" p = subprocess.Popen([binary, "--port=0"], env=myenv, stdout=devnull) print "Started process", p.pid time.sleep(1) port = int(open("hyrise_server.port").readlines()[0]) assert port != 0 try: test_urls(port) c = Connection(port=port) test_tx(c) test_sockets(port, p.pid) test_perf_flag(port) send_query_and_terminate_before_response(port) time.sleep(2) send_query_and_terminate_before_response(port) subprocess.check_output( ["curl", "-s", "localhost:{0}/shutdown/".format(port)]) c.close() print "=====> No errors <=====" except Exception, e: if p: print "Error'd out: Terminating..." p.terminate() raise
def main(): # clear test log dir logdir = "./test/log" if (os.path.exists(logdir)): shutil.rmtree(logdir) os.mkdir(logdir) # recreate dummy file open(logdir+"/dummy", 'a').close() p = None if len(sys.argv) == 2: binary = sys.argv[-1] myenv = os.environ.copy() myenv["HYRISE_DB_PATH"] = os.getcwd() + "/test/" p = subprocess.Popen([binary, "--port=0"], env=myenv, stdout=devnull) print "Started process", p.pid time.sleep(1) port = int(open("hyrise_server.port").readlines()[0]) assert port != 0 try: test_urls(port) c = Connection(port=port) test_tx(c) test_sockets(port, p.pid) test_perf_flag(port) send_query_and_terminate_before_response(port) time.sleep(2) send_query_and_terminate_before_response(port) subprocess.check_output(["curl", "-s", "localhost:{0}/shutdown/".format(port)]) c.close() print "=====> No errors <=====" except Exception, e: if p: print "Error'd out: Terminating..." p.terminate() raise
def main(): global Conn Conn = Connection(7890, "10.183.1.16", "main_server") #Socket S1 is socket for client prompt (tcp) #Message recieving socket global s1 s1 = socket.socket() s1.bind((Conn.host, Conn.port)) print s1 #Socket S2 is socket for client reader (udp) #Message Sending socket global s2 s2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s2.bind((Conn.host, Conn.port)) Thread(target = mlisten).start() Thread(target = clisten).start()
def testFile1(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) res = c.get('/home/guest/NASA-SETI.bin') print(res)
def __init__(self): self.connection = Connection("http://pac.fil.cool/uglix") self.itsTarget = None self.user = '******' self.password = '******'
def helpDesk3(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) res = c.get('/bin/crypto_helpdesk/ticket/43/attachment/fetch-me') print(res)
def testMailUnread(): c = Connection("http://pac.fil.cool/uglix") c.post('/bin/login', user='******', password="******") res = c.get('/home/guest/INBOX/unread') print(res)
def testFile2(): c = Connection("http://pac.fil.cool/uglix") c.post('/bin/login', user='******', password="******") res = c.get('/home/guest/soundtrack_0.s3m') print(res)
def testlogin(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res)
#!/bin/env python2 from client import Connection c = Connection() response = c.stored_procedure( "TPCC-NewOrder", """{ "W_ID": 1, "D_ID": 1, "C_ID": 1, "O_CARRIER_ID": 5, "OL_DIST_INFO": "lalala", "items": [{"I_ID":1 , "I_W_ID": 1, "quantity": 1}, {"I_ID":2 , "I_W_ID": 1, "quantity": 1}, {"I_ID":7 , "I_W_ID": 1, "quantity": 1}, {"I_ID":11, "I_W_ID": 1, "quantity": 1}, {"I_ID":3 , "I_W_ID": 1, "quantity": 1}]}""" ) print response
from client import Connection _printer = lambda x: print(x) if __name__ == '__main__': # Creates a connection to the broker conn = Connection('newavalon.cs.rit.edu') # Create a queue with id "sample_queue" in the # "default" exchange. conn.create_queue('sample_queue') # Subscribe to incoming messages on the queue # Supply the _printer function defined earlier as a callback # which is used to print incoming messages. conn.subscribe("sample_queue", _printer) # Publish a message to the queue conn.publish('sample_queue', "Hello World") flag = True while (flag): # Continue the chat cmd = input("Enter a message you want to be sent.. ") if cmd == 'q': flag = False else: conn.publish('sample_queue', cmd)
def helpDesk(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) res = c.get('/bin/crypto_helpdesk') print(res)
def testecho1(): c = Connection("http://pac.fil.cool/uglix") res = c.get('/bin/echo') print(res)
def testSendMail(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) res = c.post('/bin/sendmail', to='guest', subject="test", content="coucou") print(res)
def testecho2(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/echo', string_example="toto") print(res)
#!/bin/env python2 from client import Connection c = Connection() response = c.stored_procedure("TPCC-StockLevel", """{ "W_ID": 1, "D_ID": 1, "threshold": 15 }""") print response
def helpDeskCloseTicket(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) res = c.post('/bin/crypto_helpdesk/ticket/43/close', confirm=True) print(res)
def testFile1(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print (res) res = c.get('/home/guest/NASA-SETI.bin') print(res)
def testMail2(): c = Connection("http://pac.fil.cool/uglix") res = c.post('/bin/login', user='******', password="******") print(res) res = c.get('/home/gritchie/INBOX/3714') # on peut mtn fermer le ticket print(res)
print(type(xorABZ)) clair = xorABZ.decode('latin-1') print(clair) print("\n********************\n") elif ans2=="22": numTicket = input("Numéro du ticket? ") res = c.post('/bin/police_hq/ticket/' + str(numTicket) + '/close', confirm=True) print(res) elif ans2 !="": print("\n Not Valid Choice Try again") if __name__ == '__main__': c = Connection("http://pac.fil.cool/uglix") while True: print (""" 2.Connect en CHAP """) ans=input("What would you like to do? ") if ans =="2": login = input("Login: "******"MDP: ") dictio = c.get('/bin/login/CHAP') challenge = dictio.get("challenge") plaintext = login + "-" + challenge reponse = encrypt(plaintext, mdp) res = c.post('/bin/login/CHAP', user=login, response=reponse) print(res)
class Helper: def __init__(self): self.connection = Connection("http://pac.fil.cool/uglix") self.itsTarget = None self.user = '******' self.password = '******' def connectionTest(self): print(self.connection.get("/")) def sessionStart(self, target): if target == "guest": print(self.connection.post('/bin/login', user = "******", password = "******")) self.itsTarget = target elif target == "tunderwood": print(self.connection.post('/bin/login', user = '******', password = '******')) self.itsTarget = target else: print("Unknown target. Check your username.\n") def chapGetChallenge(self): data = self.connection.get("/bin/login/CHAP") return (data['challenge']) def chapGetPlainText(self): username = self.user challenge = self.chapGetChallenge() plainText = username + '-' + challenge return (plainText) def chapBuildChallengeResponse(self): plainText = self.chapGetPlainText() cryptedPlainText = encrypt(plainText, self.password) return (cryptedPlainText) def chapConnect(self): challengeResponse = self.chapBuildChallengeResponse() print(self.connection.post("/bin/login/CHAP", user = self.user, response = challengeResponse)) self.itsTarget = self.user def souleymaneConnect(self): challenge = self.connection.get('/bin/login/CHAP') return self.connection.post('/bin/login/CHAP', user=self.user, response=encrypt(self.user + '-' + challenge['challenge'], self.password)) def echo(self): kwds = {'name':'toto', 'age':'42'} print(self.connection.post('/bin/echo', **kwds)) def fileGetContent(self, filename): file = open(filename, 'r') content = file.read() file.close() return (content) def mailList(self): print(self.connection.get("/home/" + self.itsTarget + "/INBOX")) def mailDisplay(self, number): print(self.connection.get("/home/" + self.itsTarget + "/INBOX/" + number)) def mailBodyDisplay(self, number): print(self.connection.get("/home/" + self.itsTarget + "/INBOX/" + number + "/body")) def mailBodyGet(self, number): return self.connection.get("/home/" + self.itsTarget + "/INBOX/" + number + "/body") def mailBodySave(self, number): body = self.connection.get("/home/" + self.itsTarget + "/INBOX/" + number + "/body") file = open('mail-body', 'w') file.write(body) file.close() def mailSend(self, recipient, subjectText, contentText): kwds = {'to': recipient, 'subject': subjectText, 'content': contentText} print(self.connection.post('/bin/sendmail', **kwds)) def home(self): print(self.connection.get("/home/")) def helpdeskConnect(self): print(self.connection.get("/bin/crypto_helpdesk")) def ticketDisplay(self, number): print(self.connection.get("/bin/crypto_helpdesk/ticket/" + number)) def ticketDisplayAttachment(self, number, filename): print(self.connection.get("/bin/crypto_helpdesk/ticket/" + number + "/attachment/" + filename)) def ticketDownloadAttachment(self, number, filename): file = open(filename, 'w') content = self.connection.get("/bin/crypto_helpdesk/ticket/" + number + "/attachment/" + filename) file.write(content) file.close() def ticketClose(self, ticketId): print(self.connection.post("/bin/crypto_helpdesk/ticket/" + ticketId + "/close", confirm=True)) def ticketReopen(self, ticketId): print(self.connection.get("/bin/crypto_helpdesk/ticket/" + ticketId + "/reopen")) def ticketListOpened(self): print(self.connection.get("/bin/crypto_helpdesk/opened")) def ticketListClosed(self): print(self.connection.get("/bin/crypto_helpdesk/closed")) def ticketTitle(self, ticketId): print(self.connection.get("/bin/crypto_helpdesk/" + ticketId + "/title")) def keyManagerGetInfo(self, user): print(self.connection.get("/bin/key-management/" + user)) def keyManagerDownloadPublicKey(self, user): public_key = self.connection.get("/bin/key-management/" + user + "/pk") file = open('public-key', 'w') file.write(public_key) file.close() def keyManagerUploadPublicKey(self, pk): print(self.connection.post("/bin/key-management/upload-pk", public_key = pk)) def keyManagerUploadPublicKeyForce(self, pk): print(self.connection.post("/bin/key-management/upload-pk", public_key = pk, confirm = True))
#!/bin/env python2 from client import Connection c = Connection() response = c.stored_procedure("TPCC-StockLevel", """{ "W_ID": 1, "D_ID": 1, "threshold": 35 }""") print response
class TestRPCServer(RPCServer): def RPC_add(self, a, b): return a + b def RPC_sleep(self, seconds): gevent.sleep(seconds) if __name__ == "__main__": s = TestRPCServer(7000) s.dumps = dumps s.loads = loads s.start() c = Connection(("127.0.0.1", 7000), dumps, loads) print c.RPC_sleep(3) c.reconnect() # Connection 是短连接,必须主动重连才能继续利用 connection print c.RPC_add(2, 3) args = (("127.0.0.1", 7000), dumps, loads) p = Pool(args, 6) def f1(): print "1", p.RPC_echo("123") def f2(): print "2", p.RPC_sleep(3) # # Pool 是长连接,不需要重连 f2() f1() # gevent.spawn(f1)
#!/bin/env python2 from client import Connection c = Connection() #response = c.stored_procedure("TPCC-Payment", """{ "W_ID": 1, "D_ID": 1, "C_W_ID": 1, "C_D_ID": 1, "H_AMOUNT": 150.0, "C_ID": 1 }""") #print response d = Connection() response = d.stored_procedure("TPCC-Payment", """{ "W_ID": 1, "D_ID": 1, "C_W_ID": 1, "C_D_ID": 1, "H_AMOUNT": 150.0, "C_LAST": "CLName2" }""") print response
def setUp(self): self.patcher = patch('client.Connection.get_data', fake_get_data) self.patcher.start() self.client = Connection('test_token')
from client import Connection c = Connection("http://pac.fil.cool/uglix") #print(c.post("/bin/login", user="******", password="******")) print(c.get("/home/guest/INBOX"))
#!/bin/env python2 from client import Connection c = Connection() response = c.stored_procedure( "TPCC-Payment", """{ "W_ID": 1, "D_ID": 1, "C_W_ID": 1, "C_D_ID": 1, "H_AMOUNT": 150.0, "C_ID": 1 }""" ) print response d = Connection() response = d.stored_procedure( "TPCC-Payment", """{ "W_ID": 1, "D_ID": 1, "C_W_ID": 1, "C_D_ID": 1, "H_AMOUNT": 150.0, "C_LAST": "CLName2" }""" ) print response
def main(token, country_id=None): # instantiate Connection class api_connection = Connection(token) user = api_connection.get_data('user', user_url) # check if there is an issue with user call and return response if user['code'] != 200: return user # get default user group from user api call and generate group url user_default_group = user['response']['default_group_guid'] group = api_connection.get_data('group', group_url.format(user_default_group)) # get default user group from user api call and generate group url user_default_group = user['response']['default_group_guid'] # user proper pagination parameters to get all the links for the default group pagination_parm = {'page': '1'} link_pages = [] while True: group_data = api_connection.get_data( 'group', group_url.format(user_default_group), params=pagination_parm) if group_data['code'] != 200: return group_data current_page = int(group_data['response']['pagination']['page']) link_pages.append(group_data['response']['links']) if not group_data['response']['pagination']['next']: break else: current_page += 1 pagination_parm = {'page': str(current_page)} # each page result is stored in in a list - "link_pages". code below unpacks and stores individual link ids to new list default_group_links = [link['id'] for page in link_pages for link in page] # list object stores clicks for each link and country country_clicks = [] # as per requirements, only clicks for the last 30 days should be considered timeframe = {'unit': 'day', 'units': '30'} # each iteration of loop returns clicks for every country for link in default_group_links: # generate url for each link country_metrics = api_connection.get_data('country', country_url.format(link), params=timeframe) # check if there is an error with group call and return response if country_metrics['code'] != 200: return country_metrics # append values for all countries to country_cicks list for country in country_metrics['response']['metrics']: country_clicks.append({ 'country': country['value'], 'clicks': int(country['clicks']), 'link_count': 1 }) # setup return object structure country_data = { 'default_group_id': user_default_group, 'country_metrics': [] } #sort country_clicks list for faster performance country_clicks.sort(key=lambda x: x['country']) # filter results if country id(s) provided as parameter if country_id: # split and conver to set for faster performance country_id_set = set(country_id.split(',')) country_clicks = [ item for item in country_clicks if item['country'] in country_id_set ] # use itertools library to aggregate click statistics for each country for key, group in itertools.groupby(country_clicks, key=lambda x: x['country']): # itertools.groupby returns generator object 'group' which can only be accessed once. # converting it to list to sum up multiple fields group = list(group) total_clicks = sum(d['clicks'] for d in group) total_links = sum(d['link_count'] for d in group) avg_clicks = total_clicks / total_links country_data['country_metrics'].append({ 'country': key, 'total_clicks': total_clicks, 'total_links': total_links, 'avg_clicks': avg_clicks }) return {'api': 'country_clicks', 'code': 200, 'response': country_data}
#!/bin/env python2 from client import Connection c = Connection() response = c.stored_procedure("TPCC-NewOrder", """{ "W_ID": 1, "D_ID": 1, "C_ID": 1, "O_CARRIER_ID": 5, "OL_DIST_INFO": "lalala", "items": [{"I_ID":1, "I_W_ID": 1, "quantity": 1}, {"I_ID":2, "I_W_ID": 1, "quantity": 1}, {"I_ID":7, "I_W_ID": 1, "quantity": 1}, {"I_ID":11, "I_W_ID": 1, "quantity": 1}, {"I_ID":3, "I_W_ID": 1, "quantity": 1}]}""") print response
elif ans2=="22": numTicket = input("Numéro du ticket? ") res = c.post('/bin/police_hq/ticket/' + str(numTicket) + '/close', confirm=True) print(res) elif ans2=="23": delpi_bancaire() elif ans2=="24": numTicket = input("Numéro du ticket? ") connection_kerberos(numTicket) elif ans2 !="": print("\n Not Valid Choice Try again") if __name__ == '__main__': c = Connection("http://pac.fil.cool/uglix") while True: print (""" 1.Connect as gritchie 2.Connect as gritchie CHAP 3.Decoder fichier B64 4.XOR 2 files """) ans=input("What would you like to do? ") if ans=="1": res = c.post('/bin/login', user='******', password="******") print(res) connected() elif ans =="2":
#!/bin/env python2 from client import Connection c = Connection() response = c.stored_procedure("TPCC-OrderStatus", """{ "W_ID": 1, "D_ID": 1, "C_ID": 1}""") print response d = Connection() response = d.stored_procedure( "TPCC-OrderStatus", """{ "W_ID": 1, "D_ID": 1, "C_LAST": "CLName1"}""") print response
from client import Connection _printer = lambda x: print(x) if __name__ == '__main__': # Connect to the broker conn = Connection('newavalon.cs.rit.edu') # Create a queue conn.create_queue('q1') # Subscribe to the queue conn.subscribe('q1', _printer)
#!/bin/env python2 from client import Connection c = Connection() response = c.stored_procedure("TPCC-Delivery", """{ "W_ID": 1, "D_ID": 1, "O_CARRIER_ID": 1}""") print response