コード例 #1
0
def get_jpt(teryt):
    client = Client(
        "https://uslugaterytws1test.stat.gov.pl/wsdl/terytws1.wsdl",
        wsse=UsernameToken(username='******', password='******'))
    client.create_service(
        binding_name='{http://tempuri.org/}custom',
        address='https://uslugaterytws1test.stat.gov.pl/terytws1.svc')
    if client.service.CzyZalogowany() == True:
        factory = client.type_factory('ns2')
        identyfiks = factory.identyfikatory(terc=teryt)
        list_identyfiks = factory.ArrayOfidentyfikatory(identyfiks)
        jpt = client.service.WyszukajJednostkeWRejestrze(
            identyfiks=list_identyfiks,
            kategoria='3',
            DataStanu=datetime.now())
        if jpt != None:
            jpt = jpt[0]
            result = {
                i: jpt[i]
                for i in jpt
                if i == 'GmiNazwa' or i == 'Powiat' or i == 'Wojewodztwo'
            }
            return result
    else:
        return None
コード例 #2
0
def _setup_connection():
    # Setup SOAP/AXL/HTTPS Connection
    global service
    # Change to true to enable output of request/response headers and XML
    DEBUG = False

    # The WSDL is a local file in the working directory, see README
    WSDL_FILE = 'schema/AXLAPI.wsdl'

    # This class lets you view the incoming and outgoing http headers and XML

    class MyLoggingPlugin(Plugin):

        def egress(self, envelope, http_headers, operation, binding_options):

            # Format the request body as pretty printed XML
            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):

            # Format the response body as pretty printed XML
            xml = etree.tostring(envelope, pretty_print=True, encoding='unicode')

            print(f'\nResponse\n-------\nHeaders:\n{http_headers}\n\nBody:\n{xml}')


    # The first step is to create a SOAP client session
    session = Session()

    # We avoid certificate verification by default
    # session.verify = False

    # To enabled SSL cert checking (recommended for production)
    # place the CUCM Tomcat cert .pem file in the root of the project
    # and uncomment the line below

    session.verify = sessionCert

    # Add Basic Auth credentials
    session.auth = HTTPBasicAuth(cucmusername, cucmpassword)

    # Create a Zeep transport and set a reasonable timeout value
    transport = Transport(session=session, timeout=10)

    # strict=False is not always necessary, but it allows zeep to parse imperfect XML
    settings = Settings(strict=False, xml_huge_tree=True)

    # If debug output is requested, add the MyLoggingPlugin callback
    plugin = [MyLoggingPlugin()] if DEBUG else [ ]

    # Create the Zeep client with the specified settings
    client = Client(WSDL_FILE, settings=settings, transport=transport,
            plugins=plugin)

    # FUTURE create CUCM chooser menu

    # Create the Zeep service binding to AXL at the specified CUCM
    service = client.create_service('{http://www.cisco.com/AXLAPIService/}AXLAPIBinding', serverUrl)
コード例 #3
0
class DimeGetFileService:
    def __init__(self,
                 username,
                 password,
                 hostname,
                 tls_verify=True,
                 timeout=10):
        self.last_exception = None
        wsdl = f'https://{hostname}:8443/logcollectionservice/services/DimeGetFileService?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)
        self.history = HistoryPlugin()
        self.client = Client(wsdl=wsdl,
                             transport=transport,
                             plugins=[self.history])
        binding_name = '{http://cisco.com/ccm/serviceability/soap/LogCollection/GetFile/}GetFileBinding'
        service_addr = f'https://{hostname}:8443/logcollectionservice/services/DimeGetFileService'
        self.service = self.client.create_service(binding_name, service_addr)

    def GetOneFile(self, data):
        try:
            result = self.service.GetOneFile(data)
            return result
        except Exception as fault:
            self.last_exception = fault
コード例 #4
0
    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")
コード例 #5
0
ファイル: __init__.py プロジェクト: undmicj/cucca
class UcmRisPortToolkit:
    last_exception = None
    '''
    Constructor - Create new instance 
    '''
    def __init__(self, username, password, server_ip, tls_verify=True):
        wsdl = 'https://{0}:8443/realtimeservice2/services/RISService70?wsdl'.format(
            server_ip)

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

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

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

        self.service = self.client.create_service(
            "{http://schemas.cisco.com/ast/soap}RisBinding",
            "https://{0}:8443/realtimeservice2/services/RISService70".format(
                server_ip))

        # enable_logging()

    def get_service(self):
        return self.service
