Beispiel #1
0
    def connect_soap(self, wsdl, model):
        if 'company_id' in model._fields:
            public_crt, private_key = self.env[
                'l10n.es.aeat.certificate'].get_certificates(model.company_id)
        else:
            public_crt, private_key = self.env[
                'l10n.es.aeat.certificate'].get_certificates()

        session = Session()
        session.cert = (public_crt, private_key)
        transport = Transport(session=session)

        history = HistoryPlugin()
        client = Client(wsdl=wsdl, transport=transport, plugins=[history])
        return client
Beispiel #2
0
    def update_soap_record(self, soap_object, data):
        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()))

        complex_type = client.get_type(f'ns0:{soap_object}')
        record = complex_type(**data)

        serialized_response = client.service.Update(record)
        return serialized_response
    def SOAP_runJob(self, context, jobunitId, jobId, jobWM=1, jobWT=1):

        HM = data_model.Hinemos.create_from_context(context)
        csapisession = CloudShellAPISession(
            host=context.connectivity.server_address,
            token_id=context.connectivity.admin_auth_token,
            domain=context.reservation.domain)

        ip = context.resource.address
        username = HM.user
        password = csapisession.DecryptPassword(
            context.resource.attributes['Hinemos.Password']).Value

        #with CloudShellSessionContext(context) as session:
        #session.WriteMessageToReservationOutput(context.reservation.reservation_id, 'Password found : {}'.format(password))

        session = Session()
        session.auth = HTTPBasicAuth(username, password)

        client = Client("http://" + ip + ":8080/HinemosWS/JobEndpoint?wsdl",
                        transport=Transport(session=session))

        factory = client.type_factory(
            'http://jobmanagement.ws.clustercontrol.com')

        out = factory.outputBasicInfo()
        trig = factory.jobTriggerInfo()

        trig.trigger_type = 2
        trig.trigger_info = username

        out.priority = 0
        trig.jobCommand = ""
        trig.jobWaitMinute = jobWM
        trig.jobWaitTime = jobWT
        session_id = client.service.runJob(jobunitId, jobId, out, trig)

        with CloudShellSessionContext(context) as session:
            session.WriteMessageToReservationOutput(
                context.reservation.reservation_id, "Hinemos Runjob:")
            session.WriteMessageToReservationOutput(
                context.reservation.reservation_id,
                "-Inputs: JobUnitId=" + jobunitId + " JobId=" + jobId)
            session.WriteMessageToReservationOutput(
                context.reservation.reservation_id,
                '-RunJob Output (Session ID) = {}'.format(session_id))

        pass
    def __init__(self,
                 server="",
                 provider="",
                 username="",
                 password="",
                 version=""):

        # TODO: add checks
        # for key, value in locals().items():
        #     if value is "":
        #         raise ValueError('Argument %s required', key)

        super(BaseProvisioningService, self).__init__()

        self.server = server
        self._add_scheme_to_server()

        self.provider = provider
        self.username = username
        self.password = password
        self.version = version

        self.endpoint = self._build_endpoint_from_server()
        self.wsdl = self._build_wsdl_url_from_endpoint()
        self.userpath = self._build_full_username()

        # plugin for fixing the arrays
        arrayfixer = ArrayFixer()
        booleanfixer = BooleanFixer()

        # initialize our client using basic auth and with the wsdl file
        session = Session()
        session.auth = HTTPBasicAuth(self.userpath, self.password)
        settings = Settings(
            strict=False,  # ePages wsdl files are full of errors...
        )
        client = Client(wsdl=self.wsdl,
                        settings=settings,
                        transport=Transport(session=session),
                        plugins=[arrayfixer, booleanfixer])
        self.client = client

        # get the binding name, there is only one so this should be ok
        qname = next(iter(client.wsdl.bindings))

        # and create new service with the name pointing to our endpoint
        self.service2 = client.create_service(qname, self.endpoint)
        logger.debug('Initialized new client: %s', self.client)
