def __init__( self, host=cfg.cucm_host, username=cfg.cucm_user, password=cfg.cucm_pass, timeout=30): self.host = host self.username = username self.password = password self.timeout = timeout wsdl = 'https://' + host + \ ':8443/logcollectionservice2/services/LogCollectionPortTypeService?wsdl' location = 'https://' + host + \ ':8443/logcollectionservice2/services/LogCollectionPortTypeService' t = HttpAuthenticated(username=self.username, password=self.password, timeout=timeout) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1) self.client = Client( wsdl, location=location, username=username, password=password, cache=None, transport=t )
def __init__(self, username, password, wsdl, cucm, cucm_version=10): """ :param username: axl username :param password: axl password :param wsdl: wsdl file location :param cucm: UCM IP address :param cucm_version: UCM version """ self.username = username self.password = password self.wsdl = wsdl self.cucm = cucm self.cucm_version = cucm_version tns = 'http://schemas.cisco.com/ast/soap/' imp = Import('http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add(tns) t = HttpAuthenticated(username=self.username, password=self.password) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1) self.client = Client(self.wsdl, location='https://{0}:8443/axl/'.format(cucm), faults=False, plugins=[ImportDoctor(imp)], transport=t)
def __init__(self, username, password, cucm, cucm_version): """ :param username: ris username :param password: ris password :param cucm: UCM IP address :param cucm_version: UCM version example usage: >>> from ris import RIS >>> ucm = RIS('ris_user', 'ris_pass', '192.168.200.10', '11.5') """ self.username = username self.password = password self.wsdl = 'https://'+cucm+':8443//realtimeservice2/services/RISService70?wsdl' self.cucm = cucm self.cucm_version = cucm_version tns = 'http://schemas.cisco.com/ast/soap/' imp = Import('http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add(tns) t = HttpAuthenticated(username=self.username, password=self.password) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1) self.client = Client(self.wsdl, location='https://{0}:8443/realtimeservice2/services/RISService70'.format(cucm), faults=False, plugins=[ImportDoctor(imp)], transport=t)
def axlSQL(): #get AXL information from GUI info = connectAXL() location = info.get('location') username = info.get('username') password = info.get('password') wsdl = info.get('wsdl') t = HttpAuthenticated(username=username, password=password) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE ssl_def_context.set_ciphers('HIGH:!DH:!aNULL') t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1) try: client = Client(wsdl, location=location, plugins=[ImportDoctor(imp)], transport=t) try: result = client.service.executeSQLQuery( "select ProcessNode.name as ProcessNode, ProcessConfig.paramname,ProcessConfig.paramvalue as ProcessConfig from processconfig,processnode where ProcessConfig.fkprocessnode = ProcessNode.pkid" ) car.clearTable() for node in result['return']['row']: car.LoadTable(str(node['processnode']), str(node['paramname']), str(node['processconfig']), '') except Exception as e: logger.critical(e) except Exception as e: logger.critical(e)
def setup_connection(): result = urllib2.install_opener(urllib2.build_opener(HTTPSHandlerV3())) logging.raiseExceptions = 0 beamlineScheduleServiceURL = base + \ 'beamlineScheduleService/beamlineScheduleWebService.wsdl' runScheduleServiceURL = base + \ 'runScheduleService/runScheduleWebService.wsdl' try: credentials = dict(username=username, password=password) t = HttpAuthenticated(**credentials) if debug: print t.u2handlers() print t.credentials() runScheduleServiceClient = Client(runScheduleServiceURL) runScheduleServiceClient.options.cache.setduration(seconds=10) result = setSoapHeader(runScheduleServiceClient, username, password) beamlineScheduleServiceClient = Client(beamlineScheduleServiceURL) beamlineScheduleServiceClient.options.cache.setduration(seconds=10) result = setSoapHeader(beamlineScheduleServiceClient, username, password) except Exception, ex: print "CANNOT OPEN SERVICES:" + str(ex) raise exit(-1)
def button_testaxl_callback(): info = connectAXL() location = info.get('location') username = info.get('username') password = info.get('password') wsdl = info.get('wsdl') t = HttpAuthenticated(username=username, password=password) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE ssl_def_context.set_ciphers('HIGH:!DH:!aNULL') t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1) try: client = Client(wsdl, location=location, plugins=[ImportDoctor(imp)], transport=t) resp = client.service.getCCMVersion() version = resp['return'].componentVersion.version logger.info('Successfully tested to Call Manager : ' + version) except Exception as e: logger.error('Failed to connect to ' + location) logger.critical(e)
def axlinsertSQL(server, name, newval): #get AXL information from GUI info = connectAXL() location = info.get('location') username = info.get('username') password = info.get('password') wsdl = info.get('wsdl') t = HttpAuthenticated(username=username, password=password) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE ssl_def_context.set_ciphers('HIGH:!DH:!aNULL') t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1) try: client = Client(wsdl, location=location, plugins=[ImportDoctor(imp)], transport=t) try: sqlStr = "insert into processconfig(paramvalue,paramname,tkservice,tkparam,fkprocessnode) values ('" + newval + "','" + name + "','0','2',(select ProcessNode.pkid from Processnode where ProcessNode.name='" + server + "'))" result = client.service.executeSQLUpdate(sqlStr) logger.info("Successfully inserted " + name + " to '" + newval + "' on " + server) except Exception as e: logger.critical(e) except Exception as e: logger.critical(e)
def get_auth_stub(config): """ Given a config dict in the format: {'clientid': ... your ET client ID ..., 'clientsecret': ... your ET client secret ...} ... return an auth stub to be used when making requests. """ LOGGER.info("Generating auth stub...") params = { 'clientid': config['client_id'], 'clientsecret': config['client_secret'] } if config.get('tenant_subdomain'): # For S10+ accounts: https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-apis.meta/mc-apis/your-subdomain-tenant-specific-endpoints.htm params['authenticationurl'] = ('https://{}.auth.marketingcloudapis.com/v1/requestToken' .format(config['tenant_subdomain'])) LOGGER.info("Authentication URL is: %s", params['authenticationurl']) params['soapendpoint'] = ('https://{}.soap.marketingcloudapis.com/Service.asmx' .format(config['tenant_subdomain'])) # First try V1 try: LOGGER.info('Trying to authenticate using V1 endpoint') params['useOAuth2Authentication'] = "False" auth_stub = FuelSDK.ET_Client(params=params) transport = HttpAuthenticated(timeout=int(config.get('request_timeout', 3600))) auth_stub.soap_client.set_options( transport=transport, timeout=3600) LOGGER.info("Success.") return auth_stub except Exception as e: LOGGER.info('Failed to auth using V1 endpoint') if not config.get('tenant_subdomain'): LOGGER.warning('No tenant_subdomain found, will not attempt to auth with V2 endpoint') raise e # Next try V2 # Move to OAuth2: https://help.salesforce.com/articleView?id=mc_rn_january_2019_platform_ip_remove_legacy_package_create_ability.htm&type=5 try: LOGGER.info('Trying to authenticate using V2 endpoint') params['useOAuth2Authentication'] = "True" params['authenticationurl'] = ('https://{}.auth.marketingcloudapis.com' .format(config['tenant_subdomain'])) LOGGER.info("Authentication URL is: %s", params['authenticationurl']) auth_stub = FuelSDK.ET_Client(params=params) transport = HttpAuthenticated(timeout=int(config.get('request_timeout', 3600))) auth_stub.soap_client.set_options( transport=transport, timeout=3600) except Exception as e: LOGGER.info('Failed to auth using V2 endpoint') raise e LOGGER.info("Success.") return auth_stub
def __init__(self, con_opts): wsdl_url = 'file://%s/PeakflowSP.wsdl' % os.path.dirname(__file__) soap_url = 'https://%s/soap/sp' % con_opts.host # SOAP shit t = HttpAuthenticated(username=con_opts.username, password=con_opts.password) t.handler = urllib2.HTTPDigestAuthHandler(t.pm) t.urlopener = urllib2.build_opener(t.handler) self.client = Client(url = wsdl_url, location = soap_url, transport = t) self._timeout = 10
def __init__(self, con_opts): wsdl_url = 'file://%s/PeakflowSP.wsdl' % os.path.dirname(__file__) soap_url = 'https://%s/soap/sp' % con_opts.host # SOAP shit t = HttpAuthenticated(username=con_opts.username, password=con_opts.password) t.handler = urllib2.HTTPDigestAuthHandler(t.pm) t.urlopener = urllib2.build_opener(t.handler) self.client = Client(url=wsdl_url, location=soap_url, transport=t) self._timeout = 10
def get_service(): global url global username global password wsdl_url = 'file://%s/PeakflowSP.wsdl' % os.getcwd() t = HttpAuthenticated(username=username, password=password) t.handler = urllib2.HTTPDigestAuthHandler(t.pm) t.urlopener = urllib2.build_opener(t.handler) client = Client(url=wsdl_url, location=url, transport=t) return client
def __init__(self, username, password, source='', wsdl_url=None, **kwargs): if not wsdl_url: wsdl_url = docmail.client.DOCMAIL_WSDL self.source = source self.username = username self.password = password self.return_format = 'XML' self.failure_return_format = 'XML' options = Options() options.transport = HttpAuthenticated() self.options = options options.cache = MemCache() self.set_options(**kwargs) reader = DefinitionsReader(options, Definitions) self.wsdl = reader.open(wsdl_url) plugins = PluginContainer(options.plugins) plugins.init.initialized(wsdl=self.wsdl) self.factory = Factory(self.wsdl) self.service = ServiceSelector(self, self.wsdl.services) self.sd = [] for s in self.wsdl.services: sd = ServiceDefinition(self.wsdl, s) self.sd.append(sd) self.messages = dict(tx=None, rx=None)
def connect_AXL(): # First we connect to the AXL API # Logging for debugging logging.basicConfig(level=logging.INFO) #logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.client').setLevel(logging.CRITICAL) #logging.getLogger('suds.transport').setLevel(logging.DEBUG) #logging.getLogger('suds.xsd.schema').setLevel(logging.CRITICAL) #logging.getLogger('suds.wsdl').setLevel(logging.CRITICAL) #"Connecting to myphone.central1.com to add the line and phones for the user" location = 'https://172.20.133.71:8443/axl/' if platform.uname()[0] == 'Darwin': # OSX path wsdl = 'file:///Users/fbobes/Documents/Python/CUCM/AXLAPI.wsdl' elif platform.uname()[0] == 'Linux': # Linux path wsdl = 'file:///home/fbobes/cucm/AXLAPI.wsdl' else: # Some other OS wsdl = 'file:///home/fbobes/cucm/AXLAPI.wsdl' auth = getAuthentication("axl") Username = auth[0] Password = auth[1] # Bypassing SSL self-cert check ssl._create_default_https_context = ssl._create_unverified_context # URL Detail client = Client(wsdl,location = location, transport = HttpAuthenticated(username = Username, password = Password),faults=False) return client
def add_client(self): logger.info('About to add a client to `%s` (%s)', self.address, self.conn_type) # Lazily-imported here to make sure gevent monkey patches everything well in advance from suds.client import Client from suds.transport.https import HttpAuthenticated from suds.transport.https import WindowsHttpAuthenticated from suds.wsse import Security, UsernameToken sec_type = self.config['sec_type'] if sec_type == SEC_DEF_TYPE.BASIC_AUTH: transport = HttpAuthenticated(**self.suds_auth) elif sec_type == SEC_DEF_TYPE.NTLM: transport = WindowsHttpAuthenticated(**self.suds_auth) elif sec_type == SEC_DEF_TYPE.WSS: security = Security() token = UsernameToken(self.suds_auth['username'], self.suds_auth['password']) security.tokens.append(token) client = Client(self.address, autoblend=True, wsse=security) if sec_type in(SEC_DEF_TYPE.BASIC_AUTH, SEC_DEF_TYPE.NTLM): client = Client(self.address, autoblend=True, transport=transport) # Still could be either none at all or WSS if not sec_type: client = Client(self.address, autoblend=True, timeout=self.config['timeout']) self.client.put_client(client)
def new_client(service_type): """ Make a `suds` client, accounting for ?wsdl suffixes, failing to import appropriate schemas, and http auth Args: service_type: type of service to ping (usually 'procurement_service' or 'grant_service') Returns: Client for FSRS service """ config = service_config(service_type) wsdl_url = config.get('wsdl', '') options = {'url': wsdl_url} if wsdl_url.endswith('?wsdl'): options['location'] = wsdl_url[:-len('?wsdl')] # The WSDL is missing an import; it's so common that suds has a work around parsed_wsdl = urlparse(wsdl_url) import_fix = doctor.Import('http://schemas.xmlsoap.org/soap/encoding/') # Main namespace is the wsdl domain import_fix.filter.add('{}://{}/'.format(parsed_wsdl.scheme, parsed_wsdl.netloc)) options['doctor'] = doctor.ImportDoctor(import_fix) options['plugins'] = [ControlFilter(), ZeroDateFilter()] if config.get('username') and config.get('password'): options['transport'] = HttpAuthenticated( username=config['username'], password=config['password'], timeout=300) return Client(**options)
def get_auth_stub(config): """ Given a config dict in the format: {'clientid': ... your ET client ID ..., 'clientsecret': ... your ET client secret ...} ... return an auth stub to be used when making requests. """ LOGGER.info("Generating auth stub...") params = { 'clientid': config['client_id'], 'clientsecret': config['client_secret'] } if config.get('tenant_subdomain'): # For S10+ accounts: https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-apis.meta/mc-apis/your-subdomain-tenant-specific-endpoints.htm params['authenticationurl'] = ( 'https://{}.auth.marketingcloudapis.com/v1/requestToken'.format( config['tenant_subdomain'])) params['soapendpoint'] = ( 'https://{}.soap.marketingcloudapis.com/Service.asmx'.format( config['tenant_subdomain'])) auth_stub = FuelSDK.ET_Client(params=params) transport = HttpAuthenticated( timeout=int(config.get('request_timeout', 900))) auth_stub.soap_client.set_options(transport=transport) LOGGER.info("Success.") return auth_stub
def add_client(): sec_type = self.config['sec_type'] if sec_type == security_def_type.basic_auth: transport = HttpAuthenticated(**self.suds_auth) elif sec_type == security_def_type.ntlm: transport = WindowsHttpAuthenticated(**self.suds_auth) elif sec_type == security_def_type.wss: security = Security() token = UsernameToken(self.suds_auth['username'], self.suds_auth['password']) security.tokens.append(token) client = Client(url, autoblend=True, wsse=security) if sec_type in (security_def_type.basic_auth, security_def_type.ntlm): client = Client(url, autoblend=True, transport=transport) # Still could be either none at all or WSS if not sec_type: client = Client(url, autoblend=True) self.client.queue.put(client) logger.debug('Adding Suds SOAP client to [%s]', url)
def preProcess(self, _edObject=None): EDPluginControl.preProcess(self) # Initializing webservices self.DEBUG("EDPluginBioSaxsISPyBModellingv1_0.preProcess") self.dataBioSaxsSample = self.dataInput.sample user = None password = "" if self.dataBioSaxsSample: if self.dataBioSaxsSample.login: user = self.dataBioSaxsSample.login.value password = self.dataBioSaxsSample.passwd.value self.URL = self.dataBioSaxsSample.ispybURL if not user: self.ERROR( "No login/password information in sample configuration. Giving up." ) self.setFailure() return # self.modellingResult = self.dataInput.saxsModelingResult if "http:" in self.URL: #print "OLD URL" self.URL = self.URL.replace("http:", "https:", 1) self.URL = self.URL.replace("8080", "", 1) # I don't trust in this authentication.... but it is going to work soon self.httpAuthenticatedToolsForBiosaxsWebService = HttpAuthenticated( username=user, password=password) self.client = Client( self.dataBioSaxsSample.ispybURL.value, transport=self.httpAuthenticatedToolsForBiosaxsWebService, cache=None)
def _create_basic_auth(self): """ Create the Basic auth """ basic = HttpAuthenticated(username=self.username, password=self.password) return basic
def get_device_ip(phone_name): #Disable HTTPS certificate validation check - not recommended for production if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context url = 'https://' + user_env.CUCM_LOCATION + ':8443/realtimeservice/services/RisPort?wsdl' print(url) tns = 'http://schemas.cisco.com/ast/soap/' imp = Import('http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add(tns) t = HttpAuthenticated(username=user_env.CUCM_USER, password=user_env.CUCM_PASSWORD) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) context = ssl.SSLContext() t1 = urllib.request.HTTPSHandler(context=context) t.urlopener = urllib.request.build_opener(t.handler, t1) c = Client(url, plugins=[ImportDoctor(imp)], transport=t) result = c.service.SelectCmDevice('', { 'SelectBy': 'Name', 'Status': 'Any', 'Class': 'Phone' }) total_phones = result['SelectCmDeviceResult']['TotalDevicesFound'] list_phones = result['SelectCmDeviceResult']["CmNodes"] print('number of devices found', total_phones) for node in result['SelectCmDeviceResult']['CmNodes']: for device in node['CmDevices']: if device["IpAddress"] is None: print("IP address not assigned for", device["Name"]) print("----------------") continue else: print("Name ", device["Name"], "IP Address: ", device["IpAddress"]) print("----------------") continue
def send(self, request): self.addenhanceddnsheaders(request) response = HttpAuthenticated.send(self, request) self.logenhanceddnsheaders(response) return response
def init_suds_lib(self, url): from suds.client import Client from suds.transport.https import HttpAuthenticated credentials = dict(username=tambov_api_login, password=tambov_api_password) transport_with_basic_auth = HttpAuthenticated(**credentials) self.client = Client(url, transport=transport_with_basic_auth)
def __init__(self, wsdl, settings): transport = HttpAuthenticated(username=settings.get('username'), password=settings.get('password'), timeout=DEFAULT_CLIENT_TIMEOUT) self.client = Client(wsdl, cache=SudsCache(), transport=transport, location=re.sub(r'\?wsdl$', '', wsdl))
def __init__( self, host=cfg.cucm_host, username=cfg.cucm_user, password=cfg.cucm_pass, timeout=30): self.host = host self.username = username self.password = password wsdl = 'https://' + host + \ ':8443/controlcenterservice2/services/ControlCenterServices?wsdl' location = 'https://' + host + \ ':8443/controlcenterservice2/services/ControlCenterServices' TNS = 'http://schemas.cisco.com/ast/soap' IMP = Import('http://schemas.xmlsoap.org/soap/encoding/') IMP.filter.add(TNS) t = HttpAuthenticated(username=self.username, password=self.password, timeout=timeout) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1) class SetPrefix(MessagePlugin): def marshalled(self, context): context.envelope[1][0][0].setPrefix('soap') self.client = Client( wsdl, location=location, username=username, password=password, cache=None, timeout=timeout, plugins=[ImportDoctor(IMP), SetPrefix()], transport=t )
def __init__( self, host=cfg.cucm_host, username=cfg.cucm_user, password=cfg.cucm_pass, cucm_version=cfg.cucm_version, timeout=10, wsdl="file://" + os.path.abspath( "axl_wsdl/{0}/AXLAPI.wsdl".format(cfg.cucm_version)), ): self.username = username self.password = password self.wsdl = wsdl self.host = host self.timeout = timeout t = HttpAuthenticated(username=self.username, password=self.password, timeout=timeout) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ses = urllib.request.HTTPCookieProcessor() ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1, ses) tns = 'http://schemas.cisco.com/ast/soap/' imp = Import('http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add(tns) self.client = Client( self.wsdl, location='https://{0}:8443/axl/'.format(host), faults=False, plugins=[ImportDoctor(imp)], transport=t ) self.service = self.client.service
def u2handlers(self): handlers = HttpAuthenticated.u2handlers(self) context = ssl._create_unverified_context() # add an HTTPS handler, using the custom context handlers.append(HTTPSHandler(context=context)) return handlers
def u2handlers(self): # use handlers from superclass handlers = HttpAuthenticated.u2handlers(self) # create custom ssl context, e.g. ctx = ssl.create_default_context(cafile=CERTIFICATE_LOCATION) # configure context as needed... ctx.check_hostname = False # add a https handler using the custom context handlers.append(HTTPSHandler(context=ctx)) return handlers
def __init__(self, cert, verify=True, **kwargs): """ Initialisation. Args: cert (tuple): Tuple containing the path to the cert file followed by the path to the key file as strings. verify (bool/str): Whether to verify the handled request url. If a string is given then this is used as the path to a CA_BUNDLE file or directory with certificates of trusted CAs. Note: If verify is set to a path to a directory, the directory must have been processed using the c_rehash utility supplied with OpenSSL. This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable (this may cause pip to fail to validate against PyPI). """ HttpAuthenticated.__init__(self, **kwargs) self.cert = cert self.verify = verify
def setup_connection(): home = expanduser("~") credentials = os.path.join(home, 'scheduling.ini') cf = ConfigParser.ConfigParser() cf.read(credentials) username = cf.get('credentials', 'username') password = cf.get('credentials', 'password') beamline = cf.get('settings', 'beamline') # Uncomment one if using ANL INTERNAL or EXTERNAL network #base = cf.get('hosts', 'internal') base = cf.get('hosts', 'external') result = urllib2.install_opener(urllib2.build_opener(HTTPSHandlerV3())) logging.raiseExceptions = 0 beamlineScheduleServiceURL = base + \ 'beamlineScheduleService/beamlineScheduleWebService.wsdl' runScheduleServiceURL = base + \ 'runScheduleService/runScheduleWebService.wsdl' try: credentials = dict(username=username, password=password) t = HttpAuthenticated(**credentials) if debug: print t.u2handlers() print t.credentials() runScheduleServiceClient = Client(runScheduleServiceURL) runScheduleServiceClient.options.cache.setduration(seconds=10) result = setSoapHeader(runScheduleServiceClient, username, password) beamlineScheduleServiceClient = Client(beamlineScheduleServiceURL) beamlineScheduleServiceClient.options.cache.setduration(seconds=10) result = setSoapHeader( beamlineScheduleServiceClient, username, password) except Exception, ex: print "CANNOT OPEN SERVICES:" + str(ex) raise exit(-1)
def __init__(self, username, password, wsdl, cucm, cucm_version): """ :param username: axl username :param password: axl password :param wsdl: wsdl file location :param cucm: UCM IP address :param cucm_version: UCM version example usage: >>> from axl.foley import AXL >>> wsdl = 'file:///path/to/wsdl/axlsqltoolkit/schema/10.5/AXLAPI.wsdl' >>> ucm = AXL('axl_user', 'axl_pass' wsdl, '192.168.200.10') """ self.username = username self.password = password self.wsdl = wsdl self.cucm = cucm self.cucm_version = cucm_version tns = 'http://schemas.cisco.com/ast/soap/' imp = Import('http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add(tns) t = HttpAuthenticated(username=self.username, password=self.password) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) ssl_def_context = ssl.create_default_context() ssl_def_context.check_hostname = False ssl_def_context.verify_mode = ssl.CERT_NONE if float(cucm_version) <= 8.5: ssl_def_context.set_ciphers('HIGH:!DH:!aNULL') t1 = urllib.request.HTTPSHandler(context=ssl_def_context) t.urlopener = urllib.request.build_opener(t.handler, t1) self.client = Client(self.wsdl, location='https://{0}:8443/axl/'.format(cucm), faults=False, plugins=[ImportDoctor(imp)], transport=t)
def getPendingNotificationDetails(self, request_id, debug=False): authenticated = HttpAuthenticated(username=self.getUserId(), password=self.getPassword()) result = suds.client.Client( url=self.getProperty("tracking_url_string"), transport=authenticated).service.getPendingNotificationDetails( request_id) return { "status": str(result.status), "notification_status": str(result.notificationStatus), "detail": repr(result) }
def _access_code_method_(self, request, action, access_code='', is_post=True): result = None if self.method == 'SOAP': if self.debug: logging.basicConfig(level=logging.DEBUG) logging.getLogger('suds.client').setLevel(logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.INFO) # Create AUTH credentials credentials = dict(username=self.username, password=self.password) t = HttpAuthenticated(**credentials) # Read WSDL wsdl_url = '%s?WSDL' % self.url['SOAP'] client = Client(wsdl_url, transport=t) # Send request if action == 'CREATE': result = client.service.CreateAccessCode(request) else: result = client.service.GetAccessCodeResult(request) elif self.method == 'REST': # Create URL for REST rest_url = self.url['REST'] rest_url += 's' if action == 'CREATE' else '/%s' % str(access_code) result = self.__post_to_rapidapi__(rest_url, request, is_post) elif self.method == 'POST': is_post = True if self.format == 'XML': result = self.__post_to_rapidapi__( self.url['POST']['XML'][action], request, is_post) else: result = self.__post_to_rapidapi__( self.url['POST']['JSON'][action], request, is_post) elif self.method == 'RPC': if self.format == 'XML': result = self.__post_to_rapidapi__(self.url['RPC']['XML'], request, is_post) else: result = self.__post_to_rapidapi__(self.url['RPC']['JSON'], request, is_post) return result
def risport_request(): phone_list = [] #Disable HTTPS certificate validation check - not recommended for production if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context url = 'https://' + user_env.CUCM_LOCATION + ':8443/realtimeservice/services/RisPort?wsdl' tns = 'http://schemas.cisco.com/ast/soap/' imp = Import('http://schemas.xmlsoap.org/soap/encoding/', 'http://schemas.xmlsoap.org/soap/encoding/') imp.filter.add(tns) t = HttpAuthenticated(username=user_env.CUCM_USER, password=user_env.CUCM_PASSWORD) t.handler = urllib.request.HTTPBasicAuthHandler(t.pm) context = ssl.SSLContext() t1 = urllib.request.HTTPSHandler(context=context) t.urlopener = urllib.request.build_opener(t.handler, t1) c = Client(url, plugins=[ImportDoctor(imp)], transport=t) result = c.service.SelectCmDevice('', { 'SelectBy': 'Name', 'Status': 'Any', 'Class': 'Phone' }) total_phones = result['SelectCmDeviceResult']['TotalDevicesFound'] list_phones = result['SelectCmDeviceResult']["CmNodes"] for node in result['SelectCmDeviceResult']['CmNodes']: for device in node['CmDevices']: phone_list.append(device) return phone_list
def soap_client(): """ SoapClient to EVM based on base_url""" username = conf.credentials['default']['username'] password = conf.credentials['default']['password'] url = '{}/vmdbws/wsdl/'.format(store.base_url) transport = HttpAuthenticated(username=username, password=password) imp = Import('http://schemas.xmlsoap.org/soap/encoding/') doc = ImportDoctor(imp) client = MiqClient(url, transport=transport, doctor=doc) return client
def getTransport(): transport = None logger = UtilsLogging.getLogger() if not "ISPyB_user" in os.environ: logger.error("No ISPyB user name defined as environment variable!") elif not "ISPyB_pass" in os.environ: logger.error("No ISPyB password defined as environment variable!") else: ispybUserName = os.environ["ISPyB_user"] ispybPassword = os.environ["ISPyB_pass"] transport = HttpAuthenticated(username=ispybUserName, password=ispybPassword) return transport
def __createClient(self, ciType): "@types: str -> suds.Client" credentials = dict(username=self.__connectionDataManager.getUsername(), password=self.__connectionDataManager.getPassword()) proxy = self.__connectionDataManager.getProxy() if proxy: credentials['proxy'] = {'http': proxy, 'https': proxy} t = HttpAuthenticated(**credentials) url = '%s/%s.do?displayvalue=all&wsdl' % ( self.__connectionDataManager.getConnectionUrl(), ciType) return Client(url, transport=t, cache=None)
def u2handlers(self): handlers = HttpAuthenticated.u2handlers(self) handlers.append(HTTPSHandlerNoVerify()) return handlers
def __init__(self,*args,**kwargs): HttpAuthenticated.__init__(self,*args,**kwargs) self.last_headers = None
def __init__(self, **kwargs): self.cert = kwargs.pop('cert', None) HttpAuthenticated.__init__(self, **kwargs)
def send(self,request): result = HttpAuthenticated.send(self,request) self.last_headers = result.headers return result
def u2handlers(self): handlers = [ urllib2.HTTPSHandler(context=ssl._create_unverified_context()) ] handlers.extend(HttpAuthenticated.u2handlers(self)) return handlers
def __init__(self, cert, **kwargs): self.cert = cert # super won't work because not using new style class HttpAuthenticated.__init__(self, **kwargs)