コード例 #6
0
    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/",
        )
コード例 #7
0
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
コード例 #8
0
    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 getregisteration(self, macs, transport, history):
     ## setup Session
     # import required WSDL's
     riswsdl = 'https://' + self.Ipaddress + ':8443/realtimeservice2/services/RISService70?wsdl'
     try:
         client = Client(wsdl=riswsdl,
                         transport=transport,
                         plugins=[history])
         RIS_BINDING = "{http://schemas.cisco.com/ast/soap}RisBinding"
         RIS_ADDR = 'https://' + self.Ipaddress + ':8443/realtimeservice2/services/RISService70?wsdl'
         risAxl = client.create_service(RIS_BINDING, RIS_ADDR)
         factory = client.type_factory('ns0')
         item = []
         for mac in macs:
             item.append(factory.SelectItem(Item=mac))
         Item = factory.ArrayOfSelectItem(item)
         stateInfo = ''
         criteria = factory.CmSelectionCriteria(MaxReturnedDevices=1000,
                                                Status='Any',
                                                NodeName='',
                                                SelectBy='Name',
                                                SelectItems=Item)
         result = risAxl.selectCmDevice(stateInfo, criteria)
         return result
     except (Fault, Exception) as error:
         print("Error in getting RIS report from publisher\n" + error)
         return None
 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
コード例 #11
0
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'])
コード例 #12
0
ファイル: list_phones.py プロジェクト: dpnetca/clauto
async def main():
    st = time()
    loop = asyncio.get_event_loop()
    load_dotenv()

    # Load Environmental Variable
    wsdl = os.getenv("WSDL_FILE")
    username = os.getenv("UCM_USERNAME")
    password = os.getenv("UCM_PASSWORD")
    ucm_pub_url = f'https://{os.getenv("UCM_PUB_ADDRESS")}:8443/axl/'

    print(f"init: {time() - st}s")

    # Create Session, do not verify certificate, enable basic auth
    # ISSUE, zeep not using cookies, authenticating every time
    # authentication is rate limited
    connector = TCPConnector(ssl=False, limit=5)
    auth = BasicAuth(username, password)
    async with ClientSession(connector=connector, auth=auth) as session:
        transport = AsyncTransport(loop=loop, session=session, timeout=10)
        client = Client(wsdl, transport=transport)

        # create the service proxy pointint to our UCM
        service = client.create_service(
            binding_name="{http://www.cisco.com/AXLAPIService/}AXLAPIBinding",
            address=ucm_pub_url,
        )
        print(f"Zeep Setup: {time() - st}s")
        phone_list = await get_phone_list(service)
        # print(client.transport.session)
        print(f"phone List: {time() - st}s")
        await get_phone_list_detail(service, phone_list)
        print(f"Done: {time() - st}s")
コード例 #13
0
    def create_validation_service(self, partners):
        port_name = 'VNifPort1'
        type_address = '/wlpl/BURT-JDIT/ws/VNifV1SOAP'
        binding_name = '{http://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/burt/jdit/ws/VNifV1.wsdl}VNifV1SoapBinding'
        service_name = 'VNifV1Service'
        wsdl = self.wsdl_files['ids_validator_v1']
        if isinstance(partners, list):
            type_address = '/wlpl/BURT-JDIT/ws/VNifV2SOAP'
            binding_name = '{http://www2.agenciatributaria.gob.es/static_files/common/internet/dep/aplicaciones/es/aeat/burt/jdit/ws/VNifV2.wsdl}VNifV2SoapBinding'
            service_name = 'VNifV2Service'
            wsdl = self.wsdl_files['ids_validator_v2']
        session = Session()
        session.cert = (self.certificate, self.key)
        session.verify = False
        transport = Transport(session=session)

        client = Client(wsdl=wsdl,
                        port_name=port_name,
                        transport=transport,
                        service_name=service_name)
        if not self.url:
            return client.service
        address = '{0}{1}'.format(self.url, type_address)
        service = client.create_service(binding_name, address)
        return service