Beispiel #5
0
def connect_to_cucm(username=None, password=None, cucm_ip=None):
    WSDL_FILE = str(Path('schema') / 'AXLAPI.wsdl')

    DEBUG = False
    SUPRESS_INSECURE_CONNECTION_WARNINGS = True

    if SUPRESS_INSECURE_CONNECTION_WARNINGS:
        import urllib3
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    # This class lets you view the incoming and outgoing http headers and/or XML
    class MyLoggingPlugin(Plugin):
        def egress(self, envelope, http_headers, operation, binding_options):
            xml = etree.tostring(envelope,
                                 pretty_print=True,
                                 encoding='unicode')
            print(
                f'\nRequest\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}'
            )

        def ingress(self, envelope, http_headers, operation):
            xml = etree.tostring(envelope,
                                 pretty_print=True,
                                 encoding='unicode')
            print(
                f'\nResponse\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}'
            )

    sess = Session()

    sess.verify = False
    sess.auth = HTTPBasicAuth(username, password)

    transport = Transport(session=sess, timeout=10)
    settings = Settings(strict=False, xml_huge_tree=True)

    plugin = [MyLoggingPlugin()] if DEBUG else []

    client = Client(WSDL_FILE,
                    settings=settings,
                    transport=transport,
                    plugins=plugin)

    service = client.create_service(
        '{http://www.cisco.com/AXLAPIService/}AXLAPIBinding',
        'https://{cucm}:8443/axl/'.format(cucm=cucm_ip))

    return service
Beispiel #6
0
    def authenticate(self, key, verify=True):
        """Authenticates client

        Note
        ----
        This method additionaly sets sid (session id) header in Client's
        Session object. There is no need to set it manually.

        This method additionaly sets 'key' attribute

        This method additionaly sets 'sid' attribute

        Parameters
        ----------
        key : str
            API key
        verify : bool
            If True verifies if authentication was successfull

        Returns
        -------
        str
            sid (session id) required by API for further requests.

        Raises
        ------
        ApiAuthenticationError
            If authentication was a failure
        """
        if not self.is_production:
            key = API_KEY_TEST_ENV

        logger.debug('key=%s verify=%s' % (key, verify))
        sid = self.service.Zaloguj(key)
        session = Session()
        session.headers.update({'sid': sid})
        self.client = Client(wsdl=self.wsdl,
                             transport=Transport(session=session))
        self._create_service()
        if verify:
            if not self._check_session():
                logger.error('Authentication failed')
                raise ApiAuthenticationError(key)
            else:
                logger.debug('Authenticated successfully')
        self.key = key
        self.sid = sid
        return sid
Beispiel #7
0
    def __init__(self,
                 xml_string="",
                 site_file=None,
                 site_id_column_header='site_id',
                 testing=False,
                 endpoint=SCHEDULE_ENDPOINT):
        """
        Initializes the ScheduleConnection. This method attempts to authenticate the connection, pulls site_ids from the site_id file, and determines WSDL definition info

        :param xml_string: override the default xml, which is just <tangier method="schedule.request"/>
        :param site_file: (str) fully qualified path to xlsx or csv document containing all tangier site ids
        :param site_id_column_header: (str) header name of column containing site ids in site_file
        :param endpoint: where the WSDL info is with routing info and SOAP API definitions
        """
        super(self.__class__, self).__init__()
        if not xml_string:
            self.base_xml = """<tangier version="1.0" method="schedule.request"></tangier>"""
        else:
            self.base_xml = xml_string
        if site_file:
            if site_file.endswith('.xlsx'):
                df = pandas.read_excel(site_file)
            elif site_file.endswith('.csv'):
                df = pandas.read_csv(site_file)
            else:
                df = pandas.DataFrame()
                print(
                    'Did not read site file; must be a csv or xlsx document.')

            if not df.empty and site_id_column_header in list(df.columns):
                if testing:
                    self.site_ids = list(
                        numpy.random.choice(df[site_id_column_header],
                                            20,
                                            replace=False))
                else:
                    self.site_ids = list(df[site_id_column_header])
            elif df.emtpy:
                self.site_ids = []
            else:
                print('Site ids must be in a column with the header "{0}"'.
                      format(site_id_column_header))

        self.base_xml = xmlmanip.inject_tags(self.base_xml,
                                             user_name=TANGIER_USERNAME,
                                             user_pwd=TANGIER_PASSWORD)
        self.client = Client(endpoint, transport=Transport(session=Session()))
        self.saved_schedule = None
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)

    language = mylocale(axl)

    for para in readCSV(FILE):
        udplist = myvariables(axl, para['user'])
        udplist['udplist'].append(para['udp'])

        delLine(
            axl,
            para['dirn'],
            para['dnpt'],
        )

        addLine(
            axl,
            para['dirn'],
            para['desc'],
            'Device',
            para['dnpt'],
            para['llabel'],
        )

        addUDP(axl, para['udp'], para['model'], para['desc'], para['ptn'],
               para['local'], para['dirn'], para['dnpt'], para['llabel'],
               para['ldisplay'])

        updateUser(axl, para['user'], language[para['language'].upper()],
                   udplist['udplist'])

        print("\n")
Beispiel #9
0
 def _l10n_mx_edi_finkok_cancel(self, pac_info):
     '''CANCEL for Finkok.
     '''
     url = pac_info['url']
     username = pac_info['username']
     password = pac_info['password']
     for inv in self:
         uuid = inv.l10n_mx_edi_cfdi_uuid
         certificate_ids = inv.company_id.l10n_mx_edi_certificate_ids
         certificate_id = certificate_ids.sudo().get_valid_certificate()
         company_id = self.company_id
         cer_pem = certificate_id.get_pem_cer(certificate_id.content)
         key_pem = certificate_id.get_pem_key(certificate_id.key,
                                              certificate_id.password)
         cancelled = False
         code = False
         try:
             transport = Transport(timeout=20)
             client = Client(url, transport=transport)
             # uuid_type = client.get_type('ns0:stringArray')()
             # uuid_type.string = [uuid]
             # invoices_list = client.get_type('ns1:UUIDS')(uuid_type)
             ###########
             uuid_type = client.get_type('ns1:UUID')()
             uuid_type.UUID = uuid
             uuid_type.FolioSustitucion = inv.replace_folio or ''
             if not inv.edi_cancel_reason_id:
                 raise UserError("reason not defined")
             uuid_type.Motivo = inv.edi_cancel_reason_id.code
             invoices_list = client.get_type('ns1:UUIDS')(uuid_type)
             #############
             response = client.service.cancel(invoices_list, username,
                                              password, company_id.vat,
                                              cer_pem, key_pem)
         except Exception as e:
             inv.l10n_mx_edi_log_error(str(e))
             continue
         if not (hasattr(response, 'Folios') and response.Folios):
             msg = _(
                 'A delay of 2 hours has to be respected before to cancel')
         else:
             code = getattr(response.Folios.Folio[0], 'EstatusUUID', None)
             cancelled = code in ('201', '202'
                                  )  # cancelled or previously cancelled
             # no show code and response message if cancel was success
             code = '' if cancelled else code
             msg = '' if cancelled else _("Cancelling got an error")
         inv._l10n_mx_edi_post_cancel_process(cancelled, code, msg)
def setLrApiClient(url, username, password):
    """Creates and set LogRythem API Client

    Args:
        url: string LogRythem API server url
        username: string LogRythem API username
        password: string LogRythem API password

    Return:
        apiClient: object
    """
    session = Session()
    session.verify = False
    transport = Transport(session=session, timeout=120)
    apiClient = Client(url, wsse=UsernameToken(username, password), transport=transport, strict=False)
    return apiClient
Beispiel #11
0
    def __init__(self,
                 wsdl,
                 wsse=None,
                 transport=None,
                 service_name=None,
                 port_name=None):
        if not wsdl:
            raise ValueError("No URL given for the wsdl")

        self.transport = transport or Transport()
        self.wsdl = Document(wsdl, self.transport)
        self.wsse = wsse

        self._default_service = None
        self._default_service_name = service_name
        self._default_port_name = port_name
Beispiel #12
0
    def __init__(self, username, password, server_ip, tls_verify=True):
        wsdl = 'https://{0}:8443/controlcenterservice2/services/ControlCenterServices?wsdl'.format(
            server_ip)

        self.session = Session()
        self.session.auth = HTTPBasicAuth(username, password)
        self.session.verify = tls_verify

        self.cache = SqliteCache(path='/tmp/sqlite_serviceability.db',
                                 timeout=60)

        self.client = Client(wsdl=wsdl,
                             transport=Transport(cache=self.cache,
                                                 session=self.session))

        self.service = self.client.service
Beispiel #13
0
def get_soap_data(msg_request):
    session = Session()
    session.auth = HTTPBasicAuth(username=login, password=password)
    cnn_settings = Settings(strict=True, xml_huge_tree=True)

    client = Client(wsdl=cnn_url,
                    transport=Transport(session=session),
                    settings=cnn_settings)

    with client.settings(strict=False, raw_response=True, xml_huge_tree=True):
        saop_data = client.service[serviceName](**msg_request)

    # print saop_data
    # print saop_data.content

    return saop_data.content
    def create_client(self):
        session = Session()
        session.verify = False       

        try:
            transport = Transport(cache=SqliteCache(), session=session)
            history = HistoryPlugin()
            client = Client(self.soap_url, transport=transport, plugins=[history])

            if client:
                print("client: {}".format(client))
                return client, history
            else:
                raise AccessError(_("Not possible to establish a client."))
        except Exception as e:
            raise AccessError(_("Access error message: {}".format(e)))
Beispiel #15
0
def axl_bind(server, acct, pw):
    binding_name = "{http://www.cisco.com/AXLAPIService/}AXLAPIBinding"
    axl_address = "https://{}:8443/axl/".format(server)
    script_dir = os.path.dirname(__file__)
    wsdl_file = "{}\\AXLAPI.wsdl".format(script_dir)
    session = Session()
    session.verify = False
    session.auth = HTTPBasicAuth(acct, pw)
    transport = Transport(session=session, timeout=20)
    history = HistoryPlugin()
    settings = Settings(strict=False, xml_huge_tree=True)
    client = Client(wsdl=wsdl_file, transport=transport, plugins=[history], settings=settings)
    axl = client.create_service(binding_name, axl_address)


    return axl, history
Beispiel #16
0
    def __init__(self, server, username="", password="", debug=False):
        """At minimum server address or IP must be provided
        service = OPDMservice(<server_ip_or_address>)"""

        wsdl = '{}/cxf/OPDMSoapInterface?wsdl'.format(server)

        session = Session()
        session.verify = False
        session.auth = HTTPBasicAuth(username, password)

        transport = Transport(session=session)
        client = Client(wsdl, transport=transport)
        client.debug = debug

        self.client = client
        self.API_VERSION = "0.2"
Beispiel #17
0
    def __init__(self, shopping_list_path, LatestFlag="Y", proxies=None):
        self.LatestFlag = LatestFlag
        self.proxies = proxies
        self.shopping_list_path = shopping_list_path
        self.shopping_list = pd.read_excel(shopping_list_path)

        # create session to accomodate proxies
        session = Session()
        session.proxies = self.proxies
        retry = Retry(connect=3, backoff_factor=0.5)
        adapter = HTTPAdapter(max_retries=retry)
        session.mount("http://", adapter)
        session.mount("https://", adapter)

        url = "http://marketinformation.natgrid.co.uk/MIPIws-public/public/publicwebservice.asmx?wsdl"
        self.client = Client(url, transport=Transport(session=session))
Beispiel #18
0
def getClient(servicewsdl):
	"""Attempt to stablish a connection to the webservice and return a client object connected to servicewsdl webservice"""

	client = None

	try:
		webSession = WebSession()
		webSession.auth = HTTPBasicAuth('soap', "")
		transport = Transport(timeout=10, session = webSession)
		client = zeep.Client(wsdl=servicewsdl, transport=transport)
		print('Client successfully created')
	except Exception as e:
		print(traceback.format_exc())
		print("error in getting a client to the webservice")

	return client
