def build_command_xml(self, wrm_req): """Create a WinRM Command Run Request in XML format. :param wrm_req: The request object containing relevant request data. :returns: An LXML object representing the request xml.""" soap_request = self.get_soap_header( "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command", wrm_req.message_id) ns_w = ElementMaker( namespace="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd") header_element = soap_request.find( "{http://www.w3.org/2003/05/soap-envelope}Header") header_element.append( ns_w.SelectorSet(ns_w.Selector(wrm_req.shell_id, Name="ShellId"))) # TODO: Should the ElementMakers be members? header_element = soap_request.find( "{http://www.w3.org/2003/05/soap-envelope}Header") header_element.append( ns_w.OptionSet(ns_w.Option("TRUE", Name="WINRS_CONSOLEMODE_STDIN"), ns_w.Option("FALSE", Name="WINRS_SKIP_CMD_SHELL"))) ns_env = ElementMaker( namespace="http://www.w3.org/2003/05/soap-envelope") ns_rsp = ElementMaker( namespace="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" ) if wrm_req.arguments: cli_properties = [ ns_rsp.Command(wrm_req.command), ns_rsp.Arguments(wrm_req.arguments) ] else: cli_properties = [ns_rsp.Command(wrm_req.command)] soap_request.append(ns_env.Body(ns_rsp.CommandLine(*cli_properties))) return soap_request
def build_shell_request_xml(self, wrm_req): """Create a WinRM Shell Request in XML format. :param wrm_req: The request object containing relevant request data. :returns: An LXML object representing the request xml.""" soap_request = self.get_soap_header( "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd", "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create", wrm_req.message_id) ns_w = ElementMaker( namespace="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd") ns_env = ElementMaker( namespace="http://www.w3.org/2003/05/soap-envelope") ns_rsp = ElementMaker( namespace="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" ) soap_request.append( ns_env.Body( ns_rsp.Shell( ns_rsp.InputStreams("stdin"), ns_rsp.OutputStreams("stderr stdout"), ))) header_element = soap_request.find( "{http://www.w3.org/2003/05/soap-envelope}Header") header_element.append( ns_w.OptionSet(ns_w.Option("FALSE", Name="WINRS_NOPROFILE"), ns_w.Option("437", Name="WINRS_CODEPAGE"))) return soap_request
def serialize(self, *args, **kwargs): """Create a SerializedMessage for this message""" nsmap = {'soap-env': self.nsmap['soap-env']} nsmap.update(self.wsdl.types._prefix_map_custom) soap = ElementMaker(namespace=self.nsmap['soap-env'], nsmap=nsmap) # Create the soap:header element headers_value = kwargs.pop('_soapheaders', None) header = self._serialize_header(headers_value, nsmap) # Create the soap:body element body = soap.Body() if self.body: body_value = self.body(*args, **kwargs) self.body.render(body, body_value) # Create the soap:envelope envelope = soap.Envelope() if header is not None: envelope.append(header) envelope.append(body) # XXX: This is only used in Soap 1.1 so should be moved to the the # Soap11Binding._set_http_headers(). But let's keep it like this for # now. headers = {'SOAPAction': '"%s"' % self.operation.soapaction} return SerializedMessage(path=None, headers=headers, content=envelope)
def build_command_receive_xml(self, wrm_req): """Create a WinRM Receive Command Response Request in XML format. :param wrm_req: The request object containing relevant request data. :returns: An LXML object representing the request xml.""" ns_w = ElementMaker( namespace="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd") ns_env = ElementMaker( namespace="http://www.w3.org/2003/05/soap-envelope") ns_rsp = ElementMaker( namespace="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" ) soap_request = self.get_soap_header( "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive", wrm_req.message_id) header_element = soap_request.find( "{http://www.w3.org/2003/05/soap-envelope}Header") header_element.append( ns_w.SelectorSet(ns_w.Selector(wrm_req.shell_id, Name="ShellId"))) soap_request.append( ns_env.Body( ns_rsp.Receive( ns_rsp.DesiredStream("stdout stderr", CommandId=wrm_req.command_id)))) return soap_request
def _soap_request(req, url, action): SOAPENV_NS = u'http://schemas.xmlsoap.org/soap/envelope/' S = ElementMaker(namespace=SOAPENV_NS, nsmap={'s':SOAPENV_NS}) sr = S.Envelope( S.Body(req) ) r = Request(url, headers={'soapaction' : action, 'content-type': 'text/xml; charset="utf-8"'}) sr.attrib['{{{pre}}}encodingStyle'.format(pre=SOAPENV_NS)] = 'http://schemas.xmlsoap.org/soap/encoding/' l = urlopen(r,etree.tostring(sr,xml_declaration=True, encoding='utf-8')).read() return etree.fromstring(l)
def serialize(self, *args, **kwargs): """Create a SerializedMessage for this message""" if 'soap' not in self.wsdl.types._prefix_map_custom: nsmap = {"soap-env": self.nsmap["soap-env"]} else: nsmap = {} nsmap.update(self.wsdl.types._prefix_map_custom) soap = ElementMaker(namespace=self.nsmap["soap-env"], nsmap=nsmap) # Create the soap:envelope envelope = soap.Envelope() # Create the soap:header element headers_value = kwargs.pop("_soapheaders", None) header = self._serialize_header(headers_value, nsmap) if header is not None: envelope.append(header) # Create the soap:body element. The _is_body_wrapped attribute signals # that the self.body element is of type soap:body, so we don't have to # create it in that case. Otherwise we create a Element soap:body and # render the content into this. if self.body: body_value = self.body(*args, **kwargs) if self._is_body_wrapped: self.body.render(envelope, body_value) else: body = soap.Body() envelope.append(body) self.body.render(body, body_value) else: body = soap.Body() envelope.append(body) # XXX: This is only used in Soap 1.1 so should be moved to the the # Soap11Binding._set_http_headers(). But let's keep it like this for # now. headers = {"SOAPAction": '"%s"' % self.operation.soapaction} return SerializedMessage(path=None, headers=headers, content=envelope)
def _create_fault(self, faultcode, faultstring): "Compose SOAP fault message" nsmap = { 'soap': NS.SOAP11, 'soapenc': NS.SOAPENC, 'xsi': NS.XSI, 'xsd': NS.XSD, } e = ElementMaker(namespace=NS.SOAP11, nsmap=nsmap) envelope = e.Envelope( e.Body(e.Fault(E.faultcode(faultcode), E.faultstring(faultstring)))) return outer_xml(envelope, True)
def __init__(self): """Creates a SOAP-envelope.""" super(SOAPEnvelope, self).__init__() soap_envelope_maker = ElementMaker( namespace='http://schemas.xmlsoap.org/soap/envelope/', nsmap=dict(soapp='http://schemas.xmlsoap.org/soap/envelope/') ) soap_envelope = soap_envelope_maker.Envelope() soap_body = soap_envelope_maker.Body() soap_body.text = '%s' soap_envelope.append(soap_body) self.envelope = soap_envelope
async def main(): ucm_pub = Soap() soap_action = "listPhone" env_dict = { "soapenv:Envelope": { "@xmlns:soapenv": ucm_pub.soap_ns, "@xmlns:ns0": ucm_pub.axl_ns, "soapenv:Body": { f"ns0:{soap_action}": { "searchCriteria": {"name": "%"}, "returnedTags": None, } }, } } envelope = xmltodict.unparse(env_dict) conenctor = aiohttp.TCPConnector(limit=50) async with aiohttp.ClientSession(connector=conenctor) as session: phone_list = await ucm_pub.send_request(session, soap_action, envelope) soap_action = "getPhone" tasks = [] for phone in phone_list["phone"]: soap = ElementMaker( namespace=ucm_pub.soap_ns, nsmap=ucm_pub.ns_map ) envelope = soap.Envelope() ns = ElementMaker(namespace=ucm_pub.axl_ns) elem = ElementMaker() getPhone = ns(soap_action) uuid = elem("uuid") uuid.text = phone["@uuid"] body = soap.Body() getPhone.append(uuid) body.append(getPhone) envelope.append(body) envelope_string = ET.tostring(envelope) tasks.append( ucm_pub.send_request(session, soap_action, envelope_string) ) phone_details = await asyncio.gather(*tasks, return_exceptions=True) for phone in phone_details: print(phone["phone"]["name"])
def _create_response_envelope(self, header, response, name, namespace): "Compose response envelope" # response is wrapper element of the output message response.tag = '{%s}%sResponse' % (namespace, name) nsmap = {'soap': NS.SOAP11, 'soapenc': NS.SOAPENC, 'xsi': NS.XSI, 'xsd': NS.XSD, 'a': namespace } e = ElementMaker(namespace=NS.SOAP11, nsmap=nsmap) envelope = e.Envelope() if header is not None: envelope.append(header) envelope.append(e.Body(response)) return outer_xml(envelope, True)
def serialize(self, *args, **kwargs): """Create a SerializedMessage for this message""" nsmap = self.nsmap.copy() nsmap.update(self.wsdl.types._prefix_map) soap = ElementMaker(namespace=self.nsmap['soap-env'], nsmap=nsmap) body = header = None # Create the soap:header element headers_value = kwargs.pop('_soapheaders', None) if headers_value: header = soap.Header() if isinstance(headers_value, list): for header_value in headers_value: if hasattr(header_value, '_xsd_elm'): header_value._xsd_elm.render(header, header_value) elif isinstance(header_value, etree._Element): header.append(header_value) else: raise ValueError("Invalid value given to _soapheaders") elif isinstance(headers_value, dict): if not self.headers: raise ValueError( "_soapheaders only accepts a dictionary if the wsdl " "defines the headers.") headers_value = self.headers(**headers_value) self.headers.render(header, headers_value) else: raise ValueError("Invalid value given to _soapheaders") # Create the soap:body element if self.body: body_value = self.body(*args, **kwargs) body = soap.Body() self.body.render(body, body_value) # Create the soap:envelope envelope = soap.Envelope() if header is not None: envelope.append(header) if body is not None: envelope.append(body) headers = {'SOAPAction': '"%s"' % self.operation.soapaction} etree.cleanup_namespaces(envelope) return SerializedMessage(path=None, headers=headers, content=envelope)
def serialize(self, *args, **kwargs): soap = ElementMaker(namespace=self.nsmap['soap-env'], nsmap=self.nsmap) tag_name = etree.QName(self.namespace['body'], self.abstract.name.localname) body = soap.Body() operation = xsd.Element( tag_name, xsd.ComplexType(children=[ xsd.Element(etree.QName(name), message.type) for name, message in self.abstract.parts.items() ])) operation_value = operation(*args, **kwargs) operation.render(body, operation_value) return body, None, None
def _gen_envelope(self, service_name, params, service_version, namespace): "Compose SOAP envelope" # params is SOAP doc/literal wrapper element and must be named by name of the service params.tag = '{%s}%s' % (namespace, service_name) nsmap = { 'soap': NS.SOAP11, 'soapenc': NS.SOAPENC, 'xsi': NS.XSI, 'xsd': NS.XSD, 'a': namespace } nsmap['xrd'] = NS.XROAD4 nsmap['id'] = NS.XROAD4ID e = ElementMaker(namespace=NS.SOAP11, nsmap=nsmap) header = self._gen_header(service_name, service_version) envelope = e.Envelope(header, e.Body(params)) return outer_xml(envelope, True)
def build_xml(num): soap = ElementMaker(namespace='http://schemas.xmlsoap.org/soap/envelope/') tns = ElementMaker(namespace='http://benchmark.python-zeep.org/') body = soap.Body() envelope = soap.Envelope(body) items = tns.items() body.append(items) for i in range(num): item = tns.item( tns.id(str(i)), tns.name('SomeName'), tns.active('true'), tns.price('1234.12'), ) items.append(item) return etree.tostring(envelope, pretty_print=True)
def build_shell_delete_xml(self, wrm_req): """Create a WinRM Shell Delete Request in XML format. :param wrm_req: The request object containing relevant request data. :returns: An LXML object representing the request xml.""" soap_request = self.get_soap_header( "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd", "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete", wrm_req.message_id) ns_w = ElementMaker( namespace="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd") ns_env = ElementMaker( namespace="http://www.w3.org/2003/05/soap-envelope") header_element = soap_request.find( "{http://www.w3.org/2003/05/soap-envelope}Header") header_element.append( ns_w.SelectorSet(ns_w.Selector(wrm_req.shell_id, Name="ShellId"))) soap_request.append(ns_env.Body()) return soap_request
def package(self, request, response, function=None): E = ElementMaker(namespace=self.namespaces.search(SOAP_ENV), nsmap=self.namespaces) wsf = function envelope = E.Envelope( E.Header(), E.Body( E('{%s}%sResponse' % (self.target_ns, wsf.function_name), E('{%s}%sResult' % (self.target_ns, wsf.function_name), response, **{'{%s}type' % self.namespaces.search(XSI): '%s:%s' % (self.namespaces.search(value=wsf.outtype.Meta.namespace), wsf.outtype.Meta.name)} ) ) ) ) return HttpResponse(etree.tostring(envelope), content_type='text/xml')
def serialize(self, *args, **kwargs): nsmap = self.nsmap.copy() nsmap.update(self.wsdl.schema._prefix_map) soap = ElementMaker(namespace=self.nsmap['soap-env'], nsmap=nsmap) body = header = None header_value = kwargs.pop('_soapheader', None) if self.body: body_value = self.body(*args, **kwargs) body = soap.Body() self.body.render(body, body_value) if header_value is not None: if self.header: if isinstance(header_value, dict): header_value = self.header(**header_value) header = soap.Header() self.header.render(header, header_value) elif hasattr(header_value, '_xsd_elm'): header = soap.Header() header_value._xsd_elm.render(header, header_value) elif isinstance(header_value, etree._Element): header = soap.Header(header_value) else: raise ValueError("Invalid value given to _soapheader") # Create the soap:envelope envelope = soap.Envelope() if header is not None: envelope.append(header) if body is not None: envelope.append(body) headers = { 'SOAPAction': self.operation.soapaction or self.operation.name } etree.cleanup_namespaces(envelope) return SerializedMessage( path=None, headers=headers, content=envelope)
def serialize(self, *args, **kwargs): soap = ElementMaker(namespace=self.nsmap['soap-env'], nsmap=self.nsmap) body = header = headerfault = None header_value = kwargs.pop('_soapheader', None) if self.body: body_obj = self.body body_value = body_obj(*args, **kwargs) body = soap.Body() body_obj.render(body, body_value) if self.header: header_obj = self.header if header_value is None: header_value = header_obj() elif not isinstance(header_value, Element): header_value = header_obj(**header_value) header = soap.Header() header_obj.render(header, header_value) headerfault = None return body, header, headerfault
"searchCriteria": {"name": "%"}, "returnedTags": None, } }, } } envelope = xmltodict.unparse(env_dict) phone_list = ucm_pub.send_request(soap_action, envelope) soap_action = "getPhone" for phone in phone_list["phone"]: soap = ElementMaker(namespace=ucm_pub.soap_ns, nsmap=ucm_pub.ns_map) envelope = soap.Envelope() ns = ElementMaker(namespace=ucm_pub.axl_ns) elem = ElementMaker() getPhone = ns(soap_action) uuid = elem("uuid") uuid.text = phone["@uuid"] body = soap.Body() getPhone.append(uuid) body.append(getPhone) envelope.append(body) envelope_string = ET.tostring(envelope) phone_details = ucm_pub.send_request(soap_action, envelope_string) print(phone_details["phone"]["name"])