コード例 #14
0
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
コード例 #15
0
def create_service(server, username, password):
    session = Session()
    session.auth = HTTPBasicAuth(username, password)
    client = Client(wsdl='http://{}/wsDataServer/MEX?wsdl'.format(server),
                    transport=Transport(session=session))
    return client.create_service(
            '{http://www.totvs.com/}RM_IwsDataServer',
            'http://{}/wsDataServer/IwsDataServer'.format(server))
コード例 #16
0
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
コード例 #17
0
def send_data(data):
    proprietario = {"cfProprietario": data["cfProprietario"]}
    documentoSpesa = {
        "idSpesa": {
            "pIva": data["pIva"],
            "dataEmissione": data["dataEmissione"],
            "numDocumentoFiscale": {"dispositivo": "1", "numDocumento": data["numDocumento"]},
        },
        "dataPagamento": data["dataPagamento"],
        "voceSpesa": [
            {
                "tipoSpesa": data["tipoSpesa"],
                "importo": data["importo"],
                "naturaIVA": data["naturaPrestazione"],
            }
        ],
        "pagamentoTracciato": data["pagamentoTracciato"],
        "tipoDocumento": "F",
        "flagOpposizione": data["flagOpposizione"],
    }
    if "flagPagamentoAnticipato" in data:
        documentoSpesa["flagPagamentoAnticipato"] = data["flagPagamentoAnticipato"]
    if "cfCittadino" in data:
        documentoSpesa["cfCittadino"] = data["cfCittadino"]
    if "bollo" in data:
        documentoSpesa["voceSpesa"].append(
            {
                "tipoSpesa": data["tipoSpesa"],
                "importo": data["bollo"],
                "naturaIVA": data["naturaBollo"],
            }
        )
    session = Session()
    session.verify = VERIFY_SSL
    session.auth = HTTPBasicAuth(data["username"], data["password"])
    client = Client("data/DocumentoSpesa730p.wsdl", transport=Transport(session=session))
    service = client.create_service(
        "{http://documentospesap730.sanita.finanze.it}DocumentoSpesa730pServicePortBinding",
        ENDPOINT,
    )
    try:
        esito = service.Inserimento(
            pincode=data["pincode"],
            Proprietario=proprietario,
            idInserimentoDocumentoFiscale=documentoSpesa,
        )
    except RequestException as e:
        raise ValueError("Errore durante la richiesta: %s" % e)
    if esito["protocollo"]:
        return (True, esito["protocollo"])
    else:
        return (
            False,
            "; ".join(
                [messaggio["descrizione"] for messaggio in esito["listaMessaggi"]["messaggio"]]
            ),
        )
コード例 #18
0
ファイル: panopto.py プロジェクト: harvard-dce/panopto-cli
    def auth_transport(self, transport):

        auth_wsdl = "https://{}/Panopto/PublicAPI/4.2/Auth.svc".format(
            self.host)
        auth_client = Client(auth_wsdl + "?singleWsdl", transport=transport)
        auth_service = auth_client.create_service(binding_name=AUTH_BINDING,
                                                  address=auth_wsdl)
        with auth_client.settings(raw_response=True):
            auth_service.LogOnWithPassword(self.user, self.password)
コード例 #19
0
ファイル: __init__.py プロジェクト: undmicj/cucca
class UcmPerfMonToolkit:
    last_exception = None
    '''
    Constructor - Create new instance 
    '''
    def __init__(self, username, password, server_ip, tls_verify=True):
        wsdl = 'https://{0}:8443/perfmonservice2/services/PerfmonService?wsdl'.format(
            server_ip)
        self.session = Session()
        self.session.auth = HTTPBasicAuth(username, password)
        self.session.verify = tls_verify
        self.cache = SqliteCache(path='/tmp/sqlite_risport.db', timeout=60)
        self.client = Client(wsdl=wsdl,
                             transport=Transport(cache=self.cache,
                                                 session=self.session))
        self.service = self.client.create_service(
            "{http://schemas.cisco.com/ast/soap}PerfmonBinding",
            "https://{0}:8443/perfmonservice2/services/PerfmonService".format(
                server_ip))
        # enable_logging()

    def get_service(self):
        return self.service

    def perfmonOpenSession(self):
        session_handle = self.service.perfmonOpenSession()
        return session_handle

    def perfmonAddCounter(self, session_handle, counters):
        '''
        :param session_handle: A session Handle returned from perfmonOpenSession()
        :param counters: An array of counters or a single string for a single counter
        :return: True for Success and False for Failure
        '''

        if isinstance(counters, list):
            counter_data = [{'Counter': []}]

            for counter in counters:
                new_counter = {'Name': counter}
                counter_data[0]['Counter'].append(new_counter)

        elif counters is not None:
            counter_data = [{'Counter': [{'Name': counters}]}]

        try:
            self.service.perfmonAddCounter(SessionHandle=session_handle,
                                           ArrayOfCounter=counter_data)
            result = True
        except:
            result = False

        return result

    def perfmonCollectSessionData(self, session_handle):
        return self.service.perfmonCollectSessionData(
            SessionHandle=session_handle)
コード例 #20
0
ファイル: axl_zeep.py プロジェクト: sanzcarlos/CiscoCollab
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
コード例 #21
0
ファイル: main.py プロジェクト: npetreley/IPPS
    def getPhones(self):

        client = Client(WSDL_URL,
                        settings=settings,
                        transport=transport,
                        plugins=[MyLoggingPlugin(), history])
        service = client.create_service(
            "{http://schemas.cisco.com/ast/soap}RisBinding", CUCM_URL)

        phone_data = {
            'StateInfo': '',
            'CmSelectionCriteria': {
                'MaxReturnedDevices': '1000',
                'DeviceClass': 'Phone',
                'Model': '255',
                'Status': 'Registered',
                'NodeName': '',
                'SelectBy': 'Description',
                'SelectItems': {
                    'item': {
                        'Item': '*'
                    }
                }
            }
        }

        try:
            cm_resp = service.selectCmDevice(**phone_data)
        except Fault as err:
            print("Zeep error: {0}".format(err))
        else:
            DevFound = cm_resp['SelectCmDeviceResult']['TotalDevicesFound']
            for x in range(DevFound):
                device = cm_resp['SelectCmDeviceResult']['CmNodes']['CmNode'][
                    0]['CmDevices']['CmDevice'][x]
                newPhone = {}
                if device['Httpd'] == 'Yes':
                    name = device['Name']
                    ip = device['IpAddress']
                    ENUM = device['Model']
                    model = get_model(ENUM)
                    newPhone["ip"] = ip
                    newPhone["enum"] = ENUM
                    newPhone["model"] = model
                    self.phoneList[name] = newPhone

            for name in self.phoneList:
                self.phoneBox.addItem(name)
                self.modelBox.addItem(self.phoneList[name]['model'])
                self.ipAddress.setText(self.phoneList[name]['ip'])
                self.Enum.setText(str(self.phoneList[name]['enum']))
            self.phoneBox.setCurrentIndex(0)
            self.modelBox.setCurrentIndex(0)
            name = self.phoneBox.currentText()
            self.ipAddress.setText(self.phoneList[name]['ip'])
            self.Enum.setText(str(self.phoneList[name]['enum']))
コード例 #22
0
def get_service():
    wsdl = 'http://адрес?wsdl'
    session = Session()
    session.auth = HTTPBasicAuth('логин', 'пароль')

    client = Client(wsdl, transport=Transport(session=session))
    # Подмена адреса в wsdl, потребовалась из-за проброса порта с сервера, чтобы иметь возможность показать проект на сдаче
    service = client.create_service('путь который подменяем',
                                    'путь на который подменяем')
    return service
コード例 #23
0
def get_web_payment_details(merchant_id, access_key, token):

    session = Session()
    session.auth = HTTPBasicAuth(merchant_id, access_key)
    client = Client(WSDL, transport=Transport(session=session))
    service = client.create_service(
        '{http://impl.ws.payline.experian.com}WebPaymentAPISoapBinding',
        'https://services.payline.com/V4/services/WebPaymentAPI')

    response = service.getWebPaymentDetails(version=4, token=token)
    return serialize_object(response)
コード例 #24
0
class RisPort70:
    def __init__(self,
                 username,
                 password,
                 hostname,
                 tls_verify=True,
                 timeout=10):
        self.last_exception = None
        wsdl = f'https://{hostname}:8443/realtimeservice2/services/RISService70?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)
        self.history = HistoryPlugin()
        self.client = Client(wsdl=wsdl,
                             transport=transport,
                             plugins=[self.history])
        binding_name = '{http://schemas.cisco.com/ast/soap}RisBinding'
        service_addr = f'https://{hostname}:8443/realtimeservice2/services/RISService70'
        self.service = self.client.create_service(binding_name, service_addr)

    def selectCmDevice(self, data, serialize=False):
        try:
            result = self.service.selectCmDevice(**data)
        except Exception as fault:
            result = None
            self.last_exception = fault
        if serialize is True:
            return serialize_object(result)
        return result

    def selectCmDeviceExt(self, data, serialize=False):
        try:
            result = self.service.selectCmDeviceExt(**data)
        except Exception as fault:
            result = None
            self.last_exception = fault
        if serialize is True:
            return serialize_object(result)
        return result

    def selectCtiItem(self, data, serialize=False):
        try:
            result = self.service.selectCtiItem(**data)
        except Exception as fault:
            result = None
            self.last_exception = fault
        if serialize is True:
            return serialize_object(result)
        return result
コード例 #25
0
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
コード例 #26
0
 def __init__(self):
     try:
         session = Session()
         session.auth = HTTPBasicAuth(axl_client.username,axl_client.password)
         session.verify = False
         transport = Transport(session = session,timeout = 3)
         settings = Settings(strict = False,xml_huge_tree = True)
         plugin = [ MyLoggingPlugin() ] if axl_client.DEBUG else [ ]
         client = Client(wsdl=axl_client.WSDL_FILE,settings = settings,transport=transport, plugins=plugin)
         self.service = client.create_service(axl_client.axl_binding,axl_client.CallManager)
     except Exception as e:
         logger._write("axl initialize failed %s" % e, debugtype="DEBUG")
コード例 #27
0
    def CustomSoapClient (self):
        self.Logger.debug('La direccion IP para la conexion SOAP es: %s' % (self.ipaddress))

        # Comprobamos el SO sobre el que esta funcionando el servidor de Flask
        if platform.system() == 'Windows':
            self.Logger.debug('El sistema operativo es: %s' % (platform.system()))
            CustomWSDL = 'file://' + os.getcwd().replace ("\\","//") + '//Schema//CUCM//' + self.version + '//AXLAPI.wsdl'
        else:
            self.Logger.debug('El sistema operativo es: %s' % (platform.system()))
            CustomWSDL = 'file://' + os.getcwd() + '/Schema/CUCM/' + self.version + '/AXLAPI.wsdl'
        
        self.Logger.debug('El archivo WSDL es: %s' % (CustomWSDL))

        # Definimos la URL de AXL
        self.location = 'https://' + self.ipaddress + ':' + self.port + '/axl/'

        # History shows http_headers
        global CustomHistory
        CustomHistory = HistoryPlugin()

        # The first step is to create a SOAP client session
        CustomSession = 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
        CustomSession.verify = False
        CustomSession.auth = HTTPBasicAuth(self.username, self.password)

        CustomTransport = Transport(session=CustomSession, timeout=10, cache=SqliteCache())

        urllib3.disable_warnings()

        # strict=False is not always necessary, but it allows zeep to parse imperfect XML
        CustomSettings = Settings(strict=False, xml_huge_tree=True)

        try:
            CustomSOAPClient = Client(CustomWSDL,
                                        settings=CustomSettings,
                                        transport=CustomTransport,
                                        plugins=[MyLoggingPlugin(),CustomHistory],
            )

            CustomService = CustomSOAPClient.create_service("{http://www.cisco.com/AXLAPIService/}AXLAPIBinding", self.location)
        except:
            self.Logger.error('Se ha producido un error al crear el cliente SOAP')
            self.Logger.debug(sys.exc_info())
            self.Logger.error(sys.exc_info()[1])
            sys.exit()
        else:
            self.Logger.info('Se ha creado el cliente SOAP')
            return (CustomService)
コード例 #28
0
ファイル: gus.py プロジェクト: bogdal/django-gusregon
 def __init__(self, api_key=None, sandbox=False):
     if not any([api_key, sandbox]):
         raise AttributeError('Api key is required.')
     self.api_key = api_key
     self.sandbox = sandbox
     if sandbox:
         self.api_key = api_key or 'abcde12345abcde12345'
         self.endpoint = ENDPOINT_SANDBOX
     transport = Transport(session=Session())
     transport.session.headers = self.headers
     client = Client(WSDL, transport=transport)
     self.service = client.create_service('{http://tempuri.org/}e3', self.endpoint)
     self.headers.update({'sid': self._service('Zaloguj', self.api_key)})
