Created
November 28, 2016 21:27
-
-
Save lukassup/97f47964351442de9649bd6f9b9d03a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import os | |
import requests | |
try: | |
from lxml.etree import ElementTree as ET, Element as E | |
except ImportError: | |
from xml.etree import ElementTree as ET, Element as E | |
SOAP11_HEADERS = {'Content-Type': 'text/xml; charset=utf-8'} | |
SOAP12_HEADERS = {'Content-Type': 'application/soap+xml; charset=utf-8'} | |
SOAP11_ENVELOPE = ('<?xml version="1.0" encoding="utf-8"?>' | |
'<soap:Envelope {namespaces} ' | |
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' | |
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' | |
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' | |
'<soap:Body>{body}</soap:Body>' | |
'</soap:Envelope>') | |
SOAP12_ENVELOPE = ('<?xml version="1.0" encoding="utf-8"?>' | |
'<soap12:Envelope {namespaces} ' | |
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' | |
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' | |
'xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">' | |
'<soap12:Body>{body}</soap12:Body>' | |
'</soap12:Envelope>') | |
def auth_from_env(): | |
env = os.environ.get | |
return (env('SOAP_USERNAME'), env('SOAP_PASSWORD')) | |
def nsformat(namespaces): | |
"""Format a dictionary into valid XML namespaces""" | |
return ' '.join(['xmlns:{0}="{1}"'.format(k, namespaces[k]) | |
for k in namespaces]) | |
def soap11_post(url, body, namespaces=None, action=None, auth=None): | |
"""HTTP POST SOAP version 1.1""" | |
auth = auth or auth_from_env() | |
envelope = SOAP11_ENVELOPE.format( | |
namespaces=nsformat(namespaces), body=body) | |
headers = SOAP11_HEADERS | |
headers['SOAPAction'] = action | |
return requests.post(url, data=envelope, headers=headers, auth=auth) | |
def soap12_post(url, body, namespaces=None, auth=None): | |
"""HTTP POST SOAP version 1.2""" | |
auth = auth or auth_from_env() | |
envelope = SOAP12_ENVELOPE.format( | |
namespaces=nsformat(namespaces), body=body) | |
return requests.post(url, data=envelope, headers=SOAP12_HEADERS, auth=auth) | |
def soap_whois(hostname): | |
"""Retrieve whois result from an external web service using SOAP 1.2""" | |
url = 'http://www.webservicex.net/whois.asmx?WSDL' | |
namespaces = {'ns0': 'http://www.webservicex.net'} | |
body = ('<ns0:GetWhoIS><ns0:HostName>{0}</ns0:HostName></ns0:GetWhoIS>' | |
).format(hostname) | |
return soap12_post(url, body, namespaces) | |
if __name__ == '__main__': | |
import sys | |
print(soap_whois('=google.com').text) | |
sys.exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment