def __init__(self, ReportService, ReportExecution, user, key_password, verbose=True): self.verbose = verbose service_cred = WindowsHttpAuthenticated( username=user, password=key_password) exec_cred = WindowsHttpAuthenticated( username=user, password=key_password) log.basicConfig(filename='SSRS.log', level=log.INFO) try: self.ServiceClient = Client(ReportService, transport=service_cred) self.ExecutionClient = Client(ReportExecution, transport=exec_cred) except BaseException as e: msg = "Error during connection: %s" % e.fault.faultstring log.error(msg) if self.verbose: print(msg) exit()
def connect(domain, username, password): transport = WindowsHttpAuthenticated(username=username, password=password) client = suds.client.Client("https://%s/EWS/Services.wsdl" % domain, transport=transport, plugins=[ewsclient.AddService()]) return client
def upload(setting, product_sales, nav_info): ntlm = WindowsHttpAuthenticated(username=setting.nav_username, password=setting.nav_password) client = Client(setting.nav_url, transport=ntlm) # Create SalesOrder sales_order = new_sales_order(client, nav_info) result = None try: result = client.service.Create(sales_order) #result = client.service.Read('SO16-NAV029066') print result except WebFault as detail: upload_error('Create failed with %s, ERROR: %s\n' % (nav_info, detail)) return sales_order = result now_utc = datetime.now(timezone('UTC')) now_sg = now_utc.astimezone(timezone('Asia/Singapore')) with open(expanduser("~") + '/Documents/nav_record.txt', 'a+') as f: f.write("[%s]Create success with %s, SalesOrder.No = %s\n" % (now_sg, nav_info, sales_order.No)) # Update SalesOrder lines lines = sales_order_lines(client, product_sales) sales_order.SalesLines = lines result = None try: result = client.service.Update(sales_order) except WebFault as detail: upload_error('Update failed with %s, ERROR: %s\n' % (nav_info, detail))
def add_client(): sec_type = self.config['sec_type'] if sec_type == security_def_type.basic_auth: transport = HttpAuthenticated(**self.suds_auth) elif sec_type == security_def_type.ntlm: transport = WindowsHttpAuthenticated(**self.suds_auth) elif sec_type == security_def_type.wss: security = Security() token = UsernameToken(self.suds_auth['username'], self.suds_auth['password']) security.tokens.append(token) client = Client(url, autoblend=True, wsse=security) if sec_type in (security_def_type.basic_auth, security_def_type.ntlm): client = Client(url, autoblend=True, transport=transport) # Still could be either none at all or WSS if not sec_type: client = Client(url, autoblend=True) self.client.queue.put(client) logger.debug('Adding Suds SOAP client to [%s]', url)
def add_client(self): logger.info('About to add a client to `%s` (%s)', self.address, self.conn_type) # Lazily-imported here to make sure gevent monkey patches everything well in advance from suds.client import Client from suds.transport.https import HttpAuthenticated from suds.transport.https import WindowsHttpAuthenticated from suds.wsse import Security, UsernameToken sec_type = self.config['sec_type'] if sec_type == SEC_DEF_TYPE.BASIC_AUTH: transport = HttpAuthenticated(**self.suds_auth) elif sec_type == SEC_DEF_TYPE.NTLM: transport = WindowsHttpAuthenticated(**self.suds_auth) elif sec_type == SEC_DEF_TYPE.WSS: security = Security() token = UsernameToken(self.suds_auth['username'], self.suds_auth['password']) security.tokens.append(token) client = Client(self.address, autoblend=True, wsse=security) if sec_type in(SEC_DEF_TYPE.BASIC_AUTH, SEC_DEF_TYPE.NTLM): client = Client(self.address, autoblend=True, transport=transport) # Still could be either none at all or WSS if not sec_type: client = Client(self.address, autoblend=True, timeout=self.config['timeout']) self.client.put_client(client)
def get_ewsclient(): ews_domain, ews_user, ews_pass = \ map(os.environ.get, ('EWS_DOMAIN', 'EWS_USER', 'EWS_PASS')) transport = WindowsHttpAuthenticated(username=ews_user, password=ews_pass) uri = "https://%s/EWS/Services.wsdl" % ews_domain # Long cache to avoid w3c xml.xsd lifetime issue: client = Client(uri, transport=transport, cache=ObjectCache(weeks=52), plugins=[ewsclient.AddService()]) return client
def test_basic(): domain = os.environ.get('EWS_DOMAIN') username = os.environ.get('EWS_USER') password = os.environ.get('EWS_PASS') transport = WindowsHttpAuthenticated(username=username, password=password) client = suds.client.Client("https://%s/EWS/Services.wsdl" % domain, transport=transport, plugins=[ewsclient.AddService()]) return client
def create_sharepoint_client(self, url, USERNAME=None, PASSWORD=None, **args): if USERNAME and '\\' in USERNAME: from suds.transport.https import WindowsHttpAuthenticated transport = WindowsHttpAuthenticated(username=USERNAME, password=PASSWORD) return self.create_ws_client(url, transport=transport) else: return self.create_ws_client(url, username=USERNAME, password=PASSWORD)
def connect(self): exchangeDigest.ntlm = WindowsHttpAuthenticated(username=self.user, password=self.password) try: exchangeDigest.c = Client(self.wsdl, transport=self.ntlm, location=self.url) except: sys.exit() # build a list of all email id's and key's, then reverse sort xml = self.findItemXML() attr = exchangeDigest.c.service.ResolveNames(__inject={'msg': xml}) try: exchangeDigest.id_key_list = attr.FindItemResponseMessage.RootFolder.Items.Message except AttributeError: exchangeDigest.id_key_list = '99' sys.exit()
def dpapi_purchase_pin(form_fields): if settings.TEST_MODE: status = 1 adv_status = "on Test mode" pin = 111222 return status, adv_status, pin status = 0 pin = None adv_status = '' try: ntlm = WindowsHttpAuthenticated(username='******' % form_fields['username'], password=form_fields['password']) imp = Import('http://schemas.xmlsoap.org/soap/encoding/') imp = Import('http://www.w3.org/2001/XMLSchema') imp.filter.add('https://dollarphone.com/PMAPI/PinManager') doctor = ImportDoctor(imp) try: client = WSClient( "https://www.dollarphone.com/pmapi/PinManager.asmx?WSDL", transport=ntlm, doctor=doctor) except Exception, e: logger.error("Exception: %s. Trace: %s." % (e, traceback.format_exc(limit=10))) raise Exception( 'Failed to initialize dollarphone api, please verify your credentials' ) req = client.factory.create('TopUpReqType') action = client.factory.create('TopUpAction') req.Action = action.PurchasePin req.OfferingId = form_fields['OfferingId'] req.Amount = form_fields['Amount'] req.ProviderId = form_fields['ProviderId'] try: request_pin = client.service.TopUpRequest(req) except Exception, e: raise Exception( 'Failed to initialize dollarphone api, please verify your credentials' )
def __init__(self, config): self.enabled = False enabled = getProperty(config, 'email-enabled') if None != enabled: enabled = enabled.upper() if 'Y' == enabled or 'YES' == enabled: self.enabled = True if not self.enabled: return domain = getProperty(config, 'email-domain') username = getProperty(config, 'email-username') password = getProperty(config, 'email-password') for retries in range(5): try: transport = WindowsHttpAuthenticated(username=username, password=password) self.client = suds.client.Client( "https://%s/EWS/Services.wsdl" % domain, transport=transport, plugins=[ewsclient.AddService()]) print 'Create email client of "', domain, '". Retries:', retries break except WebFault, f: errMsg = f + '\n' + f.fault except Exception, e: errMsg = e print traceback.print_exc()
def people_search(target, numres, type, creds=None, cookie=None, specific_string=None): # Verify input types try: # Process creds, if any if creds is not None: creds = WindowsHttpAuthenticated(username=str(creds[0]), password=str(creds[1])) clnt = client.Client(url=target, transport=creds) elif creds is None and cookie is not None: # TODO Cookie handling here... print( red + "[!]" + endc + " Cookies not yet working for People search. Reverting to unauthenticated..." ) elif creds is None and cookie is None: clnt = client.Client(url=target) # Confirm proper input types numresults = int(numres) restype = str(type) search_text = str(specific_string) except: print(red + "\n[X] " + endc + "Invalid parameter sent to People.asmx searcher" + endc) return 1 # Check to see if the service is accessible... if test_search(target) is False: print( red + "[!]" + endc + " Error encountered. Your current credentials aren't sufficient.") return 1 # If specific_string is not None, do a single search using that string if specific_string is not None: print(yellow + "[*]" + endc + " Performing search for '%s'" % search_text) try: req = clnt.service['PeopleSoap'].SearchPrincipals( search_text, numresults, restype) print req except: print(red + "[!]" + endc + " Error encountered during text search") # Otherwise, continue with automatic search... # alphabetic search else: print(green + "\n[*] " + endc + "Beginning alphabetic People search.\n") # Perform text enumeration via <searchText> parameter try: for c in ascii_lowercase: print(yellow + "[*]" + endc + " Performing search for '%s'" % str(c)) try: req = clnt.service['PeopleSoap'].SearchPrincipals( c, numresults, restype) print req # TODO Cleanly parse through successful alpha results and make the printout look nice except: print(red + "[!]" + endc + " Error encountered during character search") break except KeyboardInterrupt: print(yellow + "[!] " + endc + "Search Interrupted by YOU!\n") except: print(red + "[!] " + endc + "Unknown error occurred during search\n") # Special accounts search print(green + "\n[*] " + endc + "Beginning special accounts search.\n") # Begin making requests for specialized accounts try: for s in request_set: print(yellow + "[*]" + endc + " Performing search for '%s'" % str(s)) try: req = clnt.service['PeopleSoap'].SearchPrincipals( s, numresults, restype) print req # TODO Cleanly parse through successful special results and make the printout look nice except: print(red + "[!]" + endc + " Error encountered during special search") break except requests.HTTPError: logging.error( "Got an HTTP error on an already validated People.aspx; that's sure weird..." ) except: print(red + "\n[!] " + endc + "Error returned for searchString %s\n" % s + endc)
def __init__(self, url, server_nice_name, username, password): self.url = url self.server_nice_name = server_nice_name transport = WindowsHttpAuthenticated(username=str(username), password=str(password)) self.client = suds.client.Client(url=url, transport=transport) self._upload_history = []
def getSiteData(self, site_name, url_prefix, libraries): if (libraries != None): self.logger().info('Running getSiteData for site: [' + site_name + '], for [' + str(libraries.length) + '] libraries') else: self.logger().info('Running Initial Traversal for site: [' + site_name + ']') lib_dict = [] ntlm = WindowsHttpAuthenticated(username=self.SP_DOMAIN + '\\' + self.SP_USER, password=self.SP_PASSWORD) url = url_prefix + '/_vti_bin/SiteData.asmx?WSDL' client = suds.client.Client(url, transport=ntlm) # First get the FolderID number for that site resp = client.service.GetListCollection() for _sList in resp.vLists._sList: if _sList.BaseType == "DocumentLibrary": folder_id = _sList.InternalName self.logger().info('Found [' + _sList.Title + '] of type [' + _sList.BaseType + ']' + ' with Folder ID: ' + folder_id) # get ready to refeed all the doc URLs feed_type = 'metadata-and-url' feed = connector.Feed(feed_type) last_sync = None # See if there is a change token for the current site if (libraries != None): for lib in libraries: if (lib.attributes['id'].value == folder_id): last_sync = lib.attributes['last_sync'].value self.logger().info( 'Retrieved LastChangeToken from file [' + last_sync + ']') # then use that ID to get the document lists ntlm = WindowsHttpAuthenticated(username=self.SP_DOMAIN + '\\' + self.SP_USER, password=self.SP_PASSWORD) url = url_prefix + '/_vti_bin/Lists.asmx?WSDL' client = suds.client.Client(url, transport=ntlm) # attribute used for paging ListItemCollectionPositionNext = '' while (ListItemCollectionPositionNext != None): query = ( '<Query><OrderBy><FieldRef Name="Created" Ascending="TRUE" /></OrderBy></Query>' ) viewfields = '<ViewFields Properties="TRUE"/>' # get 100 rows now per cursor... rowlimit = 100 if (ListItemCollectionPositionNext != ''): queryoptions = ( '<QueryOptions><IncludeMandatoryColumns>true</IncludeMandatoryColumns>' + '<DateInUtc>TRUE</DateInUtc><ViewAttributes Scope="Recursive"/>' + '<Paging ListItemCollectionPositionNext="%s"/>' + '<OptimizeFor>ItemIds</OptimizeFor></QueryOptions>' ) % (escape(ListItemCollectionPositionNext)) else: queryoptions = ( '<QueryOptions><IncludeMandatoryColumns>true</IncludeMandatoryColumns>' + '<DateInUtc>TRUE</DateInUtc><ViewAttributes Scope="Recursive"/>' + '<OptimizeFor>ItemIds</OptimizeFor></QueryOptions>' ) contains = ( '<Contains><FieldRef Name="Status"/><Value Type="Text">Complete</Value></Contains>' ) client.service.GetListItemChangesSinceToken( folder_id, '', Raw(query), Raw(viewfields), rowlimit, Raw(queryoptions), last_sync, Raw(contains)) li = client.last_received().getChild( "soap:Envelope").getChild("soap:Body").getChild( "GetListItemChangesSinceTokenResponse").getChild( "GetListItemChangesSinceTokenResult").getChild( "listitems") # Read the last change token from Sharepoint changes = li.getChild('Changes') if (changes != None): if (changes.getAttribute("LastChangeToken") != None): changeid = changes.getAttribute( "LastChangeToken").getValue() self.logger().info('Found new LastChangeToken [' + changeid + ']') else: self.logger().info('LastChangeToken is None') else: self.logger().info('LastChangeToken is None') rsd = li.getChild("rs:data") # extract out the cursor ListItemCollectionPositionNext if (rsd.getAttribute('ListItemCollectionPositionNext') != None): ListItemCollectionPositionNext = rsd.getAttribute( 'ListItemCollectionPositionNext').getValue() self.logger().info( 'Found response cursor ListItemCollectionPositionNext [' + ListItemCollectionPositionNext + ']') else: ListItemCollectionPositionNext = None # now for each row returned, add that to the feed set for zrow in rsd: if zrow != None: my_url = zrow.getAttribute( "ows_EncodedAbsUrl").getValue() my_last_modified = zrow.getAttribute( "ows_Last_x0020_Modified").getValue() self.logger().debug('Found URL [' + my_url + ']') # set all the attributes for this feed (TODO: set the security SPI parameters) feed.addRecord(url=my_url, displayurl=my_url, action='add', mimetype='text/html') else: break # Finally, save the library name and change token so that the next time, we know where we left off... lib_dict.append('<library id="' + folder_id + '" name="' + _sList.Title + '" last_sync="' + changeid + '" />') # flush the records to the GSA self.logger().info('Transmitting [' + str(len(rsd)) + '] documents.') self.pushFeed(feed) feed.clear() # return the last sync time return lib_dict
def run(self): self.logger().info('TIMER INVOKED for %s ' % self.getName()) self.logger().info('--------------------------------') self.logger().info('----> Start Traversal Run <-----') self.logger().info('--------------------------------') # First get the parameters we need self.SP_URL = self.getConfigParam('SP_URL') self.SP_USER = self.getConfigParam('SP_USER') self.SP_DOMAIN = self.getConfigParam('SP_DOMAIN') self.SP_PASSWORD = self.getConfigParam('SP_PASSWORD') self.SP_STATE = self.getConfigParam('SP_STATE') # go get a list of all the sites below the root: ntlm = WindowsHttpAuthenticated(username=self.SP_DOMAIN + '\\' + self.SP_USER, password=self.SP_PASSWORD) url = self.SP_URL + '/_vti_bin/Webs.asmx?WSDL' client = suds.client.Client(url, transport=ntlm) resp = client.service.GetAllSubWebCollection() resp_site = client.last_received().getChild("soap:Envelope").getChild( "soap:Body").getChild("GetAllSubWebCollectionResponse").getChild( "GetAllSubWebCollectionResult").getChild("Webs") sites = {} for web in resp_site: if web != None: sites[web.getAttribute("Title").getValue()] = web.getAttribute( "Url").getValue() else: break config_state_dict = {} # get the config param to save the last change token per site per document list last_config_state = base64.decodestring(self.SP_STATE) if (last_config_state == ''): last_config_state = '<sites></sites>' # find the current tokens saved to disk xmldoc = xml.dom.minidom.parseString(last_config_state) xsites = xmldoc.getElementsByTagName('site') for xsite in xsites: site_name = xsite.attributes["name"].value libraries = xsite.getElementsByTagName('library') config_state_dict[site_name] = libraries # for each site found, get the url site_config = '' for name in sites: self.logger().info('Found Site ID: [' + name + ' with URL: ' + sites[name] + ']') # see if the current site has its crawltokens saved to disk if (name in config_state_dict): self.logger().info('Calling getSiteData for [' + name + ']') lib_dict = self.getSiteData(name, sites[name], config_state_dict[name]) else: # no previous crawl...so start a new one lib_dict = self.getSiteData(name, sites[name], None) #update the cofnig with the new change tokens # TODO: figure out how to 'save' the new SP_STATE to the config.xml file right here # right now it just saves state when cherrypy is unloaded state_xml = '' # for each document library in this site, add on a new entry with its crawltoken for lib_entry in lib_dict: state_xml = state_xml + lib_entry site_config = site_config + '<site name="' + name + '">' + state_xml + '</site>' last_config_state = '<sites>' + site_config + '</sites>' self.setConfigParam('SP_STATE', base64.encodestring(last_config_state)) self.logger().info('--------------------------------') self.logger().info('-----> End Traversal Run <------') self.logger().info('--------------------------------')
import datetime import os import sys import suds.client import logging from suds.transport.https import WindowsHttpAuthenticated logging.basicConfig(level=logging.DEBUG) email = sys.argv[1] domain = os.environ.get('EWS_DOMAIN') username = os.environ.get('EWS_USER') password = os.environ.get('EWS_PASS') transport = WindowsHttpAuthenticated(username=username, password=password) client = suds.client.Client("https://%s/EWS/Services.wsdl" % domain, transport=transport, plugins=[ewsclient.AddService()]) tz = client.factory.create('t:TimeZone') tz.Bias = 300 tz.StandardTime.Bias = 0 tz.StandardTime.Time = '02:00:00' tz.StandardTime.DayOrder = 1 tz.StandardTime.Month = 11 tz.StandardTime.DayOfWeek = 'Sunday' tz.DaylightTime.Bias = -60
def loadWSDL(self, url): """ This function should be called right after the project_manager has loaded any projects, it will query the PM in order to perform authentication tasks before loading the WSDL and URL objects used to represent the EndPoint. Error handling is a quite a mess here. Default HTTP timeout is set from command line or default (100 seconds) if not specified. The url parameter may point to the offline WSDL copy in the filesystem while pm.getURL() will give EndPoint's addr. A WSDL file can be loaded from it's offline copy while the document contains _a_ valid EndPoint's IP addr. ServiceDefinition @ client.sd ports = (port, [methods]) ports = (port, [(name, [opers])]) ports = (port, [name, [(type, name)]]) """ try: msg = '' # Check for protocol authentication methods if self.project_manager.getAuthType() == AUTH_BASIC: if self.project_manager.getUsername( ) and self.project_manager.getPassword(): try: self.ws_client = Client( url, username=self.project_manager.getUsername(), password=self.project_manager.getPassword(), faults=True, prettyxml=True, cache=None) request = self.project_manager.createAuthorizationRequest( self.project_manager.getUsername(), self.project_manager.getPassword(), self.project_manager.getURL(), self.project_manager.getDomain()) self.server_client = urllib2.urlopen(request) except URLError as e: try: if e.code == 401: msg = 'Error: Something went wrong while trying to authenticate with saved credentials -> %s' % str( e) logger.error( 'Credentials %s:%s [Basic] for project %s stopped working' % (self.project_manager.getUsername(), self.project_manager.getPassword(), self.project_manager.getName())) return msg except: msg = "\tWarning:\nWasn't able to connect to target.\nAntares is running in offline mode now." elif self.project_manager.getAuthType() == AUTH_WINDOWS: # Can we do this? try: import ntlm if self.project_manager.getUsername( ) and self.project_manager.getPassword(): ntlm_transport = WindowsHttpAuthenticated( username='******' % (self.project_manager.getDomain(), self.project_manager.getUsername()), password=self.project_manager.getPassword()) self.server_client = self.project_manager.createNTLMRequest( self.project_manager.getUsername(), self.project_manager.getPassword(), self.project_manager.getURL(), self.project_manager.getDomain()) self.ws_client = Client(url, transport=ntlm_transport, faults=True, prettyxml=True, cache=None) except ImportError: msg = "Error: The project you're trying to load uses Windows authentication\n" msg += "but we couldn't load the proxy_ntlm third party package.\n" msg += "Please install it before proceeding. " return msg except (antaresWrongCredentialsException, TransportError) as e: msg = 'Error: Something went wrong while trying to authenticate with saved credentials -> %s' % str( e) logger.error( 'Credentials %s:%s [NTLM] for project %s stopped working' % (self.project_manager.getUsername(), self.project_manager.getPassword(), self.project_manager.getName())) return msg else: if self.project_manager.getAuthType() == AUTH_UNKNOWN: msg = "Warning: Antares detected an unknown protocol mechanism for this EndPoint!\n" msg = "We probably won't be able to connect to the service." # Or fallback to regular connections self.ws_client = Client(url, faults=True, prettyxml=True, cache=None) self.server_client = urllib2.urlopen( self.project_manager.getURL()) self.setup() if self.ws_client: self.wsdl_desc = WSDLDescription(self.ws_client.sd[0]) msg = 'OK' logger.info("WSDL helper is:\n %s" % self.ws_client) if url.startswith('file'): logger.info("Loaded wsdl from local path %s" % self.project_manager.getWSDLPath()) else: logger.info("Loaded wsdl from remote path %s" % self.project_manager.getURL()) except exceptions.ValueError: msg = "Error: Malformed URL\n" + url except URLError: msg = "Error: No route to host\n " + url except os.error: msg = "Error: Can't read offline WSDL file" except SAXParseException as e: msg = 'Error: Malformed WSDL. Are you sure you provided the correct WSDL path?' except TypeNotFound as e: msg = "Error: There is an import problem with this WSDL.\n We hope to add automatic fix for this in the future." msg += "\nReference is: https://fedorahosted.org/suds/wiki/TipsAndTricks#Schema-TypeNotFound" except TransportError as e: msg = 'Error: Something went wrong while trying to authenticate with saved credentials' logger.error('Credentials %s:%s for project %s stopped working' % (self.project_manager.getUsername(), self.project_manager.getPassword(), self.project_manager.getName())) except Exception as e: msg = 'FATAL: unmanaged exception. Check stderr : ' + e.message print e.__dict__ print type(e) raise antaresUnknownException( "Got unknown exception while loading wsdl at WSDLHelper: %s" % str(e)) # Check how we'll run if self.server_client: self.is_offline = False else: logger.error("Running in offline mode on %s" % url) return msg
def send(self, request): """Overrides HttpTransport.send() to strip the message of linefeeds and non-printing characters.""" request.message = request.message.replace('\n', '').replace('\r', '').replace('\t','') # Remove all whitespaces between '>' and '<' request.message = re.sub(r'> *<', '><', request.message) return WindowsHttpAuthenticated.send(self, request)
from bottle import default_app, response from config import * if authmethod == 'NTLM': from suds.transport.https import WindowsHttpAuthenticated from suds.client import Client import ssl # disable ssl verification for funky certs if hasattr(ssl, '_create_unverified_context'): ssl._create_default_https_context = ssl._create_unverified_context ntlm = WindowsHttpAuthenticated(username=username, password=password) nav = Client(wsdl, transport=ntlm, faults=False) elif authmethod == 'BASIC': from requests import Session from requests.auth import HTTPBasicAuth from zeep import Client from zeep.transports import Transport session = Session() #session.verify = False session.auth = HTTPBasicAuth(username, password) nav = Client(wsdl, transport=Transport(session=session)) app = default_app() @app.hook('after_request') def enable_cors():