コード例 #29
0
ファイル: gus.py プロジェクト: matmoscicki/gusregon
 def __init__(self, api_key=None, sandbox=False):
     if not any([api_key, sandbox]):
         raise AttributeError('Api key is required.')
     self.api_key = api_key
     self.sandbox = sandbox
     if sandbox:
         self.api_key = api_key or 'abcde12345abcde12345'
         self.endpoint = ENDPOINT_SANDBOX
     transport = Transport(session=Session())
     transport.session.headers = self.headers
     client = Client(WSDL, transport=transport)
     self.service = client.create_service('{http://tempuri.org/}e3', self.endpoint)
     self.headers.update({'sid': self._service('Zaloguj', self.api_key)})
コード例 #30
0
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 userid in data_from_file():

        try:

            mystuff = myvariables(axl, userid)
            print(mystuff)

            cfwd = {'forwardToVoiceMail': VMFWD,
                    'callingSearchSpaceName': {'_value_1': CSSFWD},
                    'destination': None}

            cfwur = {'forwardToVoiceMail': VMFWD,
                        'callingSearchSpaceName': {'_value_1': CFWUR_CSS},
                        'destination': mystuff['fwddn']}

            updateLine(axl,
                       '\\' + str(mystuff['fwddn']),
                       mystuff['pt'],
                       SITE,
                       mystuff['firstname'],
                       mystuff['lastname'],
                       mystuff['ext'],
                       cfwd,
                       cfwur,
                       )
            updateUDP(axl,
                      mystuff['udp'],
                      SITE,
                      mystuff['firstname'],
                      mystuff['lastname'],
                      mystuff['ext']
                      )
        except:
            print('No user ID found for: ' + userid)
            pass
コード例 #31
0
ファイル: __init__.py プロジェクト: rxavier1979/axltoolkit
class PawsToolkit:

    last_exception = None
    '''

    Constructor - Create new instance 

    '''
    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 get_service(self):
        return self.service

    def get_hardware_information(self):
        hw_info = self.service.getHardwareInformation()

        return hw_info
