def getSoapService(self, wsdl): session = requests.Session() session.auth = requests.auth.HTTPBasicAuth(self.credentials[0], self.credentials[1]) soapService = zeep.Client(self.url + wsdl, transport=zeep.Transport(session=session)) return soapService
def _get_client(self): try: transport = zeep.Transport(timeout=self.timeout, operation_timeout=self.timeout) client = zeep.Client(self.WS_URL, transport=transport) yield client finally: transport.session.close()
def setup_soapclient(env, prefix, verify=False): plugins = [] # if logger.getEffectiveLevel() <= logger.TRACE: plugins.append(SOAPLogger()) session = requests.Session() session.verify = verify try: session.auth = requests.auth.HTTPBasicAuth( environments_config[env][prefix + 'username'], environments_config[env][prefix + 'password']) except KeyError: logger.warning( "No authentication data given for {env} using {wsdl}". format(env=env, wsdl=os.path.basename( environments_config[env][prefix + 'wsdl_file']))) finally: soap_client = zeep.Client( 'file://' + environments_config[env][prefix + 'wsdl_file'], transport=zeep.Transport(session=session), plugins=plugins) setattr( soap_client, prefix + "service", soap_client.create_service( environments_config[env][prefix + 'service_binding'], environments_config[env][prefix + 'endpoint'])) logger.info( "Setting up SOAP client for {env} using {wsdl}".format( env=env, wsdl=os.path.basename( environments_config[env][prefix + 'wsdl_file']))) return soap_client
def __init__(self, auth, version=None, verify=None, timeout=60): self.session = requests.Session() self.session.auth = auth if verify is not None: self.session.verify = verify if version is None: # Somehow determine the UCM version raise Exception('Not implemented') wsdl_version = version self.wsdl = os.path.join(os.path.dirname(__file__), 'WSDL', wsdl_version, 'ControlCenterServices.wsdl') self.cache = zeep.cache.SqliteCache(path=os.path.join( tempfile.gettempdir(), 'sqlite_control_CC.db'), timeout=60) self.client = zeep.Client(wsdl=self.wsdl, transport=zeep.Transport( timeout=timeout, operation_timeout=timeout, cache=self.cache, session=self.session)) self.services = {} return
def __init__(self, base_url, username, password): self.base_url = base_url self.username = username self.password = password self.lock = threading.Lock() session = requests.Session() session.auth = requests.auth.HTTPBasicAuth(username, password) self.transport = zeep.Transport(session=session)
def chebi_connect(self): ''' Connect to the chebi client ''' wsdl='https://www.ebi.ac.uk/webservices/chebi/2.0/webservice?wsdl' transport = zeep.Transport(operation_timeout=300) self.client = zeep.Client(wsdl=wsdl, transport=transport) return None
def _get_teryt_client(session: requests.Session = requests.Session() ) -> zeep.Client: __log = logging.getLogger(__name__ + ".get_teryt_client") __log.info("Connecting to TERYT web service") wsdl = "https://uslugaterytws1.stat.gov.pl/wsdl/terytws1.wsdl" wsse = UsernameToken("osmaddrtools", "#06JWOWutt4") return zeep.Client(wsdl=wsdl, wsse=wsse, transport=zeep.Transport(session=session))
def __init__(self, wsurl, user=None, pwd=None, idlength=6): self.idlength = idlength if (user or pwd): session = Session() session.auth = auth.HTTPBasicAuth(user, pwd) self.sclient = zeep.Client( wsdl=wsurl, transport=zeep.Transport(session=session)) else: self.sclient = zeep.Client(wsdl=wsurl)
def setup_soap(**kwargs): session = requests.Session() session.auth = requests.auth.HTTPBasicAuth(kwargs["username"], kwargs["password"]) sys.stderr.write("using username {}\n".format(kwargs["username"])) session.headers = { "user-agent": "state-of-the-map-tickeos-ticket-tool/0.1" } transport = zeep.Transport(session=session, cache=zeep.cache.SqliteCache()) return zeep.Client(kwargs["wsdl_url"], None, transport)
def _get_authenticated_client(self, wsdl): """Return an authenticated SOAP client. Returns: zeep.Client: Authenticated API client. """ return zeep.Client( wsdl % quote(self.username), transport=zeep.Transport( session=self._get_authenticated_session(), ), )
def __init__(self, client_id, username, password): client = zeep.Client(transport=zeep.Transport(timeout=None), wsdl=self.WSDL_URL.format(client_id), strict=False, xml_huge_tree=True) auth_response = client.service.Authenticate(client_id, username, base64.b64encode(password)) session = auth_response['Detail'].split(',')[1] SessionCredentials = client.get_type('ns0:UserSessionCredentials') creds = SessionCredentials(UserId=0, ClientId=client_id, SessionId=session) self._client = client self._auth = {'_soapheaders': [creds]}
def try_zeep(): global transport, history, client, service, factory # disable warnings for HTTPS sessions w/ diabled cert validation urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) logging.getLogger('zeep').setLevel(logging.INFO) logging.getLogger('zeep.transports').setLevel(logging.INFO) logging.getLogger('urllib3').setLevel(logging.INFO) logging.basicConfig(level=logging.DEBUG) axl_url = f'https://{UCM_PUBLISHER}:8443/axl/' # we have WSDL files for a number of releases in the WSDL directory wsdl_version = '12.5' wsdl = os.path.join(os.path.dirname(__file__), 'WSDL', wsdl_version, 'AXLAPI.wsdl') print(f'Using WSDL: {wsdl}') # we want to use the same requests session for all requests # among other things this makes sure that cookies are handled # properly: a session cookies set by UCM in the 1st reaponse # will automatically be sent with each following request # see: # https://developer.cisco.com/docs/axl/#!axl-developer-guide/using-jsessionidsso-to-improve-performance session = requests.Session() session.auth = (AXL_USER, AXL_PASSWORD) session.verify = False # setting up the zeep client # - we enable the history plugin so that after calling an endpoint we have access to the latest request & response # - also we enable our logging plugin above which logs requests and responses in real-time transport = zeep.Transport(session=session, cache=zeep.cache.SqliteCache()) history = zeep.plugins.HistoryPlugin() client = zeep.Client(wsdl=wsdl, transport=transport, # create a chain of plugins to keep the history of request/response # and log everything to stdout plugins=[history, LoggingPlugin()]) # the 1st parameter here is the binding defined in the WSDL service = client.create_service('{http://www.cisco.com/AXLAPIService/}AXLAPIBinding', axl_url) list_phones() list_css() list_process_node() #add_user() sql_test()
def run_sync(): print("sync example") print("============") transport = zeep.Transport(cache=None) client = zeep.Client("http://localhost:8000/?wsdl", transport=transport) st = time.time() result = [ client.service.slow_request("request-1"), # takes 1 sec client.service.slow_request("request-2"), # takes 1 sec ] print("Time: %.2f" % (time.time() - st)) print("result:", result) print("\n") return result
def __init__(self, ucm_host, auth, version=None, verify=None, timeout=60): """ :param ucm_host: IP/FQDN of host to direct AXL requests to, optional with port spec :param auth: passed to requests.Session object. For basic authentication simply pass a (user/password) tuple :param version: String of WSDL version to use. For example: '12.0' :param verify: set to False to disable SSL key validation :param timeout: zeep timeout """ self.ucm_host = ucm_host if not ':' in ucm_host: ucm_host += ':8443' self.axl_url = 'https://{ucm_host}/axl/'.format(ucm_host=ucm_host) self.session = requests.Session() self.session.auth = auth if verify is not None: self.session.verify = verify if version is None: # Somehow determine the UCM version raise Exception('Not implemented') wsdl_version = version self.wsdl = os.path.join(os.path.dirname(__file__), 'WSDL', wsdl_version, 'AXLAPI.wsdl') self.cache = zeep.cache.SqliteCache(path=os.path.join( tempfile.gettempdir(), 'sqlite_{}.db'.format(self.ucm_host)), timeout=60) self.client = zeep.Client(wsdl=self.wsdl, transport=zeep.Transport( timeout=timeout, operation_timeout=timeout, cache=self.cache, session=self.session)) self.service = self.client.create_service( '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding', self.axl_url) return
def __init__(self, load_api_preco_prazo: bool = False, load_api_sro: bool = False, load_api_sigep: bool = False, producao: bool = False): self.producao = producao self.cache = zeep.cache.InMemoryCache(timeout=86400) self.transport = zeep.Transport(cache=self.cache, timeout=20, operation_timeout=15) if load_api_preco_prazo: self.load_api_preco_prazo() if load_api_sro: self.load_api_sro() if load_api_sigep: self.load_api_sigep()
def request(self): start_time = time.time() try: transport = zeep.Transport( cache=None, timeout=self.max_response_time, operation_timeout=self.max_response_time, session=None) client = zeep.Client(self.url, transport=transport) resp = client.service[self.method](*self.params) self.resp_time = time.time() - start_time self.resp_status = 200 self.last_finish_time = time.time() if self.assert_type == AssertType.TYPE_TEXT: if resp.find(self.assert_data) == -1: self.resp_status = 404 return RequestType.TYPE_DATAERROR elif self.assert_type == AssertType.TYPE_JSON: if MonitorObject.assertJsonData( resp, self.assert_data) != AssertValue.VALUE_ASSERT_SUCCESS: self.resp_status = MonitorStatus.STATUS_DATAERROR return RequestType.TYPE_DATAERROR elif self.assert_type == AssertType.TYPE_XML: if MonitorObject.assertXmlData( resp, self.assert_data) != AssertValue.VALUE_ASSERT_SUCCESS: self.resp_status = MonitorStatus.STATUS_DATAERROR return RequestType.TYPE_DATAERROR return RequestType.TYPE_SUCCESS except rq.exceptions.Timeout: self.resp_status = MonitorStatus.STATUS_TIMEOUT self.resp_time = 0 self.last_finish_time = time.time() - self.max_response_time return RequestType.TYPE_TIMEOUT except: self.resp_time = time.time() - start_time self.resp_status = 404 self.last_finish_time = time.time() return RequestType.TYPE_FAILED
def __init__(self, server='maullin', module=1, mode=1, ssl=0): logger = logging.getLogger() """ Load certificate """ self.mode = mode self.module = module self.ssl = ssl self.server = server """ Set module and server """ self.server_url = self.get_wsdl_url(server, module) """ Pass SII certificate """ session = Session() session.verify = False transport = zeep.Transport(session=session) self.sii_plugin = SiiPlugin() logger.info("SiiConnectorBase.__init__::Loading WSDL from : " + str(self.server_url)) self.soap_client = zeep.Client(wsdl=self.server_url, transport=transport, plugins=[self.sii_plugin])
def __init__(self, configuration_file="medisnip.yaml"): #Setup logger self.log = logging.getLogger("medisnip") self.log.info("MediSnip logger initialized") #Open configuration file try: config_data = open(os.path.expanduser(configuration_file), 'r').read() except IOError: raise Exception('Cannot open configuration file ({file})!'.format( file=configuration_file)) #Try to parse yaml configuration try: self.config = yaml.load(config_data) except Exception as yaml_error: raise Exception( 'Configuration problem: {error}'.format(error=yaml_error)) transport = zeep.Transport() transport.session.headers[ 'User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36' self.medicover = zeep.Client(self.MEDICOVER_API, transport=transport) self.mol = self.medicover.service self.log.info("MediSnip client initialized") #Try to login to MOL Service ticket = json.loads( self.mol.MobileLogin_StrongTypeInput( self.config['medicover']['card_id'], self.config['medicover']['password'], 'NewMOB', uuid.uuid4, 'Android', '7.1')) if ticket['TicketId'] is None: raise Exception("Login or password is incorrect") else: self.ticket = ticket['TicketId'] self.person = ticket['Id'] self.log.info( "Succesfully logged in! (TicketID: {ticket}, PersonID: {person})". format(ticket=self.ticket, person=self.person))
#!/usr/bin/python3 import zeep, configparser, smtplib, pprint, datetime import xml.etree.ElementTree as ET from email.mime.text import MIMEText config = configparser.ConfigParser() config.read('api.conf') mail_content = '' transport = zeep.Transport(verify=False) if config.has_option('connection', 'proxy'): transport.session.proxies = { 'http': config['connection']['proxy'], 'https': config['connection']['proxy'] } try: portal_wsdl = 'https://' + config['connection'][ 'ien_server'] + '/portal/services/IsvWebService?wsdl' portal_client = zeep.Client(wsdl=portal_wsdl, transport=transport) ienc_wsdl = 'https://' + config['connection'][ 'ien_server'] + '/ienc/services/IsvService?wsdl' ienc_client = zeep.Client(wsdl=ienc_wsdl, transport=transport) portal_result = portal_client.service.apiLogin( config['connection']['username'], config['connection']['password'], config['connection']['isv']) portal_root = ET.fromstring(portal_result) for element in portal_root.iter('AuthCode'):
import zeep from requests import Session #wsdl = 'http://www.soapclient.com/xml/soapresponder.wsdl' #wsdl = 'https://homologacao.nfe.fazenda.sp.gov.br/ws/nfeautorizacao4.asmx?wsdl' #wsdl = 'https://homologacao.nfe.fazenda.sp.gov.br/ws/nfeautorizacao4.asmx' wsdl = 'https://nfe.fazenda.sp.gov.br/ws/nfeconsultaprotocolo4.asmx?wsdl' #nota fiscal chave nfe = '35200643708379010830550050002904511102904515' session = Session() session.verify = 'path/to/my/certificate.pem' transport = zeep.Transport(session=session) client = zeep.Client(wsdl=wsdl, transport=transport) print(client.service._operations)
import zeep import pandas as pd import asyncio import asyncio import time import zeep from zeep.asyncio import AsyncTransport wsdl = 'http://10.21.2.75:8080/service/LBEBusiness?wsdl' transport = zeep.Transport(cache=None) client = zeep.Client(wsdl=wsdl, transport=transport) login_ans = client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", ""), sessionId = login_ans[0].sessionId result = [] def handle_future(future): result.extend(future.result()) print('*' * 200) print(result) print('*' * 200) # wsdl = 'http://10.21.2.75:8080/service/LBEBusiness?wsdl' # client = zeep.Client(wsdl=wsdl) # sessionId = client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", "") # print(client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", "")) # factory = client.type_factory('ns0')
def seed(): import datetime, time utc_offset_sec = time.altzone if time.localtime( ).tm_isdst else time.timezone utc_offset = datetime.timedelta(seconds=-utc_offset_sec) return (datetime.datetime.now().replace(microsecond=0).replace( tzinfo=datetime.timezone(offset=utc_offset)).isoformat()) def make_sha1(cadena, encoding='utf-8'): return sha1(cadena.encode(encoding)).hexdigest() #imprimir algunas variables print(seed()) print(make_sha1(str(seed()) + tranKey)) print(len(make_sha1(seed() + tranKey))) import zeep transport = zeep.Transport(operation_timeout=10000) wsdl = 'https://test.placetopay.com/soap/pse/?wsdl' client = zeep.Client(wsdl=wsdl) semilla = str(seed()) result = client.service.getBankList( [identificador, make_sha1(semilla + tranKey), semilla, '', ''])
def _get_client(self): if not self._client: transport = zeep.Transport(timeout=self.timeout, operation_timeout=self.timeout) self._client = zeep.Client(self.WS_URL, transport=transport) return self._client
def __init__(self, ucm_host, auth, version=None, verify=None, timeout=60): """ :param ucm_host: IP/FQDN of host to direct AXL requests to, optional with port spec :param auth: passed to requests.Session object. For basic authentication simply pass a (user/password) tuple :param version: String of WSDL version to use. For example: '12.0' :param verify: set to False to disable SSL key validation :param timeout: zeep timeout """ self.ucm_host = ucm_host if not ':' in ucm_host: ucm_host += ':8443' self.axl_url = 'https://{ucm_host}/axl/'.format(ucm_host=ucm_host) self.session = requests.Session() self.session.auth = auth if verify is not None: self.session.verify = verify version = version or self._get_version() wsdl_version = version self.wsdl = os.path.join(os.path.dirname(__file__), 'WSDL', wsdl_version, 'AXLAPI.wsdl') temp_dir = None if not os.path.isfile(self.wsdl): log.debug(f'__init__: WSDL not found: {self.wsdl}') # we need to download the wsdl from UCM temp_dir = tempfile.TemporaryDirectory() temp_zip_file_name = os.path.join(temp_dir.name, 'axlsqltoolkit.zip') r = self.session.get( f'https://{self.ucm_host}/plugins/axlsqltoolkit.zip') with open(temp_zip_file_name, 'wb') as f: f.write(r.content) log.debug(f'__init__: downloaded {temp_zip_file_name}') with zipfile.ZipFile(temp_zip_file_name, 'r') as zip: zip.extractall(path=temp_dir.name) log.debug(f'__init__: extracted {temp_zip_file_name}') self.wsdl = os.path.join(temp_dir.name, 'schema', 'current', 'AXLAPI.wsdl') log.debug(f'__init__: using {self.wsdl}') self.cache = zeep.cache.SqliteCache(path=os.path.join( tempfile.gettempdir(), 'sqlite_{}.db'.format(self.ucm_host)), timeout=60) self.client = zeep.Client(wsdl=self.wsdl, transport=zeep.Transport( timeout=timeout, operation_timeout=timeout, cache=self.cache, session=self.session)) self.service = self.client.create_service( '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding', self.axl_url) if temp_dir: # remove temporary WSDL directory and temp files log.debug(f'__init__: cleaning up temp dir {temp_dir.name}') temp_dir.cleanup() return
def run_async(): print("async example") print("=============") wsdl = 'http://10.21.2.75:8080/service/LBEBusiness?wsdl' transport = zeep.Transport(cache=None) client = zeep.Client(wsdl=wsdl, transport=transport) login_ans = client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", ""), sessionId = login_ans[0].sessionId result = [] def handle_future(future): result.extend(future.result()) print('*' * 200) print(result) print('*' * 200) loop = asyncio.get_event_loop() transport = AsyncTransport(loop, cache=None) # client = zeep.Client(wsdl=wsdl) # client = zeep.Client(wsdl=wsdl, transport=transport) # sessionId = client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", "") string_type = client.get_type('xsd:string') lbParameter_type = client.get_type('ns0:lbParameter') queryOption_type = client.get_type('ns0:queryOption') par_dict = { "KSRQ": "2018-11-13", "JSRQ": "2018-11-13", "YYB": "1", # "TJFL": "0", "TJFL": "1", } params = [] for key in par_dict: val = par_dict[key] temp_lbParameter = lbParameter_type(name=key, value=val) params.append(temp_lbParameter) valueOption_type = client.get_type('ns0:valueOption') valueOption = valueOption_type('VALUE') batchNo = 1 batchSize = 30 mqueryOption = queryOption_type(batchNo=batchNo, batchSize=batchSize, queryCount=True, valueOption=valueOption) batchNo += 1 mqueryOption2 = queryOption_type(batchNo=batchNo, batchSize=batchSize, queryCount=True, valueOption=valueOption) mqueryOption0 = queryOption_type(batchNo=batchNo, batchSize=batchSize, queryCount=True, valueOption=valueOption) # ans = client.service.query(sessionId.sessionId, "cxSqlKHCJTJ_GPXZ", params, "", mqueryOption) # print(ans) tasks = [ # client.service.login("ZXQH_GPXZ", "GPXZ123321", "myapp", "plain", ""), client.service.query(sessionId, "cxSqlKHCJTJ_GPXZ", params, "", mqueryOption0), client.service.query(sessionId, "cxSqlKHCJTJ_GPXZ", params, "", mqueryOption), client.service.query(sessionId, "cxSqlKHCJTJ_GPXZ", params, "", mqueryOption2), # takes 1 sec ] future = asyncio.gather(*tasks, return_exceptions=True) future.add_done_callback(handle_future) st = time.time() loop.run_until_complete(future) loop.run_until_complete(transport.session.close()) print("time: %.2f" % (time.time() - st)) print("result: %s", result) print("") return result
traceback.print_exc() print('===============================================================================================') try: client = zeep.Client('http://www.soapclient.com/xml/soapresponder.wsdl') with client.options(raw_response=True): resp = client.service.Method1('Zeep', 'is cool') print(resp.content) except: traceback.print_exc() print('===============================================================================================') try: client = zeep.Client('http://www.soapclient.com/xml/soapresponder.wsdl') with client.options(raw_response=True): resp = client.service.Method1('Zeep', 'is cool') print(resp.content) except: traceback.print_exc() print('===============================================================================================') try: transport = zeep.Transport(timeout=10) client = zeep.Client('http://www.soapclient.com/xml/soapresponder.wsdl', transport=transport) print(client.service.Method1('Zeep', 'is cool')) except: traceback.print_exc()
def load_class_variables(cls, app_configs): """load_class_variables loads in the app_configs dict and assigned each value as a class variable. After loading, a zeep SOAP Client is created with our credentials :param app_configs: a dictionary containing key-value pairs used for setting up a client with Symantec DLP. :type app_configs: dict """ cls.is_connected = False # Set is_connected to false initially validate_fields(['sdlp_host', 'sdlp_wsdl', 'sdlp_username', 'sdlp_password', 'sdlp_savedreportid', 'sdlp_incident_endpoint'], kwargs=app_configs) LOG.debug("Validated Mandatory app.configs for DLPSoapClient") cls.host = app_configs.get('sdlp_host') cls.wsdl = app_configs.get('sdlp_wsdl') # Gather the DLP User Name cls.dlp_username = app_configs.get('sdlp_username') # Gather the DLP User Password cls.dlp_password = app_configs.get('sdlp_password') # Gather the DLP Cert cls.dlp_cert = app_configs.get('sdlp_cafile', False) # Gather the DLP Saved Report ID cls.dlp_saved_report_id = app_configs.get('sdlp_savedreportid') # Gather the DLP Incident Endpoint cls.sdlp_incident_endpoint = app_configs.get('sdlp_incident_endpoint') cls.session = Session() # Use DLP Cert if provided or if None, set verify to false cls.session.verify = cls.dlp_cert cls.session.auth = SymantecAuth(cls.dlp_username, cls.dlp_password, cls.host) mimefile_abs_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), os.path.pardir, "data", "xmlmime.xml") # If the Xmlmime file was provided if os.path.isfile(mimefile_abs_path): LOG.info("A Local XML file was found in the data directory, %s \n Loading this into the cache", mimefile_abs_path) # Open it and add it to a Cache with open(mimefile_abs_path, mode="rb") as f: filecontent = f.read() dlp_cache = InMemoryCache() dlp_cache.add("http://www.w3.org/2005/05/xmlmime", filecontent) dlp_cache.add("https://www.w3.org/2005/05/xmlmime", filecontent) # Setup Transport with credentials and the cached mimefile cls.transport = zeep.Transport(session=cls.session, cache=dlp_cache) else: # Setup Transport with our credentials cls.transport = zeep.Transport(session=cls.session) try: # Try to create a soap_client from the wsdl and transport cls.soap_client = zeep.Client(wsdl=cls.wsdl, transport=cls.transport) except Exception as caught_exc: # We got an error when setting up a client, catch and release the error in logs so circuits doesn't stop # Put the traceback into DEBUG LOG.debug(traceback.format_exc()) # Log the Connection error to the user LOG.error(u"Problem: %s", repr(caught_exc)) LOG.error(u"[Symantec DLP] Encountered an exception when setting up the SOAP Client") else: # No connection error, client is setup with the URL. Allow the poller to be setup cls.is_connected = True cls.class_vars_loaded = True