class Transport(object): def __init__(self, cache=NotSet, timeout=300, verify=True, http_auth=None, **post_xml_format_options): self.cache = SqliteCache() if cache is NotSet else cache self.timeout = timeout self.verify = verify self.http_auth = http_auth self.logger = logging.getLogger(__name__) self.post_xml_format_options = post_xml_format_options self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth self.session.headers['User-Agent'] = ( 'Zeep/%s (www.python-zeep.org)' % (get_version())) def create_session(self): return requests.Session() def load(self, url): if not url: raise ValueError("No url given to load") scheme = urlparse(url).scheme if scheme in ('http', 'https'): if self.cache: response = self.cache.get(url) if response: return bytes(response) response = self.session.get(url, timeout=self.timeout) response.raise_for_status() if self.cache: self.cache.add(url, response.content) return response.content elif scheme == 'file': if url.startswith('file://'): url = url[7:] with open(url, 'rb') as fh: return fh.read() def post(self, address, message, headers): self.logger.debug("HTTP Post to %s:\n%s", address, message) response = self.session.post(address, data=message, headers=headers) self.logger.debug( "HTTP Response from %s (status: %d):\n%s", address, response.status_code, response.content) return response def post_xml(self, address, message, headers): message = etree_to_string(message, **self.post_xml_format_options) return self.post(address, message, headers) def get(self, address, params, headers): response = self.session.get(address, params=params, headers=headers) return response
class Transport(object): def __init__(self, cache=NotSet, timeout=300, verify=True, http_auth=None): self.cache = SqliteCache() if cache is NotSet else cache self.timeout = timeout self.verify = verify self.http_auth = http_auth self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth def create_session(self): return requests.Session() def load(self, url): if self.cache: response = self.cache.get(url) if response: return bytes(response) response = self.session.get(url, timeout=self.timeout) response.raise_for_status() if self.cache: self.cache.add(url, response.content) return response.content def post(self, address, message, headers): response = self.session.post(address, data=message, headers=headers) return response def get(self, address, params, headers): response = self.session.get(address, params=params, headers=headers) return response
def __init__(self, cache=NotSet, timeout=300, operation_timeout=None, verify=True, http_auth=None): """The transport object handles all communication to the SOAP server. :param cache: The cache object to be used to cache GET requests :param timeout: The timeout for loading wsdl and xsd documents. :param operation_timeout: The timeout for operations (POST/GET). By default this is None (no timeout). :param verify: Boolean to indicate if the SSL certificate needs to be verified. :param http_auth: HTTP authentication, passed to requests. """ self.cache = SqliteCache() if cache is NotSet else cache self.load_timeout = timeout self.operation_timeout = None self.verify = verify self.http_auth = http_auth self.logger = logging.getLogger(__name__) self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth self.session.headers['User-Agent'] = ('Zeep/%s (www.python-zeep.org)' % (get_version()))
def __init__(self, cache=NotSet, timeout=300, verify=True, http_auth=None): self.cache = SqliteCache() if cache is NotSet else cache self.timeout = timeout self.verify = verify self.http_auth = http_auth self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth
def __init__(self, cache=NotSet, timeout=300, verify=True, http_auth=None): self.cache = SqliteCache() if cache is NotSet else cache self.timeout = timeout self.verify = verify self.http_auth = http_auth self.logger = logging.getLogger(__name__) self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth self.session.headers['User-Agent'] = ('Zeep/%s (www.python-zeep.org)' % (get_version()))
class Transport(object): def __init__(self, cache=NotSet, timeout=300, verify=True, http_auth=None): self.cache = SqliteCache() if cache is NotSet else cache self.timeout = timeout self.verify = verify self.http_auth = http_auth self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth self.session.headers['User-Agent'] = ( 'Zeep/%s (www.python-zeep.org)' % (get_version())) def create_session(self): return requests.Session() def load(self, url): if not url: raise ValueError("No url given to load") scheme = urlparse(url).scheme if scheme in ('http', 'https'): if self.cache: response = self.cache.get(url) if response: return bytes(response) response = self.session.get(url, timeout=self.timeout) response.raise_for_status() if self.cache: self.cache.add(url, response.content) return response.content elif scheme == 'file': if url.startswith('file://'): url = url[7:] with open(url, 'rb') as fh: return fh.read() def post(self, address, message, headers): response = self.session.post(address, data=message, headers=headers) return response def get(self, address, params, headers): response = self.session.get(address, params=params, headers=headers) return response
def __init__(self, username, password, server_ip, version='12.5', tls_verify=True, timeout=10, logging_enabled=False): self.session = Session() self.session.auth = HTTPBasicAuth(username, password) self.session.verify = tls_verify filedir = os.path.dirname(__file__) self.cache = SqliteCache(path=Path(tempfile.gettempdir()+'/sqlite_{0}.db'.format(server_ip)), timeout=60) if version == '12.5': self.wsdl = os.path.join(filedir, 'schema/12.5/AXLAPI.wsdl') elif version == '12.0': self.wsdl = os.path.join(filedir, 'schema/12.0/AXLAPI.wsdl') elif version == '11.5': self.wsdl = os.path.join(filedir, 'schema/11.5/AXLAPI.wsdl') elif version == '11.0': self.wsdl = os.path.join(filedir, 'schema/11.0/AXLAPI.wsdl') elif version == '10.5': self.wsdl = os.path.join(filedir, 'schema/10.5/AXLAPI.wsdl') elif version == '10.0': self.wsdl = os.path.join(filedir, 'schema/10.0/AXLAPI.wsdl') else: self.wsdl = os.path.join(filedir, 'schema/12.5/AXLAPI.wsdl') self.client = Client(wsdl=self.wsdl, plugins=[self.history], transport=Transport(timeout=timeout, operation_timeout=timeout, cache=self.cache, session=self.session)) self.service = self.client.create_service("{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", "https://{0}:8443/axl/".format(server_ip)) if logging_enabled: enable_logging()
def __init__(self, url, username, password): self.IdToPropType = dict() self.IdtoObjectType = dict() self.PropIdToDict = dict() self.RNEFnameToPropType = dict() from requests.auth import HTTPBasicAuth from requests import Session from zeep.cache import SqliteCache from zeep.transports import Transport session = Session() session.auth = HTTPBasicAuth(username, password) transport = Transport(cache=SqliteCache(), session=session) from zeep import Client, Settings settings = Settings(strict=False, xml_huge_tree=True) #settings = zeep.Settings(extra_http_headers={'Authorization': 'Bearer ' + token}) self.logger = configure_logging(logging.getLogger(__name__)) try: self.SOAPclient = Client(wsdl=url, transport=transport, settings=settings) self.__load_model() print('Connected to Resnet API server:\n%s as %s' % (url, username)) except Exception as error: self.logger.error( "Pathway Studio server connection failed: {error}".format( error=error)) raise ConnectionError( f"Server connection failed. Wrong or inaccessible url: {url}" ) from None
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') """ wsdl = 'https://' + cucm + ':8443/realtimeservice2/services/RISService70?wsdl' session = Session() session.verify = False session.auth = HTTPBasicAuth(username, password) settings = Settings(strict=False, xml_huge_tree=True) transport = Transport(session=session, timeout=10, cache=SqliteCache()) ris_client = Client(wsdl, settings=settings, transport=transport) self.wsdl = wsdl self.username = username self.password = password self.cucm = cucm self.cucm_version = cucm_version self.UUID_PATTERN = re.compile( r'^[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}$', re.IGNORECASE) self.client = ris_client.create_service( "{http://schemas.cisco.com/ast/soap}RisBinding", f"https://{cucm}:8443/realtimeservice2/services/RISService70")
def __init__(self, username, password, cucm, cucm_version): cwd = os.path.dirname(os.path.abspath(__file__)) if os.name == "posix": wsdl = Path(f"{cwd}/schema/{cucm_version}/AXLAPI.wsdl").as_uri() else: wsdl = str( Path(f"{cwd}/schema/{cucm_version}/AXLAPI.wsdl").absolute()) session = Session() session.verify = False session.auth = HTTPBasicAuth(username, password) settings = Settings(strict=False, xml_huge_tree=True, xsd_ignore_sequence_order=True) transport = Transport(session=session, timeout=10, cache=SqliteCache()) axl_client = Client(wsdl, settings=settings, transport=transport) self.wsdl = wsdl self.username = username self.password = password self.wsdl = wsdl self.cucm = cucm self.cucm_version = cucm_version self.UUID_PATTERN = re.compile( r"^[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}$", re.IGNORECASE) self.client = axl_client.create_service( "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", f"https://{cucm}:8443/axl/", )
def main(api_key, mastr_number, limit, step, start, filter_type, units_file): wsdl = 'https://www.marktstammdatenregister.de/MaStRAPI/wsdl/mastr.wsdl' transport = Transport(cache=SqliteCache()) settings = Settings(strict=False, xml_huge_tree=True) client = Client(wsdl=wsdl, transport=transport, settings=settings) client_bind = client.bind('Marktstammdatenregister','Anlage') writer = csv.DictWriter(units_file, field_names) writer.writeheader() total = total_filtered = 0 logging.getLogger('zeep').setLevel(logging.CRITICAL) for current_step in range(start, math.ceil(limit/step)): try: try: c = client_bind.GetListeAlleEinheiten(apiKey=api_key, marktakteurMastrNummer=mastr_number, startAb=step*current_step, limit=step) respond = serialize_object(c) except Fault as e: print('Probably reached the end, saving file: ' + e.message) break filtered = [dict(x) for x in respond['Einheiten'] if x['Einheittyp'] == filter_type] print(f'[{current_step}] Fetched {len(respond["Einheiten"])} entries out of which {len(filtered)} was used') writer.writerows(filtered) total += len(respond["Einheiten"]) total_filtered += len(filtered) except KeyboardInterrupt: print('Aborting fetching!') break print(f'Fetched in total {total} entries which {total_filtered} was used.')
def read_multiple_soap_records(self, soap_object, filter_field_string, filter_type_string, filter_data=[{ 'property': '', 'value': '' }]): session = Session() session.auth = HTTPBasicAuth(self.nav_user, self.nav_password) soap_service_url = self.nav_soap_service + self.nav_company + "/Page/" + soap_object client = Client(soap_service_url, transport=Transport(session=session, cache=SqliteCache())) filter_field = client.get_type(f"ns0:{filter_field_string}") filter_type = client.get_type(f"ns0:{filter_type_string}") # Build the search filters from the filter_data # Notice the default values for the filter_data arguement are empty # so we bring back all of the records as a default filters = [ filter_type(filter_field(item['property']), item['value']) for item in filter_data ] # setService tells the service how many records to return soap_response = client.service.ReadMultiple(filter=filters, setSize=0) serialized_response = serialize_object(soap_response) return serialized_response
def __init__( self, client_id: str, client_secret: str, base_url: str, settings: Optional[Settings] = None, storage_url: Optional[str] = None, timeout: Optional[int] = 60, ) -> None: """Init function.""" self.base_url = base_url self.client_id = client_id self.client_secret = client_secret self._cache = [] self._settings = settings self._session = Session() self._session.auth = HTTPBasicAuth(self.client_id, self.client_secret) self.storage_url = storage_url cache = None if self.storage_url: cache = SqliteCache(path=storage_url, timeout=timeout) try: self._client = Client( self.base_url, transport=Transport(session=self._session, cache=cache), settings=self._settings, ) except requests.exceptions.HTTPError as e: if e.response.status_code == 401: raise Unauthorized(e) raise BadRequest(e) except requests.exceptions.ConnectionError: raise ResourceDoesNotExist()
def main(): transport = Transport(cache=SqliteCache()) client = Client('http://localhost:8000/?wsdl', transport=transport) print('#-=-# Biblioteca Musical #-=-#') while True: print('\nMENU:') print('1) Inserir album') print('2) Listar albuns') print('0) Sair') op = str(input('> ')) if op.strip() == '1': #album = novoAlbum() print client.service.addAlbumInData() elif op.strip() == '2': ls = client.service.getAlbuns() for i in range(len(ls)): print '=====================================' print 'ID:', ls[i]["_id"] print 'Titulo:', ls[i]["titulo"] print 'Artista:', ls[i]["artista"] print 'Gravadora:', ls[i]["gravadora"] print 'Ano:', ls[i]["ano"] elif op.strip() == '0': break else: print('Opcao invalida! insira novamente.')
def main(): path = Path('C:\\shared\\API\\credentials') wsdl = 'file://C://shared//API//axlsqltoolkit//schema//11.5//AXLAPI.wsdl' platform = 'CUCM' role = 'rwx' urllib3.disable_warnings(InsecureRequestWarning) server = path / REGION / platform / ('fqdn' + '.txt') binding_name = '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding' address = 'https://{fqdn}:8443/axl/'.format(fqdn=read(server)[0]) session = Session() session.verify = False session.auth = HTTPBasicAuth( read(file(path, platform, role)[0])[0], crypto(file(path, platform, role)[1], file(path, platform, role)[2])) transport = Transport(cache=SqliteCache(), session=session, timeout=60) client = Client(wsdl=wsdl, transport=transport) axl = client.create_service(binding_name, address) for items in listCSS(axl, CSS)['return']['css']: print('\n####################Before adding the partition') print(getCSS(axl, items['name'])['return']['css']['name']) print(getCSS(axl, items['name'])['return']['css']['clause']) print('Adding the partition {}'.format(PT)) #addptCSS(axl, items['name'], PT, '0') #rmptCSS(axl, items['name'], PT, '0') print('********************After adding the partition {}'.format(PT)) print(getCSS(axl, items['name'])['return']['css']['name']) print(getCSS(axl, items['name'])['return']['css']['clause'])
def populate_transport(): transport = None try: session = None if api.config.sslVerificationPath: session = Session() session.verify = api.config.sslVerificationPath if api.config.httpAuthUser: user = api.config.httpAuthUser password = api.config.httpAuthPassword if not session: session = Session() session.auth = HTTPBasicAuth(user, password) session_timeout = None if api.config.sessionTimeout: session_timeout = int(api.config.sessionTimeout) cache_path = None if api.config.cachePath: cache_path = api.config.cachePath if session or session_timeout or cache_path: transport = Transport( cache=SqliteCache(path=cache_path) if cache_path else None, timeout=session_timeout if session_timeout else 300, session=session) except Exception as excp: api.send("debug", str(excp)) return transport
def setupserviceconnection(self, ip): #print (threading.currentThread().getName()) ## setup Session session = Session() session.verify = False session.auth = HTTPBasicAuth(self.axluser, self.axlpass) transport = CustomTransport(cache=SqliteCache(), session=session, timeout=60) history = HistoryPlugin() # import required WSDL's servicewsdl = 'file://' + os.getcwd() + '//Files//ServiceWSDL.wsdl' SERVICE_BINDING_NAME = "{http://cisco.com/ccm/serviceability/soap/ControlCenterServices/}ControlCenterServicesBinding" SERVICE_ADDR = "https://" + ip + ":8443/controlcenterservice/services/ControlCenterServicesPort" try: print("Fetching Services Status from " + ip) client = Client(wsdl=servicewsdl, transport=transport, plugins=[history]) Servicexl = client.create_service(SERVICE_BINDING_NAME, SERVICE_ADDR) result = Servicexl.soapGetServiceStatus(['']) return result except (Fault, Exception) as error: print(error) return None
def __init__(self, username, password, server_ip, service, tls_verify=True): dir = os.path.dirname(__file__) if (service == 'HardwareInformation'): wsdl = os.path.join(dir, 'paws/hardware_information_service.wsdl') binding = "{http://services.api.platform.vos.cisco.com}HardwareInformationServiceSoap11Binding" endpoint = "https://{0}:8443/platform-services/services/HardwareInformationService.HardwareInformationServiceHttpsSoap11Endpoint/".format( server_ip) elif (service == 'ClusterNodesService'): wsdl = 'https://{0}:8443/platform-services/services/ClusterNodesService?wsdl'.format( server_ip) binding = "{http://services.api.platform.vos.cisco.com}ClusterNodesServiceHttpBinding" endpoint = "https://{0}:8443/platform-services/services/ClusterNodesService.ClusterNodesServiceHttpsEndpoint/".format( server_ip) self.session = Session() self.session.auth = HTTPBasicAuth(username, password) self.session.verify = tls_verify self.cache = SqliteCache(path='/tmp/sqlite_logcollection.db', timeout=60) self.client = Client(wsdl=wsdl, transport=Transport(cache=self.cache, session=self.session)) self.service = self.client.create_service(binding, endpoint) enable_logging()
def sql_getmodel(): path = Path('C:\\shared\\API\\credentials') wsdl = 'file://C://shared//API//axlsqltoolkit//schema//11.5//AXLAPI.wsdl' platform = 'CUCM' role = 'r' urllib3.disable_warnings(InsecureRequestWarning) server = path / REGION / platform / ('fqdn' + '.txt') binding_name = '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding' address = 'https://{fqdn}:8443/axl/'.format(fqdn=read(server)[0]) session = Session() session.verify = False session.auth = HTTPBasicAuth(read(file(path, platform, role)[0])[0], crypto(file(path, platform, role)[1], file(path, platform, role)[2])) transport = Transport(cache=SqliteCache(), session=session, timeout=60) client = Client(wsdl=wsdl, transport=transport) axl = client.create_service(binding_name, address) sql_statement = \ "SELECT " \ "name, enum " \ "FROM " \ "typemodel " axl_resp = axl.executeSQLQuery(sql=sql_statement) table = [OrderedDict((element.tag, element.text) for element in row) for row in serialize_object(axl_resp)["return"]["row"]] locale = [(items['name'], items['enum']) for items in table] dict_variable = {enum: name for (name, enum) in locale} return dict_variable
def connector(CUCM_IP, AXL_Username, AXL_Password, CUCM_Version='11.5', debug=False): """Returns a standalone connector. No class methods. For testing purposes""" WSDL = f'schema/{CUCM_Version}/AXLAPI.wsdl' if ('9.' in CUCM_Version): urllib3.disable_warnings() urllib3.util.ssl_.DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL' WSDL = 'schema/9.1/AXLAPI.wsdl' try: urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST += 'HIGH:!DH:!aNULL' except AttributeError: pass else: urllib3.disable_warnings(InsecureRequestWarning) BINDING_NAME = "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding" ADDRESS = "https://{ip}:8443/axl/".format(ip=CUCM_IP) session = Session() session.verify = False session.auth = HTTPBasicAuth(AXL_Username, AXL_Password) transport = Transport(cache=SqliteCache(), session=session, timeout=10) if debug: client = Client(wsdl=WSDL, transport=transport, plugins=[ZeepDebugPlugin()]) else: client = Client(wsdl=WSDL, transport=transport) return client.create_service(BINDING_NAME, ADDRESS)
def main(): path = Path('C:\\shared\\API\\credentials') wsdl = 'file://C://shared//API//axlsqltoolkit//schema//11.5//AXLAPI.wsdl' platform = 'CUCM' role = 'r' urllib3.disable_warnings(InsecureRequestWarning) server = path / REGION / platform / ('fqdn' + '.txt') binding_name = '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding' address = 'https://{fqdn}:8443/axl/'.format(fqdn=read(server)[0]) session = Session() session.verify = False session.auth = HTTPBasicAuth( read(file(path, platform, role)[0])[0], crypto(file(path, platform, role)[1], file(path, platform, role)[2])) transport = Transport(cache=SqliteCache(), session=session, timeout=60) client = Client(wsdl=wsdl, transport=transport) axl = client.create_service(binding_name, address) udps = [ udps['name'] for udps in listudp(axl, UDP)['return']['deviceProfile'] ] phones = [ phones['name'] for phones in listphone(axl, PHONE)['return']['phone'] ] for udp in udps: if getudp(axl, udp)['return']['deviceProfile']['speeddials'] is None: pass else: sddirn = [ sddirn['dirn'] for sddirn in getudp(axl, udp)['return'] ['deviceProfile']['speeddials']['speeddial'] ] upddesc = getudp(axl, udp)['return']['deviceProfile']['description'] for sd in sddirn: if sd == RMSD: print('User Profile Name: ' + udp + ' with description ' + upddesc + ' has the speed dial ' + RMSD) else: pass for phone in phones: if getphone(axl, phone)['return']['phone']['speeddials'] is None: pass else: sddirn = [ sddirn['dirn'] for sddirn in getphone(axl, phone)['return'] ['phone']['speeddials']['speeddial'] ] phonedesc = getphone(axl, phone)['return']['phone']['description'] for sd in sddirn: if sd == RMSD: print('Phone Name: ' + phone + ' with description ' + phonedesc + ' has the speed dial ' + RMSD) break else: pass
def __init__(self, cache=NotSet, timeout=300, operation_timeout=None, verify=True, http_auth=None): self.cache = SqliteCache() if cache is NotSet else cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.http_verify = verify self.http_auth = http_auth self.http_headers = { 'User-Agent': 'Zeep/%s (www.python-zeep.org)' % (get_version()) } self.session = self.create_session()
def __init__(self, *args, **kwargs): # Don't use setdefault since we want to lazily init the Transport cls from zeep.cache import SqliteCache kwargs['transport'] = ( kwargs.get('transport') or Transport(cache=SqliteCache())) super(CachingClient, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): # Don't use setdefault since we want to lazily init the Transport cls from zeep.cache import SqliteCache kwargs["transport"] = kwargs.get("transport") or Transport(cache=SqliteCache()) super().__init__(*args, **kwargs)
def __init__(self, version=DEFAULT_B2B_VERSION, service_group="FlightServices", dataset=DEFAULT_DATASET, how_to_auth='proxy', *args, **kwargs): self.wsdl = '' self.service_group = service_group self.version = version self.session = Session() self.available_services = [] self.available_operations = {} self._default_params_for_queries = { 'requestedFlightFields': [], 'dataset': get_dataset(dataset), 'trafficType': 'LOAD', 'includeProposalFlights': True, 'includeForecastFlights': True, 'sendTime': utils.sendTime(), } self.params_for_queries = self._default_params_for_queries # ------------- certificat ou proxy ? ------------- # if how_to_auth == 'cert': # Si authentification par certificat self.wsdl = f"data/wsdl/{self.version}/{self.service_group}_PREOPS_{self.version}.wsdl" self.session.cert = (glob.glob("cert/crt.pem")[0], glob.glob("cert/key.pem")[0]) elif how_to_auth == 'proxy': # Si authentification via proxy (défaut) NM_B2B_API_KEY_ID = os.environ.get( 'NM_B2B_API_KEY_ID') # default is None NM_B2B_API_SECRET = os.environ.get( 'NM_B2B_API_SECRET') # default is None if not NM_B2B_API_KEY_ID or not NM_B2B_API_SECRET: print( f"Impossible de définir un couple clé/pass pour le proxy b2b.\ Vérifiez que NM_B2B_API_KEY_ID et NM_B2B_API_SECRET sont bien définis dans votre environnement." ) exit(1) self.wsdl = WSDL_PROXY + self.service_group + "_PREOPS_" + version + ".wsdl" self.session.auth = HTTPBasicAuth(NM_B2B_API_KEY_ID, NM_B2B_API_SECRET) else: print( "Le mode d'authentification que vous avez spécifié n'existe pas (pour l'instant : 'cert' ou 'proxy')." ) exit(1) # ------------- self.cache = SqliteCache(path='./data/sqlite.db') self.transport = Transport(session=self.session, cache=self.cache) self.conf = {'wsdl': self.wsdl, 'transport': self.transport} self.tmp_data = None
def getAuthenticationWithServer(username, password, wsdl): disable_warnings(InsecureRequestWarning) session = Session() session.verify = False session.auth = HTTPBasicAuth(username, password) transport = Transport(cache=SqliteCache(), session=session, timeout=20) history = HistoryPlugin() ssl._create_default_https_context = ssl._create_unverified_context return (Client(wsdl=wsdl, transport=transport, plugins=[history]))
def main(): path = Path('C:\\shared\\API\\credentials') wsdl = 'file://C://shared//API//axlsqltoolkit//schema//11.5//AXLAPI.wsdl' platform = 'CUCM' role = 'rwx' urllib3.disable_warnings(InsecureRequestWarning) server = path / REGION / platform / ('fqdn' + '.txt') binding_name = '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding' address = 'https://{fqdn}:8443/axl/'.format(fqdn=read(server)[0]) session = Session() session.verify = False session.auth = HTTPBasicAuth( read(file(path, platform, role)[0])[0], crypto(file(path, platform, role)[1], file(path, platform, role)[2])) transport = Transport(cache=SqliteCache(), session=session, timeout=60) client = Client(wsdl=wsdl, transport=transport) axl = client.create_service(binding_name, address) ##Search and Update Phone for phoneitem in listPhone(axl, PHONE)['return']['phone']: for template in readCSV(TEMPLATE): if template[0] == phoneitem['phoneTemplateName']['_value_1']: print('current phone template', phoneitem['phoneTemplateName']['_value_1']) print('new phone template', template[1]) print('affected device', phoneitem['name']) updatePhone(axl, phoneitem['name'], template[1]) print( '#####The End#########The End#########The End#########The End####' ) else: pass ##Search and Update UDP for udpitem in listUDP(axl, UDP)['return']['deviceProfile']: for template in readCSV(TEMPLATE): if template[0] == udpitem['phoneTemplateName']['_value_1']: print('current phone template', udpitem['phoneTemplateName']['_value_1']) print('new phone template', template[1]) print('affected device', udpitem['name']) updateUDP(axl, udpitem['name'], template[1]) try: for em_items in sql_get_em_items(axl, udpitem['name']): print(em_items['phone']) print(em_items['userid']) em_logout(axl, em_items['phone']) em_login(axl, udpitem['name'], em_items['phone'], em_items['userid']) except TypeError: pass print( '#####The End#########The End#########The End#########The End####' ) else: pass
def client_soap(config_file): 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 + '/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)) # history shows http_headers global history history = HistoryPlugin() # The first step is to create a SOAP client session session = Session() # We avoid certificate verification by default, but you can uncomment and set # your certificate here, and comment out the False setting #session.verify = CERT session.verify = False session.auth = HTTPBasicAuth(csp_username, csp_password) transport = Transport(session=session, timeout=10, cache=SqliteCache()) # strict=False is not always necessary, but it allows zeep to parse imperfect XML settings = Settings(strict=False, xml_huge_tree=True) try: csp_soap_client = Client(wsdl, settings=settings, transport=transport, plugins=[MyLoggingPlugin(),history], ) service = csp_soap_client.create_service("{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", csp_location) 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.') return service
def __init__(self, username, password, hostname, tls_verify=True, timeout=10): self.last_exception = None wsdl = f'https://{hostname}/perfmonservice/services/PerfmonPort?wsdl' session = Session() session.verify = tls_verify session.auth = HTTPBasicAuth(username, password) cache = SqliteCache() transport = Transport(cache=cache, session=session, timeout=timeout, operation_timeout=timeout) history = HistoryPlugin() self.client = Client(wsdl=wsdl, transport=transport, plugins=[history])
def change_authenticator(settings: CzNiaAppSettings, data: Dict[str, str]): """Write a change to the VIP.""" transport = Transport(cache=SqliteCache(path=settings.CACHE_PATH, timeout=settings.CACHE_TIMEOUT), timeout=settings.TRANSPORT_TIMEOUT) fp_assertion = _call_identity(settings, transport) sub_assertion = _call_federation(settings, transport, fp_assertion) # Create the request message = ChangeAuthenticatorMessage(data) body = _call_submission(settings, transport, sub_assertion, message) return message.unpack(body)
def get_pseudonym(settings: CzNiaAppSettings, user_data: Dict[str, Any]) -> str: """Get pseudonym from NIA servers for given user data.""" transport = Transport(cache=SqliteCache(path=settings.CACHE_PATH, timeout=settings.CACHE_TIMEOUT), timeout=settings.TRANSPORT_TIMEOUT) fp_assertion = _call_identity(settings, transport) sub_assertion = _call_federation(settings, transport, fp_assertion) message = IdentificationMessage(user_data) body = _call_submission(settings, transport, sub_assertion, message) return message.unpack(body)
def __init__(self, cache=NotSet, timeout=300, verify=True, http_auth=None): self.cache = SqliteCache() if cache is NotSet else cache self.timeout = timeout self.verify = verify self.http_auth = http_auth self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth self.session.headers['User-Agent'] = ( 'Zeep/%s (www.python-zeep.org)' % (get_version()))
def soapinfo(CUCM_URL, USERNAME, PASSWD, WSDL_URL): #Create SOAP Session session = Session() session.verify = False session.auth = HTTPBasicAuth(USERNAME, PASSWD) transport = Transport(session=session, timeout=10, cache=SqliteCache()) settings = Settings(strict=False, xml_huge_tree=True) client = Client(WSDL_URL, settings=settings, transport=transport) service = client.create_service( "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", CUCM_URL) return service
def __init__(self, cache=NotSet, timeout=300, verify=True, http_auth=None, **post_xml_format_options): self.cache = SqliteCache() if cache is NotSet else cache self.timeout = timeout self.verify = verify self.http_auth = http_auth self.logger = logging.getLogger(__name__) self.post_xml_format_options = post_xml_format_options self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth self.session.headers['User-Agent'] = ( 'Zeep/%s (www.python-zeep.org)' % (get_version()))
def __init__(self, cache=NotSet, timeout=300, operation_timeout=None, verify=True, http_auth=None): """The transport object handles all communication to the SOAP server. :param cache: The cache object to be used to cache GET requests :param timeout: The timeout for loading wsdl and xsd documents. :param operation_timeout: The timeout for operations (POST/GET). By default this is None (no timeout). :param verify: Boolean to indicate if the SSL certificate needs to be verified. :param http_auth: HTTP authentication, passed to requests. """ self.cache = SqliteCache() if cache is NotSet else cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.http_verify = verify self.http_auth = http_auth self.http_headers = { 'User-Agent': 'Zeep/%s (www.python-zeep.org)' % (get_version()) } self.session = self.create_session()
class Transport(object): def __init__(self, cache=NotSet, timeout=300, verify=True, http_auth=None): self.cache = SqliteCache() if cache is NotSet else cache self.timeout = timeout self.verify = verify self.http_auth = http_auth self.logger = logging.getLogger(__name__) self.session = self.create_session() self.session.verify = verify self.session.auth = http_auth self.session.headers['User-Agent'] = ( 'Zeep/%s (www.python-zeep.org)' % (get_version())) def create_session(self): return requests.Session() def load(self, url): if not url: raise ValueError("No url given to load") scheme = urlparse(url).scheme if scheme in ('http', 'https'): if self.cache: response = self.cache.get(url) if response: return bytes(response) response = self.session.get(url, timeout=self.timeout) response.raise_for_status() if self.cache: self.cache.add(url, response.content) return response.content elif scheme == 'file': if url.startswith('file://'): url = url[7:] with open(url, 'rb') as fh: return fh.read() def post(self, address, message, headers): self.logger.debug("HTTP Post to %s:\n%s", address, message) response = self.session.post(address, data=message, headers=headers) self.logger.debug( "HTTP Response from %s (status: %d):\n%s", address, response.status_code, response.content) return response def post_xml(self, address, envelope, headers): """Post the envelope xml element to the given address with the headers. This method is intended to be overriden if you want to customize the serialization of the xml element. By default the body is formatted and encoded as utf-8. See ``zeep.wsdl.utils.etree_to_string``. """ message = etree_to_string(envelope) return self.post(address, message, headers) def get(self, address, params, headers): response = self.session.get(address, params=params, headers=headers) return response
class Transport(object): supports_async = False def __init__(self, cache=NotSet, timeout=300, operation_timeout=None, verify=True, http_auth=None): """The transport object handles all communication to the SOAP server. :param cache: The cache object to be used to cache GET requests :param timeout: The timeout for loading wsdl and xsd documents. :param operation_timeout: The timeout for operations (POST/GET). By default this is None (no timeout). :param verify: Boolean to indicate if the SSL certificate needs to be verified. :param http_auth: HTTP authentication, passed to requests. """ self.cache = SqliteCache() if cache is NotSet else cache self.load_timeout = timeout self.operation_timeout = operation_timeout self.logger = logging.getLogger(__name__) self.http_verify = verify self.http_auth = http_auth self.http_headers = { 'User-Agent': 'Zeep/%s (www.python-zeep.org)' % (get_version()) } self.session = self.create_session() def create_session(self): session = requests.Session() session.verify = self.http_verify session.auth = self.http_auth session.headers = self.http_headers return session def get(self, address, params, headers): """Proxy to requests.get() :param address: The URL for the request :param params: The query parameters :param headers: a dictionary with the HTTP headers. """ response = self.session.get( address, params=params, headers=headers, timeout=self.operation_timeout) return response def post(self, address, message, headers): """Proxy to requests.posts() :param address: The URL for the request :param message: The content for the body :param headers: a dictionary with the HTTP headers. """ if self.logger.isEnabledFor(logging.DEBUG): log_message = message if isinstance(log_message, bytes): log_message = log_message.decode('utf-8') self.logger.debug("HTTP Post to %s:\n%s", address, log_message) response = self.session.post( address, data=message, headers=headers, timeout=self.operation_timeout) if self.logger.isEnabledFor(logging.DEBUG): log_message = response.content if isinstance(log_message, bytes): log_message = log_message.decode('utf-8') self.logger.debug( "HTTP Response from %s (status: %d):\n%s", address, response.status_code, log_message) return response def post_xml(self, address, envelope, headers): """Post the envelope xml element to the given address with the headers. This method is intended to be overriden if you want to customize the serialization of the xml element. By default the body is formatted and encoded as utf-8. See ``zeep.wsdl.utils.etree_to_string``. """ message = etree_to_string(envelope) return self.post(address, message, headers) def load(self, url): """Load the content from the given URL""" if not url: raise ValueError("No url given to load") scheme = urlparse(url).scheme if scheme in ('http', 'https'): if self.cache: response = self.cache.get(url) if response: return bytes(response) content = self._load_remote_data(url) if self.cache: self.cache.add(url, content) return content elif scheme == 'file': if url.startswith('file://'): url = url[7:] with open(os.path.expanduser(url), 'rb') as fh: return fh.read() def _load_remote_data(self, url): response = self.session.get(url, timeout=self.load_timeout) response.raise_for_status() return response.content @contextmanager def _options(self, timeout=None): """Context manager to temporarily overrule options. Example:: client = zeep.Client('foo.wsdl') with client.options(timeout=10): client.service.fast_call() :param timeout: Set the timeout for POST/GET operations (not used for loading external WSDL or XSD documents) """ old_timeout = self.operation_timeout self.operation_timeout = timeout yield self.operation_timeout = old_timeout