コード例 #32
0
ファイル: connection.py プロジェクト: may-day/olap
class XMLAConnection(object):
    
    @classmethod
    def addMethod(cls, funcname, func):
        return setattr(cls, funcname, func)

        
    @classmethod
    def setupMembers(cls):
        def getFunc(schemaName):
            return lambda this, *args, **kw: cls.Discover(this, 
                                                          schemaName, 
                                                          *args, **kw)
        
        for schemaName in xmla1_1_rowsets:
            mname = schemaNameToMethodName(schemaName)
            cls.addMethod( mname, getFunc(schemaName) )

    def __init__(self, url, location, sslverify, **kwargs):

        if "session" in kwargs:
            session = kwargs["session"]
            del kwargs["session"]
            transport = Transport(session=session)
        else:
            transport = Transport()
            
        if "auth" in kwargs:
            transport.session.auth = kwargs["auth"]
            del kwargs["auth"]

        transport.session.verify = sslverify
        self.sessionplugin=SessionPlugin(self)
        plugins=[self.sessionplugin]

        if "log" in kwargs:
            log = kwargs.get("log")
            if isinstance(log, Plugin):
                plugins.append(log)
            elif log == True:
                plugins.append(LogRequest())
            del kwargs["log"]
            
        self.client = Client(url, 
                             transport=transport, 
                             # cache=None, unwrap=False,
                             plugins=plugins)

        self.service = self.client.create_service(ns_name(schema_xmla,"MsXmlAnalysisSoap"), location)
        self.client.set_ns_prefix(None, schema_xmla)
        # optional, call might fail
        self.getMDSchemaLevels = lambda *args, **kw: self.Discover("MDSCHEMA_LEVELS", 
                                                                   *args, **kw)
        self.setListenOnSessionId(False)
        self.setSessionId(None)
        self._soapheaders=None
             

    def getListenOnSessionId(self):
        return self.listenOnSessionId

    def setListenOnSessionId(self, trueOrFalse):
        self.listenOnSessionId = trueOrFalse

    def setSessionId(self, sessionId):
        self.sessionId = sessionId
        
    def Discover(self, what, restrictions=None, properties=None):
        rl = as_etree(restrictions, "RestrictionList")
        pl = as_etree(properties, "PropertyList")
        try:
            #import pdb; pdb.set_trace()
            doc=self.service.Discover(RequestType=what, Restrictions=rl, Properties=pl, _soapheaders=self._soapheaders)
            root = fromETree(doc.body["return"]["_value_1"], ns=schema_xmla_rowset)
            res = getattr(root, "row", [])
            if res:
                res = aslist(res)
        except Fault as fault:
            raise XMLAException(fault.message, dictify(fromETree(fault.detail, ns=None)))
        #logger.debug( res )
        return res


    def Execute(self, command, dimformat="Multidimensional", 
                axisFormat="TupleFormat", **kwargs):
        if isinstance(command, stringtypes):
            command=as_etree({"Statement": command})
        props = {"Format":dimformat, "AxisFormat":axisFormat}
        props.update(kwargs)

        plist = as_etree({"PropertyList":props})
        try:
            
            res = self.service.Execute(Command=command, Properties=plist, _soapheaders=self._soapheaders)
            root = res.body["return"]["_value_1"]
            return TupleFormatReader(fromETree(root, ns=schema_xmla_mddataset))
        except Fault as fault:
            raise XMLAException(fault.message, dictify(fromETree(fault.detail, ns=None)))
        
        
    def BeginSession(self):
        bs= self.client.get_element(ns_name(schema_xmla,"BeginSession"))(mustUnderstand=1)
        self.setListenOnSessionId(True)
        cmd = as_etree("Statement")

        self.service.Execute(Command=cmd,_soapheaders={"BeginSession":bs})
        self.setListenOnSessionId(False)

        sess= self.client.get_element(ns_name(schema_xmla,"Session"))(SessionId=self.sessionId, mustUnderstand = 1)
        self._soapheaders={"Session":sess}
        
    def EndSession(self):
        if self.sessionId is not None:
            es= self.client.get_element(ns_name(schema_xmla,"EndSession"))(SessionId=self.sessionId, mustUnderstand = 1)
            cmd = as_etree("Statement")
            self.service.Execute(Command=cmd, _soapheaders={"EndSession":es})
            self.setSessionId(None)
            self._soapheaders=None