Beispiel #19
0
 def __init__(self, *args, **kwargs):
     self.cert = kwargs.get('cert', self.cert)
     self.ca_cert = kwargs.get('ca_cert', self.ca_cert)
     self.key = kwargs.get('key', self.key)
     self.company = kwargs.get('company', self.company)
     self.username = kwargs.get('username', self.username)
     self.timeout = kwargs.get('timeout', self.timeout)
     session = Session()
     if self.cert and self.key and self.ca_cert:
         session.cert = (self.cert, self.key)
         session.verify = self.ca_cert
     elif self.cert or self.key or self.ca_cert:
         raise ValueError("Must provide cert, ca_cert and key")
     self.client = Client(self.endpoint,
                          transport=Transport(session=session,
                                              timeout=self.timeout))
Beispiel #20
0
    def _initSoapClient(self, logTag: str) -> Client:
        self.tracer.info("%s begin initialize SOAP client for wsdl: %s", logTag, self.wsdlUrl)

        startTime = time()
        client = None
        try:
            session = Session()
            session.verify = False
            client = Client(self.wsdlUrl, transport=Transport(session=session, timeout=SOAP_API_TIMEOUT_SECS, operation_timeout=SOAP_API_TIMEOUT_SECS))
            self.tracer.info("%s initialize SOAP client SUCCESS for wsdl: %s [%d ms]",
                             logTag, self.wsdlUrl, TimeUtils.getElapsedMilliseconds(startTime))
            return client
        except Exception as e:
            self.tracer.error("%s initialize SOAP client ERROR for wsdl: %s [%d ms] %s",
                              logTag, self.wsdlUrl, TimeUtils.getElapsedMilliseconds(startTime), e, exc_info=True)
            raise e
def test_parse_soap_header_wsdl():
    client = Client("tests/wsdl_files/soap_header.wsdl", transport=Transport())

    response = """
    <?xml version="1.0"?>
    <soapenv:Envelope
        xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
        xmlns:stoc="http://example.com/stockquote.xsd">
       <soapenv:Header/>
       <soapenv:Body>
          <stoc:TradePrice>
             <price>120.123</price>
          </stoc:TradePrice>
       </soapenv:Body>
    </soapenv:Envelope>
    """.strip()

    with requests_mock.mock() as m:
        m.post("http://example.com/stockquote", text=response)
        result = client.service.GetLastTradePrice(
            tickerSymbol="foobar",
            _soapheaders={"header": {"username": "******", "password": "******"}},
        )

        assert result.body.price == 120.123
        assert result.header.body is None

        request = m.request_history[0]

        # Compare request body
        expected = """
        <soap-env:Envelope
                xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
           <soap-env:Header>
              <ns0:Authentication xmlns:ns0="http://example.com/stockquote.xsd">
                 <username>ikke</username>
                 <password>oeh-is-geheim!</password>
              </ns0:Authentication>
           </soap-env:Header>
           <soap-env:Body>
              <ns0:TradePriceRequest xmlns:ns0="http://example.com/stockquote.xsd">
                 <tickerSymbol>foobar</tickerSymbol>
              </ns0:TradePriceRequest>
           </soap-env:Body>
        </soap-env:Envelope>
        """
        assert_nodes_equal(expected, request.body)
def main():
    module = AnsibleModule(argument_spec=dict(username=dict(required=True),
                                              password=dict(required=True),
                                              description=dict(required=True),
                                              agent=dict(required=True),
                                              path=dict(required=True,
                                                        type='path')),
                           supports_check_mode=True)

    agent = module.params.get('agent')
    description = module.params.get('description')
    path = module.params.get('path')
    username = module.params.get('username')
    password = module.params.get('password')

    http_auth = HTTPBasicAuth(username, password)
    transport = Transport(http_auth=http_auth)
    client = Client('http://localhost:9080/DiskSafe?wsdl', transport=transport)

    # Lookup the agent by hostname
    agent = _get_agent(transport, agent)
    if agent is None:
        module.fail_json(msg='Agent missing from server')

    # Lookup the disk safe
    disk_safe = _get_disk_safe(client, description)
    if disk_safe:
        module.exit_json(changed=False)

    # Not check mode, create the disk safe
    if not module.check_mode:
        disk_safe = {
            'description': description,
            'path': path,
            'compressionType': 'QUICKLZ',
            'deviceBackupType': 'AUTO_ADD_DEVICES',
            'backupPartitionTable': True,
            'agentID': agent['id']
        }

        try:
            client.service.createDiskSafeWithObject(disksafe=disk_safe)
        except (Fault, ValueError) as ex:
            module.fail_json(msg=ex.message)

    # New volume created!
    module.exit_json(changed=True)
Beispiel #23
0
    def __init__(self, account=None, caching=True, caching_timeout=2592000):
        """
        Initialize the Zeep SOAP client, parse the xsd specifications
        of Netsuite and store the complex types as attributes of this
        instance.

        :param str account_id: Account ID to connect to
        :param str caching: If caching = 'sqlite', setup Sqlite caching
        :param int caching_timeout: Timeout in seconds for caching.
                            If None, defaults to 30 days
        """
        self.logger = logging.getLogger(self.__class__.__name__)
        assert account, 'Invalid account'
        assert '-' not in account, 'Account cannot have hyphens, it is likely an underscore'
        self._account = account

        self._wsdl_url = self.WSDL_URL_TEMPLATE.format(
            account=account.replace('_', '-'))
        self._datacenter_url = self.DATACENTER_URL_TEMPLATE.format(
            account=account.replace('_', '-'))

        if caching:
            path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                'cache.db')
            timeout = caching_timeout
            cache = SqliteCache(path=path, timeout=timeout)
            transport = Transport(cache=cache)
        else:
            transport = None

        # Initialize the Zeep Client
        self._client = Client(self._wsdl_url, transport=transport)

        # default service points to wrong data center. need to create a new service proxy and replace the default one
        self._service_proxy = self._client.create_service(
            '{urn:platform_2020_1.webservices.netsuite.com}NetSuiteBinding',
            self._datacenter_url)

        # Parse all complex types specified in :const:`~netsuitesdk.netsuite_types.COMPLEX_TYPES`
        # and store them as attributes of this instance. Same for simple types.
        self._namespaces = {}
        self._init_complex_types()
        self._init_simple_types()

        self._app_info = None
        self._is_authenticated = False
        self.set_search_preferences()
Beispiel #24
0
    def __init__(self, username, password, realm, log_file, test_login=True):

        super().__init__(realm)
        transport = Transport(timeout=1000)
        self.client = Client(self.NIF_PAYMENT_URL,
                             wsse=UsernameToken(username, password),
                             plugins=[LoggingPlugin(log_file)],
                             transport=transport)

        self.ns5 = self.client.type_factory('ns5')

        if test_login is True:
            state, result = self._test()

            if state is not True:
                raise NIFApiAuthenticationError(
                    'Could not authenticate via test')
Beispiel #25
0
 def _connect(self, url):
     transport_session = requests.Session()
     transport_session.mount(
         'https://',
         CustomHTTPSAdapter(
             ctx_options={
                 'cert': self.cert_data['cert'],
                 'key': self.cert_data['key'],
                 'cafile': self.ca_file
             }
         )
     )
     ws_transport = Transport(session=transport_session)
     return Client(
         url,
         transport=ws_transport
     )
Beispiel #26
0
def get_policy_details_host():
    # SOAP call to get policy details per host
    hosts = get_all_hosts()
    session = Session()
    session.verify = False
    transport = Transport(session=session)
    client = Client('https://' + DS_host + ':4119/webservice/Manager?WSDL',
                    transport=transport)
    sid = client.service.authenticate(username, password)
    for host in hosts:
        securityProfileID = host['securityProfileID']
        if securityProfileID == None:
            continue
        else:
            hosts = client.service.securityProfileRetrieve(
                securityProfileID, sid)
            print(hosts)
