def __init__(self, **kwargs): domain = __name__ definitions = [ Definition('cache', Cache, NoCache()), Definition('faults', bool, True), Definition('transport', Transport, None, TpLinker()), Definition('service', (int, basestring), None), Definition('port', (int, basestring), None), Definition('location', basestring, None), Definition('soapheaders', (), ()), Definition('wsse', Security, None), Definition('doctor', Doctor, None), Definition('xstq', bool, True), Definition('prefixes', bool, True), Definition('retxml', bool, False), Definition('prettyxml', bool, False), Definition('autoblend', bool, False), Definition('cachingpolicy', int, 0), Definition('plugins', (list, tuple), []), Definition('nosend', bool, False), ] Skin.__init__(self, domain, definitions, kwargs)
def getSessionId(self, client, serviceUrl): try: clientSDK = Client(serviceUrl + "?wsdl", cache=NoCache()) CxLogin = clientSDK.factory.create("Credentials") CxLogin.User = self.USERNAME CxLogin.Pass = self.PASSWORD cxSDK = clientSDK.service.Login(CxLogin, 1033) if not cxSDK.IsSuccesfull: raise Exception("Unable to Login > %s" % cxSDK.ErrorMessage) if self.DEBUG: print "Service Object:", dir(client) print "Login Object:", dir(cxSDK) print "Session ID:", cxSDK.SessionId return (cxSDK.SessionId, clientSDK) except Exception as e: raise Exception("Unable to get SessionId from [%s] : %s" % (serviceUrl, e.message))
from suds.client import Client from suds.cache import NoCache #url del servicio :http://127.0.0.1:8000/api/?wsdl my_client = Client('http://127.0.0.1:8000/api?WSDL', cache=NoCache()) print(my_client) print(my_client.service.say_hello('Pedro', 4)) #my_client.service.create('Jouberth')" print(my_client.service.get('Jouberth'))
ws = DEF_WS data = json.loads(data) if not data.get('event_setting') is None: event_setting = data.get('event_setting') username = event_setting.get('username') password = event_setting.get('password') ws = event_setting.get('ws') jdata = event_setting.get('jdata') try: client = Client(ws, username=username, password=password, cache=NoCache(), timeout=60) except Exception as e: print(e) continue #lens = [] #for i, val in enumerate(upd_event_lists): # lens.append((len(upd_event_lists[i]), i)) # min_list = min(lens) # upd_event_lists[min_list[1]].append({'username':username, 'password':password, 'ws':ws, 'jdata':jdata, 'method':method}) #_thread.start_new_thread(send, (username, password, jdata, method, ws,))
def client(self, value): if isinstance(value, (str, unicode)): self._client = Client(value, cache=NoCache()) else: self._client = value
def _create_soap_client(self): '''create a soap client using suds library takes wsdl url OR file as input ''' self.client = sudsClient.Client(self.wsdl, cache=NoCache())
# soap_client.py # coding=utf-8 from suds.client import Client from suds.cache import NoCache my_client = Client('http://127.0.0.1:8000/soap_service/?WSDL', cache=NoCache()) print my_client print 'Function getEventos: ', my_client.service.getEventos() print 'Function getCharlas: ', my_client.service.getCharlas()
from suds.cache import NoCache from suds.client import Client client = Client('http://127.0.0.1:8000/?wsdl', cache=NoCache()) print(client.service.count_one_word('punk punk', 'punk')) print(client.service.count_characters('punk punk')) print(client.service.count_words('punk punk word')) print(client.service.make_caps('punk punk word')) print(client.service.count_words_on_web_page('https://ya.ru')) # print(client.service.count_words_on_web_page('https://edu.susu.ru/'))
def remedy_cm_create(prodvsqa, arglist, CMURL): """Function to Create a Remedy Change Management ticket The prodvsqa parameter, if set to QA will use the QA server for the creation, otherwise prod. The arglist is a dictionary of key/value pairs to be set in the CM. The keys must correspond to the keys used in the Change Management WSDL for creating a new Ticket """ # This code stolen from the kick ass L.Bur, with permission, I do not assume responsibility for this code, nor do I support it. try: cmclient = Client(CMURL, cache=NoCache()) except Exception as myexception: raise Exception('CM_CreateClientCreate:' + str(myexception)) cmOpCreate = cmclient.factory.create('OpCreate') cmOpCreate = dict([(str(key), val) for key, val in cmOpCreate]) cmOpCreateRequired = {} cmOpCreateRequired['AssociatedDivision'] = True cmOpCreateRequired['Back-out_Instructions'] = True cmOpCreateRequired['Change_Start_Time'] = True cmOpCreateRequired['Change_Stop_Time'] = True cmOpCreateRequired['Changes_Planned'] = True cmOpCreateRequired['Country'] = True cmOpCreateRequired['CustFacing_CustSupporting'] = True cmOpCreateRequired['Impact'] = True cmOpCreateRequired['ReasonForChange'] = True cmOpCreateRequired['Requestor'] = True cmOpCreateRequired['Requestor_Phone'] = True cmOpCreateRequired['RequestorEmail'] = True cmOpCreateRequired['ResponsibleGroup'] = True cmOpCreateRequired['Short_Description'] = True cmOpCreateRequired['Status'] = True cmOpCreateRequired['Submitter'] = True cmOpCreateRequired['TypeOfChange'] = True cmOpCreateRequired['KnownImpact'] = True for key in list(cmOpCreate): if key in arglist: cmOpCreate[key] = arglist[key] elif key in cmOpCreateRequired: raise Exception('CM_Create:Required_Field_Missing:' + key) else: del cmOpCreate[key] try: cmresult = cmclient.service.OpCreate(**cmOpCreate) except Exception as myexception: raise Exception('CM_Create:' + str(myexception)) return cmresult syslogmsgbeginbase = 'scriptruntime' + keysep + delim + scriptruntime + delim + sep + 'SearchName' + keysep + delim + arghash[ 'searchName'] + delim + sep + 'searchCount' + keysep + delim + arghash[ 'searchCount'] + delim + sep + 'searchPath' + keysep + delim + arghash[ 'searchPath'] + delim + sep try: resultstatus = get_search_results(arghash['searchPath']) except Exception as myexception: syslogmessage = syslogmsgbeginbase + 'ScriptStatus' + keysep + delim + 'Fail_GetResults_Exception:' + str( myexception) + delim logorprint(syslogmessage, mylogfile) quit() if resultstatus == None: for resultrow in resultdict: resultrow['Submitter'] = remedysubmitter if not 'Requestor' in resultrow: resultrow['Requestor'] = remedyrequestor if not 'Status' in resultrow: resultrow['Status'] = remedydefaultstatus if 'prodvsqa' in resultrow: if resultrow['prodvsqa'] == 'PROD': prodvsqa = 'PROD' else: prodvsqa = 'QA' mystarttime = resultrow['Change_Start_Time'][ 5:7] + '/' + resultrow['Change_Start_Time'][ 8:10] + '/' + resultrow['Change_Start_Time'][ 0:4] + ' ' + resultrow['Change_Start_Time'][ 11:13] + ':' + resultrow['Change_Start_Time'][ 14:16] + ':' + resultrow[ 'Change_Start_Time'][17:19] print(mystarttime) mystoptime = resultrow['Change_Stop_Time'][ 5:7] + '/' + resultrow['Change_Stop_Time'][ 8:10] + '/' + resultrow['Change_Stop_Time'][ 0:4] + ' ' + resultrow['Change_Stop_Time'][ 11:13] + ':' + resultrow['Change_Stop_Time'][ 14:16] + ':' + resultrow[ 'Change_Stop_Time'][17:19] print(mystoptime) cmoplist['Qualification'] = cmoplist[ 'Qualification'] + ' AND \'Change Start Time\' = "' + mystarttime + '" AND \'Change Stop Time\' = "' + mystoptime + '"' if foundcm == 1 and len(cmresult) > 1: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_MoreThan1CMReturned' + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif resultrow['scriptaction'] == 'CancelCM' and foundcm == 0: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CancelNotFound' + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif resultrow['scriptaction'] == 'CreateCM' and foundcm == 1: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CreateAlreadyExists' + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif resultrow['scriptaction'] == 'CancelCM' and foundcm == 1: myrequestid = cmresult[0]['Request_ID'] cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['Status'] = 'Cancelled' cmopset['Cancelled'] = 'Yes' cmopset['RequestedWindow'] = resultrow['RequestedWindow'] syslogmsgbegin = syslogmsgbegin + 'CM_Ticket_Created' + keysep + delim + myrequestid + delim + sep try: remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMApprovedToCancel_Exception:' + str( myexception) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue if resultrow['sendnotify'] == '1': cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['TriggerNotifyCustomer'] = 'Yes' try: cmresult = remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMCancelNotify_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Success' + delim + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif resultrow[ 'scriptaction'] == 'RescheduleCM' and foundcm == 1: mystarttime = cmresult[0]['Change_Start_Time'] mystarttime = mystarttime.strftime( '%Y-%m-%dT%H:%M:%S-04:00') mystoptime = cmresult[0]['Change_Stop_Time'] mystoptime = mystoptime.strftime('%Y-%m-%dT%H:%M:%S-04:00') if resultrow[ 'Change_Start_Time'] == mystarttime and resultrow[ 'Change_Stop_Time'] == mystoptime: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_AlreadyRescheduled' + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) else: myrequestid = cmresult[0]['Request_ID'] cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['Status'] = 'Re-Scheduling' syslogmsgbegin = syslogmsgbegin + 'CM_Ticket_Created' + keysep + delim + myrequestid + delim + sep try: remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMApprovedToReschedule_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['Change_Start_Time'] = resultrow[ 'Change_Start_Time'] cmopset['Change_Stop_Time'] = resultrow[ 'Change_Stop_Time'] cmopset['Rescheduled'] = 'Yes' cmopset['RequestedWindow'] = resultrow[ 'RequestedWindow'] try: remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMRescheduleChangeTimes_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue if resultrow['sendnotify'] == '1': cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['TriggerNotifyCustomer'] = 'Yes' try: cmresult = remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMRescheduleNotify_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue cmopset = {} cmopset['Request_ID'] = myrequestid cmopset['Status'] = 'Requested' try: cmresult = remedy_cm_update(prodvsqa, cmopset) except Exception as myexception: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_CMRescheduleRequested_Exception:' + str( myexception ) + delim + sep + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) continue syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Success' + delim + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) elif foundcm == 0 and ( resultrow['scriptaction'] == 'RescheduleCM' or resultrow['scriptaction'] == 'CreateCM'): try: cmresult = remedy_cm_create(prodvsqa, resultrow) except Exception as myexception: print(str(Exception)) continue else: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_Unknown_scriptaction' + delim + syslogmsgsearchresults logorprint(syslogmessage, mylogfile) else: syslogmessage = syslogmsgbegin + 'ScriptStatus' + keysep + delim + 'Fail_GetResults_Without_Exception' + delim logorprint(syslogmessage, mylogfile) quit()
def getClient(url): # Authentication httpAuthenticated = UtilsISPyB.getHttpAuthenticated() client = Client(url, transport=httpAuthenticated, cache=NoCache(), timeout=15) return client
from suds.cache import NoCache from suds.client import Client import socket import time # Code to get local ip of the machine s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("7.7.7.7", 80)) localIP = s.getsockname()[0] try: discoveryUrl = 'http://' + localIP + ':8082/servicediscovery?wsdl' discoveryClient = Client(discoveryUrl, cache=NoCache(), timeout=100) except Exception as identifier: discoveryUrl = 'http://' + localIP + ':8083/servicediscovery?wsdl' discoveryClient = Client(discoveryUrl, cache=NoCache(), timeout=100) #Number of requests i = 100 start = time.time() while i > 0: serviceUrl = discoveryClient.service.discover("", "stringReverse") serviceClient = Client(serviceUrl, cache=NoCache(), timeout=5) print serviceClient.service.stringReverse('AOS') print i i = i - 1 end = time.time() print 'completed' print end - start
def main(argv): # Command-line arguments serverFile = None try: opts, args = getopt.getopt(argv, "hF:", ["serverFile="]) except getopt.GetoptError: print './test.py -F <serverFile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print './test.py -F <serverFile>' sys.exit() elif opt in ("-U", "--serverFile="): serverFile = arg #Read server address file and append to list if serverFile is none: logging.error('No server or client name provided.') sys.exit(1) sfile = None try: sfile = open(serverFile, 'r') except: logging.error("error while trying to open the file.") sys.exit(1) servers = [] for line in sfile: addr = line.strip('\n').split(' ') uri = 'http://' + addr[0] + ':' + addr[ 1] + '/?wsdl' #'http://hostname:7789/?wsdl' servers.append(uri) #Create clients clients = [] logging.info("Testing single client with single server...") clients[0] = Client(servers[0], cache=NoCache(), timeout=60) logging.info("Get value for key 1: result: %s", clients[0].service.get('1')) logging.info("Put key 1: result: %s", clients[0].service.put('1', 'one')) logging.info("Put key 2: result: %s", clients[0].service.put('2', 'two')) logging.info("Put key 3: result: %s", clients[0].service.put('3', 'three')) logging.info("Get value for key 1: result: %s", clients[0].service.get('1')) logging.info("Get value for key 3: result: %s", clients[0].service.get('3')) logging.info("Put key 1: result: %s", clients[0].service.put('1', 'One')) logging.info("Get value for key 1: result: %s", clients[0].service.get('1')) logging.info("Delete key 1: result: %s", clients[0].service.delete('1')) logging.info("Get value for key 1: result: %s", clients[0].service.get('1')) # Test with two clients connected to single server. logging.info("Testing two clients with single server...") clients[1] = Client(servers[0], cache=NoCache(), timeout=60) logging.info("Get value for key 2: result: %s", clients[1].service.get('2')) logging.info("Put key 4: result: %s", clients[1].service.put('4', 'Four')) logging.info("Put key 5: result: %s", clients[0].service.put('5', 'Five')) logging.info("Get value for key 5: result: %s", clients[1].service.get('5')) logging.info("Get value for key 4: result: %s", clients[1].service.get('4')) logging.info("Get value for key 4: result: %s", clients[0].service.get('4')) logging.info("Delete key 2: result: %s", clients[0].service.delete('2')) logging.info("Delete key 3: result: %s", clients[1].service.delete('3')) logging.info("Get value for key 3: result: %s", clients[0].service.get('3')) logging.info("Get value for key 2: result: %s", clients[0].service.get('2')) logging.info("Get value for key 2: result: %s", clients[1].service.get('2'))
def __init__(self, wsdl_url): self.wsdl_url = wsdl_url self.client = Client(self.wsdl_url, cache=NoCache())
def test_client(request): client = Client('http://soap.dev/server.php?wsdl', cache=NoCache()) return HttpResponse("Client: " + str(client.service.getQuantity(2)))
def client_soap(config_file): # *------------------------------------------------------------------ # * function client_soap(config_file) # * # * Copyright (C) 2015 Carlos Sanz <*****@*****.**> # * # * This program is free software; you can redistribute it and/or # * modify it under the terms of the GNU General Public License # * as published by the Free Software Foundation; either version 2 # * of the License, or (at your option) any later version. # * # * This program is distributed in the hope that it will be useful, # * but WITHOUT ANY WARRANTY; without even the implied warranty of # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # * GNU General Public License for more details. # * # * You should have received a copy of the GNU General Public License # * along with this program; if not, write to the Free Software # * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, # *------------------------------------------------------------------ # * logger.debug('Ha entrado en la funcion client_soap()') csp_cmserver = cspconfigfile['CUCM']['server'] csp_username = cspconfigfile['CUCM']['user'] csp_password = cspconfigfile['CUCM']['pass'] csp_version = cspconfigfile['CUCM']['version'] if platform.system() == 'Windows': logger.debug('El sistema operativo es: %s' % (platform.system())) wsdl = 'file:///' + os.getcwd().replace( "\\", "//") + '//Schema//CUCM//' + csp_version + '//AXLAPI.wsdl' else: logger.debug('El sistema operativo es: %s' % (platform.system())) wsdl = 'file:///' + os.getcwd( ) + '/Schema/CUCM/' + csp_version + '/AXLAPI.wsdl' csp_location = 'https://' + csp_cmserver + ':8443/axl/' logger.debug('El valor de csp_cmserver es: %s' % (csp_cmserver)) logger.debug('El valor de csp_username es: %s' % (csp_username)) logger.debug('El valor de csp_version es: %s' % (csp_version)) logger.debug('El valor de csp_location es: %s' % (csp_location)) logger.debug('El valor de wsdl es: %s' % (wsdl)) # Tiempo de inicio de ejecucion. try: csp_soap_client = suds.client.Client( wsdl, location=csp_location, username=csp_username, password=csp_password, cache=NoCache(), ) except: logger.error('Se ha producido un error al crear el cliente soap') logger.debug(sys.exc_info()) logger.error(sys.exc_info()[1]) sys.exit() else: logger.info('Se ha creado el cliente SOAP.') try: csp_version_long = cspaxl_version.Get(logger, csp_soap_client, csp_cmserver) except: logger.error( 'Se ha producido un error al comprobar la version del servidor soap' ) logger.debug(sys.exc_info()) logger.error(sys.exc_info()[1]) sys.exit() else: if csp_version_long['Status']: logger.info('Se ha verificado la version del servidor soap.') csp_table = PrettyTable( ['Server', 'Username', 'Version Conf_File', 'Version Real']) csp_table.add_row([ csp_cmserver, csp_username, csp_version, csp_version_long['Detail'] ]) csp_table_response = csp_table.get_string(fields=[ 'Server', 'Username', 'Version Conf_File', 'Version Real' ], sortby="Server") logger.info('\n\n' + csp_table_response + '\n') return csp_soap_client else: logger.error( 'Se ha proucido un error comprobando la version del servidor soap' ) sys.exit()
def __init__(self, parent, name=None, debug=False, shared=False, agentSupport=False, agent=None, sslSupport=False, bindIp='', bindPort=0, destinationIp='www.webservicex.net', destinationPort=80, xmlns0='', httpAuthentication=False, httpLogin='', httpPassword='', xmlns1='http://schemas.xmlsoap.org/soap/envelope/', xmlns2='http://www.w3.org/2003/05/soap-envelope', xmlns3='http://www.w3.org/2001/XMLSchema-instance', xmlns7='', xmlns8='', xmlns4='http://www.w3.org/2001/XMLSchema', xmlns5='http://www.w3.org/XML/1998/namespace', xmlns6='', destUri='/globalweather.asmx', proxyIp='', proxyPort=3128, proxyHost='', proxyEnabled=False, proxyType=AdapterTCP.PROXY_HTTP): """ Adapter generated automatically from wsdl @param parent: parent testcase @type parent: testcase @param name: adapter name used with from origin/to destination (default=None) @type name: string/none @param debug: active debug mode (default=False) @type debug: boolean @param shared: shared adapter (default=False) @type shared: boolean @param bindIp: bind ip (default='') @type bindIp: string @param bindPort: bind port (default=0) @type bindPort: integer @param destinationIp: destination ip (default=127.0.0.1) @type destinationIp: string @param destinationPort: destination port (default=80) @type destinationPort: integer @param xmlns0: xml namespace @type xmlns0: string @param xmlns1: xml namespace (default=http://schemas.xmlsoap.org/soap/envelope/) @type xmlns1: string @param xmlns2: xml namespace (defaut=http://www.w3.org/2003/05/soap-envelope) @type xmlns2: string @param xmlns3: xml namespace (default=http://www.w3.org/2001/XMLSchema-instance) @type xmlns3: string @param xmlns4: xml namespace (default=http://www.w3.org/2001/XMLSchema) @type xmlns4: string @param xmlns5: xml namespace (default=) @type xmlns5: string @param xmlns6: xml namespace (default=) @type xmlns6: string @param xmlns7: xml namespace (default=) @type xmlns7: string @param xmlns8: xml namespace (default=) @type xmlns8: string @param sslSupport: ssl support (default=False) @type sslSupport: boolean @param destUri: destination uri @type destUri: string @param proxyType: SutAdapters.TCP.PROXY_HTTP (default) | SutAdapters.TCP.PROXY_SOCKS4 | SutAdapters.TCP.PROXY_SOCKS5 @type proxyType: strconstant @param proxyIp: proxy ip @type proxyIp: string @param proxyPort: proxy port @type proxyPort: integer @param proxyHost: proxy host (automatic dns resolution) @type proxyHost: string @param proxyEnabled: True to support proxy (default=False) @type proxyEnabled: boolean @param httpAuthentication: support http digest authentication (default=False) @type httpAuthentication: boolean @param httpLogin: login used on http digest authentication (default='') @type httpLogin: string @param httpPassword: password used on http digest authentication (default='') @type httpPassword: string @param agentSupport: agent support to use a remote socket (default=False) @type agentSupport: boolean @param agent: agent to use when this mode is activated @type agent: string/None """ TestAdapter.Adapter.__init__(self, name=__NAME__, parent=parent, debug=debug, realname=name) self.codecX2D = Xml2Dict.Xml2Dict() self.codecD2X = Dict2Xml.Dict2Xml(coding=None) self.cfg = {} self.cfg['local-wsdl'] = '%s/%s/%s' % (TestAdapter.getMainPath(), TestAdapter.getVersion(), '/GlobalWeather/wsdl.txt') self.cfg['host'] = destinationIp self.cfg['uri'] = destUri self.cfg['http-login'] = httpLogin self.cfg['http-password'] = httpPassword self.ADP_SOAP = AdapterSOAP.Client( parent=parent, name=name, bindIp=bindIp, bindPort=bindPort, destinationIp=destinationIp, destinationPort=destinationPort, debug=debug, logEventSent=True, logEventReceived=True, xmlns0=xmlns0, xmlns1=xmlns1, xmlns2=xmlns2, xmlns7=xmlns7, xmlns8=xmlns8, xmlns3=xmlns3, xmlns4=xmlns4, xmlns5=xmlns5, xmlns6=xmlns6, httpAgent='ExtensiveTesting', sslSupport=sslSupport, agentSupport=agentSupport, httpAuthentication=httpAuthentication, proxyIp=proxyIp, proxyPort=proxyPort, proxyHost=proxyHost, proxyEnabled=proxyEnabled, proxyType=proxyType, agent=agent, shared=shared) try: self.LIB_SUDS = Client("file://%s" % self.cfg['local-wsdl'], nosend=True, cache=NoCache()) except Exception as e: raise Exception("Unable to load the wsdl file: %s" % e) # agent support self.cfg['agent-support'] = agentSupport if agentSupport: self.cfg['agent'] = agent self.cfg['agent-name'] = agent['name'] self.__checkConfig()
def main(argv): # logging #logging = logging.getlogging('client').setLevel(logging.DEBUG) # command-line arguments uri_file = ['http://127.0.0.1:7788/?wsdl', 'http://127.0.0.1:7789/?wsdl'] uriFilePath = None try: opts, args = getopt.getopt(argv, "hU:", ["uri_file="]) except getopt.GetoptError: print './client.py -U <uri_file>' sys.exit(2) for opt, arg in opts: if opt == '-h': print './client.py -U <uri_file>' sys.exit() elif opt in ("-U", "--uri_file"): uriFilePath = arg # load URIs if uriFilePath is not None: try: uri_file = open(uriFilePath, 'r') except IOError: logging.error('unable to open URI file') uri_file = [ 'http://127.0.0.1:7788/?wsdl', 'http://127.0.0.1:7789/?wsdl' ] #TODO: remove this line # Create one client for each replica of server clients = [] uriList = [] counter = -1 for uri in uri_file: counter += 1 uriList.append(uri) #c = Client('file://' + uri, nosend=True, autoblend=True, cache=NoCache()) c = Client(uri, cache=NoCache(), timeout=120) clients.append(c) #print "client: ", clients[0], dir(clients[0]) # Add server and replica info logging.debug('Adding replicas %d', len(uriList)) counter = -1 while (counter < len(uriList) - 1): logging.debug('counter: %d', counter) counter = counter + 1 # set server logging.debug('server: %s', uriList[counter]) clients[counter].service.set_server(uriList[counter]) #context = clients[counter].service.set_server(uriList[counter]) #d = client.getPage(url=context.client.location(), postdata=str(context.envelope), # method='POST', headers=context.client.headers()) # Add replicas for uri in uriList: if uri.find(uriList[counter]) == -1: logging.debug('replica: %s', uri) clients[counter].service.add_replica(uri) logging.debug('starting queries...') print clients[0].service.get('key1') #context = clients[0].service.put('key1', 'fee') #d = client.getPage(url=context.client.location(), postdata=str(context.envelope), # method='POST', headers=context.client.headers()) #print "success" print clients[0].service.put('key1', 'foo') print clients[0].service.get('key1') print clients[0].service.delete('key1') print clients[0].service.get('key1')
def client_soap(config_file): # *------------------------------------------------------------------ # * function client_soap(config_file) # *------------------------------------------------------------------ # * Esta funcion nos permite crear un cliente de SOAP con los siguientes # * datos: # * # * IP Address # * Usuario # * Password # *------------------------------------------------------------------ # * global csp_soap_client logger.debug('Ha entrado en la funcion client_soap()') csp_cmserver = cspconfigfile['CUCM']['server'] csp_ip = cspconfigfile['CUCM']['ip'] csp_username = cspconfigfile['CUCM']['user'] csp_password = cspconfigfile['CUCM']['pass'] csp_version = cspconfigfile['CUCM']['version'] if platform.system() == 'Windows': logger.debug('El sistema operativo es: %s' % (platform.system())) wsdl = 'file:///' + os.getcwd().replace( "\\", "//") + '//Schema//CUCM//' + csp_version + '//AXLAPI.wsdl' else: logger.debug('El sistema operativo es: %s' % (platform.system())) wsdl = 'file:///' + os.getcwd( ) + '/Schema/CUCM/' + csp_version + '/AXLAPI.wsdl' csp_location = 'https://' + csp_cmserver + ':8443/axl/' logger.debug('El valor de csp_cmserver es: %s' % (csp_cmserver)) logger.debug('El valor de csp_ip es: %s' % (csp_ip)) logger.debug('El valor de csp_username es: %s' % (csp_username)) logger.debug('El valor de csp_version es: %s' % (csp_version)) logger.debug('El valor de csp_location es: %s' % (csp_location)) logger.debug('El valor de wsdl es: %s' % (wsdl)) # Tiempo de inicio de ejecucion. try: csp_soap_client = suds.client.Client( wsdl, location=csp_location, username=csp_username, password=csp_password, cache=NoCache(), ) except: logger.error('Se ha producido un error al crear el cliente soap') logger.debug(sys.exc_info()) logger.error(sys.exc_info()[1]) sys.exit() else: logger.info('Se ha creado el cliente SOAP.') try: csp_version_long = csp_soap_client.service.getCCMVersion( processNodeName=csp_ip) except: logger.error( 'Se ha producido un error al comprobar la version del servidor soap' ) logger.debug(sys.exc_info()) logger.error(sys.exc_info()[1]) sys.exit() else: logger.info('Se ha verificado la version del servidor soap.') csp_table = PrettyTable( ['Server', 'Username', 'Version Conf_File', 'Version Real']) csp_table.add_row([ csp_cmserver, csp_username, csp_version, csp_version_long['return']['componentVersion'].version ]) csp_table_response = csp_table.get_string( fields=['Server', 'Username', 'Version Conf_File', 'Version Real'], sortby="Server") logger.info('\n\n' + csp_table_response + '\n')
def read_wsdl(wsdlFile): """ Read wsdl """ # construct the client with wsdl print("1. Reading WSDL") try: client = Client("file://%s" % wsdlFile, nosend=False, cache=NoCache()) sdList = client.sd # all service definition except Exception as e: print("ERROR: unable to read wsdl: %s" % e) sys.exit(1) else: adaptersName = [] complexList = {} for sd in sdList: adps = {} adps['name'] = sd.service.name adps['namespaces'] = sd.prefixes adps['adapters'] = [] for p in sd.ports: adp = {} portLocation = p[0].location adp['ssl'] = False if portLocation.startswith("https://"): adp['ssl'] = True host, uri = parse_portlocation(portlocation=portLocation, https=adp['ssl']) adp['host'] = host adp['uri'] = '/%s' % uri adp['host-port'] = 80 if adp['ssl']: adp['host-port'] = 443 destPort = adp['host'].split(':') if len(destPort) == 2: adp['host-port'] = destPort[1] __adpname = p[0].name adp['name'] = __adpname.replace("-", "") adp['methods'] = [] for m in p[1]: method = {} method['name'] = m[0] method['args'] = [] for a in m[1]: arg = {} argType = a[1].resolve().name # simple type arg (string, bool, int, double, long) if argType in [ "string", "boolean", "int", "double", "long", "base64Binary", "dateTime", "nonNegativeInteger" ]: if a[1].required(): arg['expected'] = 'required' else: arg['expected'] = 'optional' arg['name'] = a[0] if argType == "double": arg['type'] = "float" else: arg['type'] = argType else: # advanced arg ? (restriction, .... ) if a[1].restriction(): values = a[1].rawchildren[0].content() vType = values[1].resolve().ref[0] l = [] for v in values: if v.resolve().name is not None: l.append(v.resolve().name) if vType in [ "string", "boolean", "int", "double", "long", "base64Binary", "dateTime", "nonNegativeInteger" ]: arg['name'] = a[0] arg['type'] = vType if vType == "double": arg['type'] = "float" else: arg['type'] = vType arg['value'] = l if a[1].required(): arg['expected'] = 'required' else: arg['expected'] = 'optional' else: print( 'arg - restriction - not yet implemented: %s' % vType) elif a[1].sequence(): print( 'arg - sequence - not yet implemented: %s' % vType) elif a[1].xslist(): print( 'arg - xslist - not yet implemented: %s' % vType) elif a[1].choice(): print( 'arg - choice - not yet implemented: %s' % vType) elif a[1].all(): print('arg - all - not yet implemented: %s' % vType) elif a[1].any(): print('arg - any - not yet implemented: %s' % vType) elif a[1].builtin(): print( 'arg - builtin - not yet implemented: %s' % vType) elif a[1].enum(): print('arg - enum - not yet implemented: %s' % vType) elif a[1].extension(): print( 'arg - extension - not yet implemented: %s' % vType) elif a[1].restriction(): print( 'arg - restriction - not yet implemented: %s' % vType) elif a[1].isattr(): print( 'arg - isattr - not yet implemented: %s' % vType) elif a[1].mixed(): print('arg - mixed - not yet implemented: %s' % vType) else: # complex arg ? complex = get_type(sd=sd, type_name=argType) if not len(complex): print( 'complex arg not yet implemented: %s' % argType) else: arg['name'] = a[0] arg['type'] = argType if a[1].required(): arg['expected'] = 'required' else: arg['expected'] = 'optional' if complex['name'] not in complexList: if 'args' in complex: complexList[complex[ 'name']] = complex['args'] for carg in complex['args']: if carg['type'] not in [ 'string', 'boolean', 'int', 'double', 'long', "base64Binary", "dateTime", "nonNegativeInteger" ]: complex2 = get_type( sd=sd, type_name=carg['type']) if not len(complex2): print( 'complex-2 arg not yet implemented: %s' % carg['type']) else: if complex2[ 'name'] not in complexList: if 'args' in complex2: complexList[complex2[ 'name']] = complex2[ 'args'] if len(arg): method['args'].append(arg) adp['methods'].append(method) print("\tnb methods detected: %s" % len(adp['methods'])) print("\tnb complex type detected: %s" % len(complexList)) adps['adapters'].append(adp) adaptersName.append(adps) return (adaptersName, complexList)
def get_resource_information(gss_location, gss_ID, session_token): """Returns a GSS resourceInformation object for the given gss ID.""" client = Client(gss_location, cache=NoCache()) return client.service.getResourceInformation(gss_ID, session_token)
from suds.client import Client from suds.cache import NoCache url = "http://localhost:8080/Calc/CalculadoraSOAP?WSDL" client = Client(url, cache=NoCache()) #invocando os metodos print client.service.somar(3, 2) # print client.service.SomarNumeros(3,2); #exibindo os servicos # print client
def __init__(self, xaddr, user, passwd, url, cache_location='/tmp/suds', cache_duration=None, encrypt=True, daemon=False, ws_client=None, no_cache=False, portType=None, dt_diff=None, timeout=None): if not os.path.isfile(url): raise ONVIFError('%s doesn`t exist!' % url) if no_cache: cache = NoCache() else: # Create cache object # NOTE: if cache_location is specified, # onvif must has the permission to access it. cache = ObjectCache(location=cache_location) # cache_duration: cache will expire in `cache_duration` days if cache_duration is not None: cache.setduration(days=cache_duration) # Convert pathname to url self.url = urlparse.urljoin('file:', urllib.pathname2url(url)) self.xaddr = xaddr soap_kwargs = {} if timeout: soap_kwargs['timeout'] = timeout # Create soap client if not ws_client: self.ws_client = Client( url=self.url, location=self.xaddr, cache=cache, port=portType, headers={'Content-Type': 'application/soap+xml'}, **soap_kwargs) else: self.ws_client = ws_client self.ws_client.set_options(location=self.xaddr) # Set soap header for authentication self.user = user self.passwd = passwd # Indicate wether password digest is needed self.encrypt = encrypt self.daemon = daemon self.dt_diff = dt_diff if self.user is not None and self.passwd is not None: self.set_wsse() # Method to create type instance of service method defined in WSDL self.create_type = self.ws_client.factory.create