コード例 #33
0
def test_xop():
    wsdl_main = StringIO("""
        <?xml version="1.0"?>
        <wsdl:definitions
          xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          xmlns:tns="http://tests.python-zeep.org/xsd-main"
          xmlns:sec="http://tests.python-zeep.org/wsdl-secondary"
          xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
          xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/"
          targetNamespace="http://tests.python-zeep.org/xsd-main">
          <wsdl:types>
            <xsd:schema
                targetNamespace="http://tests.python-zeep.org/xsd-main"
                xmlns:tns="http://tests.python-zeep.org/xsd-main">
              <xsd:complexType name="responseTypeSimple">
                <xsd:sequence>
                  <xsd:element name="BinaryData" type="xsd:base64Binary"/>
                </xsd:sequence>
              </xsd:complexType>
              <xsd:complexType name="BinaryDataType">
                <xsd:simpleContent>
                  <xsd:extension base="xsd:base64Binary">
                    <xsd:anyAttribute namespace="##other" processContents="lax"/>
                  </xsd:extension>
                </xsd:simpleContent>
              </xsd:complexType>
              <xsd:complexType name="responseTypeComplex">
                <xsd:sequence>
                  <xsd:element name="BinaryData" type="tns:BinaryDataType"/>
                </xsd:sequence>
              </xsd:complexType>
              <xsd:element name="input" type="xsd:string"/>
              <xsd:element name="resultSimple" type="tns:responseTypeSimple"/>
              <xsd:element name="resultComplex" type="tns:responseTypeComplex"/>
            </xsd:schema>
          </wsdl:types>

          <wsdl:message name="dummyRequest">
            <wsdl:part name="response" element="tns:input"/>
          </wsdl:message>
          <wsdl:message name="dummyResponseSimple">
            <wsdl:part name="response" element="tns:resultSimple"/>
          </wsdl:message>
          <wsdl:message name="dummyResponseComplex">
            <wsdl:part name="response" element="tns:resultComplex"/>
          </wsdl:message>

          <wsdl:portType name="TestPortType">
            <wsdl:operation name="TestOperation1">
              <wsdl:input message="dummyRequest"/>
              <wsdl:output message="dummyResponseSimple"/>
            </wsdl:operation>
            <wsdl:operation name="TestOperation2">
              <wsdl:input message="dummyRequest"/>
              <wsdl:output message="dummyResponseComplex"/>
            </wsdl:operation>
          </wsdl:portType>

          <wsdl:binding name="TestBinding" type="tns:TestPortType">
            <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
            <wsdl:operation name="TestOperation1">
              <soap:operation soapAction="urn:dummyRequest"/>
              <wsdl:input>
                <soap:body use="literal"/>
              </wsdl:input>
              <wsdl:output>
                <soap:body use="literal"/>
              </wsdl:output>
            </wsdl:operation>
            <wsdl:operation name="TestOperation2">
              <soap:operation soapAction="urn:dummyRequest"/>
              <wsdl:input>
                <soap:body use="literal"/>
              </wsdl:input>
              <wsdl:output>
                <soap:body use="literal"/>
              </wsdl:output>
            </wsdl:operation>
          </wsdl:binding>
          <wsdl:service name="TestService">
            <wsdl:documentation>Test service</wsdl:documentation>
            <wsdl:port name="TestPortType" binding="tns:TestBinding">
              <soap:address location="http://tests.python-zeep.org/test"/>
            </wsdl:port>
          </wsdl:service>
        </wsdl:definitions>
    """.strip())

    client = Client(wsdl_main, transport=Transport())
    service = client.create_service(
        "{http://tests.python-zeep.org/xsd-main}TestBinding",
        "http://tests.python-zeep.org/test")

    content_type = 'multipart/related; boundary="boundary"; type="application/xop+xml"; start="<soap:Envelope>"; start-info="application/soap+xml; charset=utf-8"'

    response1 = '\r\n'.join(line.strip() for line in """
        Content-Type: application/xop+xml; charset=utf-8; type="application/soap+xml"
        Content-Transfer-Encoding: binary
        Content-ID: <soap:Envelope>

        <?xml version="1.0" encoding="UTF-8"?>
        <soap:Envelope
            xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:xop="http://www.w3.org/2004/08/xop/include"
            xmlns:test="http://tests.python-zeep.org/xsd-main">
            <soap:Body>
                <test:resultSimple>
                    <test:BinaryData>
                        <xop:Include href="cid:id4"/>
                    </test:BinaryData>
                </test:resultSimple>
            </soap:Body>
        </soap:Envelope>
        --boundary
        Content-Type: application/binary
        Content-Transfer-Encoding: binary
        Content-ID: <id4>

        BINARYDATA
        --boundary--
    """.splitlines())

    response2 = '\r\n'.join(line.strip() for line in """
        Content-Type: application/xop+xml; charset=utf-8; type="application/soap+xml"
        Content-Transfer-Encoding: binary
        Content-ID: <soap:Envelope>

        <?xml version="1.0" encoding="UTF-8"?>
        <soap:Envelope
            xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:xop="http://www.w3.org/2004/08/xop/include"
            xmlns:test="http://tests.python-zeep.org/xsd-main">
            <soap:Body>
                <test:resultComplex>
                    <test:BinaryData>
                        <xop:Include href="cid:id4"/>
                    </test:BinaryData>
                </test:resultComplex>
            </soap:Body>
        </soap:Envelope>
        --boundary
        Content-Type: application/binary
        Content-Transfer-Encoding: binary
        Content-ID: <id4>

        BINARYDATA

        --boundary--
    """.splitlines())

    print(response1)
    with requests_mock.mock() as m:
        m.post('http://tests.python-zeep.org/test',
               content=response2.encode("utf-8"),
               headers={"Content-Type": content_type})
        result = service.TestOperation2("")
        assert result["_value_1"] == "BINARYDATA".encode()

        m.post(
            'http://tests.python-zeep.org/test',
            content=response1.encode("utf-8"),
            headers={"Content-Type": content_type})
        result = service.TestOperation1("")
        assert result == "BINARYDATA".encode()