Beispiel #27
0
    def __init__(self, server, username="", password="", debug=False):
        """At minimum server address or IP must be provided"""

        wsdl = '{}/ws/madesInWSInterface.wsdl'.format(server)

        session = Session()
        session.verify = False
        session.auth = HTTPBasicAuth(username, password)

        transport = Transport(session=session)
        client = Client(wsdl, transport=transport)

        client.debug = debug

        self.service = client.create_service(
            '{http://mades.entsoe.eu/}MadesEndpointSOAP12',
            '{}/ws/madesInWSInterface'.format(server))
Beispiel #28
0
def ws_support_register(email, title, mes):
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    session = Session()
    session.verify = False
    transport = Transport(session=session)
    client = Client("http://support.robokassa.ru/svc/support.asmx?WSDL",
                    transport=transport)
    RegisterRequest = {
        'EMail': email,
        'Title': title,
        'Message': mes,
        "RequestID": 2000000,
        'PersonID': str(uuid.uuid4())
    }
    #  print(RegisterRequest['PersonID'])
    result = client.service.Register(request=RegisterRequest)
    return result
def consumo_servicio():
    # Se envia la url y las credenciales como parametro para crear el cliente del servicio
    wsd = 'https://facturaelectronica.dian.gov.co/operacion/B2BIntegrationEngine/FacturaElectronica/consultaDocumentos.wsdl'
    transport = Transport(timeout=10)
    user = '******'
    passwd = '7ea182d7fe1b9359812828166500793077c6d6f16ded5f8516159bc1b9fdf7e7'
    client = Client(wsdl=wsd,
                    wsse=UsernameToken(user, passwd),
                    transport=transport)

    # Se declara la fabrica para que el WS reciba los datos correctamente

    with open('info_facturas.txt', 'r') as info_facturas:
        for line in info_facturas.readlines():
            line_temp = line.split(",")
            strformat = "%Y-%m-%dT%H:%M:%S"
            id_fac = line_temp[0]
            fecha_fac = datetime.datetime.strptime(line_temp[1], strformat)
            nit_fac = line_temp[2]
            cufe_fac = line_temp[3].rstrip()
            factory = client.type_factory('ns0')

            date = fecha_fac
            tipoDoc = factory.TipoDocumenotoType('1')
            num_doc = factory.NumeroDocumentoType(id_fac)
            nit = factory.NitType(nit_fac)
            id_software = factory.IdentificadorSoftwareType(
                '5ac5e351-ed30-4e8c-90ff-d56d1ba91dbe')
            cufe = factory.CufeType(cufe_fac)

            # Se configura el cliente para consumir el servicio
            with client.settings(strict=False,
                                 xml_huge_tree=False,
                                 raw_response=True):
                operation = client.service.ConsultaResultadoValidacionDocumentos(
                    tipoDoc, num_doc, nit, date, id_software, cufe)
                operation_code = operation
                correct_res = correct_document(operation._content)
                with open('result.xml', 'w') as fileobj:
                    fileobj.write(str(correct_res))
                    fileobj.close()

            Parse_Document.parse_document(correct_res,
                                          operation_code.status_code, id_fac)

    info_facturas.close()
    def get_wsdl_service(self, wsdl_path):
        domain = current_app.config['SF_DOMAIN'] + '.salesforce.com'
        wsdl = 'https://{}{}'.format(domain, wsdl_path)

        if not hasattr(self, wsdl_path):
            # Add cookie `sid` to get WSDL
            sid = self.sf.session_id
            self.sf.session.cookies['sid'] = sid
            client = Client(wsdl, transport=Transport(session=self.sf.session))

            # Add SessionHeader for accessing the service
            client.set_default_soapheaders({'SessionHeader': sid})

            setattr(self, wsdl_path, client)
            self.WSDL_METHODS.add(wsdl_path)

        return getattr(self, wsdl_path).service