def __init__(self): for file in CONFIG_FILES: path = 'system_parameters/' # always use slash filepath = pkg_resources.resource_filename(__name__, path) if not Auth(config_dir=filepath).check_file_exists( CONFIG_FILES[file]): sys.exit("Unable to load file %s/%s" % (filepath, CONFIG_FILES[file]))
def __init__(self, config_dir="config", output="uem.json"): logging.basicConfig(format='%(levelname)s\t%(funcName)s\t%(message)s', level=LOG_LEVEL) # If arguments are used it's passed as None if config_dir is None: config_dir = "config" # Create logging functions self.debug = logging.debug self.info = logging.info self.warning = logging.warning self.error = logging.error self.critical = logging.critical self.output = output self.auth = Auth(config_dir=config_dir)
def __init__(self, config_dir="config", config_file="uem.json", debug=False, bulk_query_trigger=50): # Sort out logging log_level = logging.ERROR if debug: log_level = logging.INFO logging.basicConfig(format='%(levelname)s\t%(funcName)s\t%(message)s', level=log_level) # Create logging functions self.debug = logging.debug self.info = logging.info self.warning = logging.warning self.error = logging.error self.critical = logging.critical # Show sensitve info such as auth headers self.show_sensitive = False # Set max size line to log self.max_log = 9000 # Set a limit of when to swtich to bulk querys self.bulk_query_trigger = bulk_query_trigger # Get config self.config_dir = config_dir self.config = Auth(config_dir).read_config(config_file) if not self.config: self.critical("Unable to get config, run configure.py") self.configure() self.critical("Run again to use config") sys.exit(1) self.info("Imported config - %s" % self.info_sensitive(self.config)) # Create v1 API object headers_v1 = self.create_headers(version=1) self.rest_v1 = REST(url=self.config['url'], headers=headers_v1, proxy=self.import_proxy(), debug=debug) # Create v2 API object headers_v2 = self.create_headers(version=2) self.rest_v2 = REST(url=self.config['url'], headers=headers_v2, proxy=self.import_proxy(), debug=debug)
def test_check_config_dir(): """Test directory related operations""" # Check no folder exists already assert AUTH.check_config_dir() is False # Create directory assert AUTH.create_config_directory() is True # Verify directory exists assert AUTH.check_config_dir() is True # Create read only directory Auth(config_dir="config/readonly").create_config_directory() os.chmod("config/readonly", 444) # Test writing to read only assert Auth( config_dir="config/readonly/test").create_config_directory() is False
def test_write_config(): """Test writing config to files""" # Create some dummy data data = {} data[KEY] = VALUE # Overwrite file from previous test with random data assert AUTH.write_config(data, "test.json") is True # Try to write in a readonly folder assert Auth("config/readonly").write_config(data, "test.json") is False # Try to create a new folder assert Auth("config/newfolder").write_config(data, "test.json") is True # Create new folder in read only will sys.exit with pytest.raises(SystemExit) as pytest_wrapped_e: Auth("config/readonly/newfolder").write_config(data, "test.json") assert pytest_wrapped_e.type == SystemExit
"""Simple example of using the Basic package""" from basic_auth import Auth # Generate config file Auth().basic_config("url", "username", "password") # Read config from file READ = Auth().read_config("basic_config.json") print(READ)
"""Configure Auth for WSO UEM""" import argparse from basic_auth import Auth AUTH = Auth() class Config(): """Configure Auth for WSO UEM""" def __init__(self, output="uem.json"): self.output = output def interactive(self): """Ask the user for the information and format the config""" # Get data from user url = AUTH.ask("AirWatch URL: ") username = AUTH.ask("AirWatch Username: "******"AirWatch Password: "******"AirWatch Tenantcode: ") # Encode data into base64 encoded = AUTH.encode(username, password) # Generate data structure data = AUTH.basic_config_generate(url, encoded) # Add the tentant code data['aw-tenant-code'] = tenant_code # Return the completed data return data
"""Automated testing for configuring WSO""" import os import copy import string import random import argparse from io import StringIO from basic_auth import Auth from wso.configure import Config CONFIG_DIR = "config-tests" # Init package AUTH = Auth(config_dir=CONFIG_DIR) WSO_CONFIG = Config(config_dir=CONFIG_DIR) # Random int / str generators def random_string(string_length=15): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(string_length)) def random_number(): """Generate a random string of fixed length """ return random.randint(0, 9999) # Create some random values to use for testing
class Config(): """Configure Auth for WSO UEM""" def __init__(self, config_dir="config", output="uem.json"): logging.basicConfig(format='%(levelname)s\t%(funcName)s\t%(message)s', level=LOG_LEVEL) # If arguments are used it's passed as None if config_dir is None: config_dir = "config" # Create logging functions self.debug = logging.debug self.info = logging.info self.warning = logging.warning self.error = logging.error self.critical = logging.critical self.output = output self.auth = Auth(config_dir=config_dir) def filter_locals(self, _locals): """Filter some args from local()""" _list = [] _list.append("self") for _item in _list: try: del _locals[_item] except KeyError: pass return _locals def interactive(self): """Ask the user for the information and format the config""" # Get data from user url = self.auth.ask("WSO UEM URL") username = self.auth.ask("WSO UEM Username") password = self.auth.ask("WSO UEM Password") tenant_code = self.auth.ask("WSO UEM Tenant code") proxyserver = self.auth.ask("Proxy server (leave blank for none)") if proxyserver != "": proxyport = self.auth.ask("Proxy port") config_dir = self.auth.ask("Config dir (leave blank for \"config\")") if config_dir == "": config_dir = "config" # TODO: Merge into one function # Encode data into base64 encoded = self.auth.encode(username, password) # Generate data structure data = self.auth.basic_config_generate(url, encoded) # Add the tentant code data['aw-tenant-code'] = tenant_code # Add the proxy settings if proxyserver != "": data['proxyserver'] = proxyserver data['proxyport'] = int(proxyport) # Return the completed data self.info(data) return data def arguments(self, args): """Using data from the arguments format the config""" url = args.url username = args.username password = args.password tenant_code = args.tenantcode try: proxyserver = args.proxyserver proxyport = args.proxyport except AttributeError: proxyserver = None proxyport = None # Encode data into base64 encoded = self.auth.encode(username, password) # Generate data structure data = self.auth.basic_config_generate(url, encoded) # Add the tentant code data['aw-tenant-code'] = tenant_code # Add the proxy settings if proxyserver is not None: data['proxyserver'] = proxyserver data['proxyport'] = proxyport # Return the completed data return data def write_data(self, data, filename): """Write the config to a file""" write = self.auth.write_config(data, filename) return write def get_args(self): # pragma: no cover """Parse arguments and return the namespace""" # This is indirectly tested by the test_main_results() funtion parser = argparse.ArgumentParser() optional = parser.add_argument_group('Optional arguments') optional.add_argument("-url", help="WSO UEM URL") optional.add_argument("-username", help="WSO UEM user") optional.add_argument("-password", help="WSO UEM password") optional.add_argument("-tenantcode", help="WSO UEM tenant code") optional.add_argument("-proxyserver", help="Proxy server") optional.add_argument("-proxyport", help="Proxy port") optional.add_argument("-directory", help="Config dir") args = parser.parse_args() return args def main(self, args): """Main function""" # Check for args if None in (args.url, args.username, args.password, args.tenantcode): # Run in interactive mode print("No arguments found or missing arguments\n\ Running in interactive mode") print("Run with -h for more info") data = self.interactive() else: # Use arguments data = self.arguments(args) # Set config dir if args.directory: self.directory = args.directory # Write the config to file if self.write_data(data, self.output): print("Config sucessfully written") return True # Issue writing to file print("Unable to write config") # pragma: no cover return False # pragma: no cover
"""Automated testing for General BAC""" import os import string import random import argparse from io import StringIO from basic_auth import Auth from Examples.general import Config # Init package AUTH = Auth() CONFIG = Config() # Random int / str generators def random_string(string_length=15): """Generate a random string of fixed length """ letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(string_length)) # Create some random values to use for testing RANDOM_URL = "%s.com" % random_string(8) RANDOM_USERNAME = random_string(8) RANDOM_PASSWORD = random_string() # Build the data structure expected EXPECTED_RESULT = {} EXPECTED_RESULT['authorization'] = AUTH.encode(RANDOM_USERNAME, RANDOM_PASSWORD)
# Create some random values to use for testing RANDOM_URL = "cn%i.awmdmtest.com" % random_number() RANDOM_USERNAME = random_string(8) RANDOM_PASSWORD = random_string() RANDOM_TENANTCODE = random_string() RANDOM_PROXYSERVER = random_string(8) RANDOM_PROXYPORT = random_number() SESSION_ID = random_chars() print('Test session ID: %s' % SESSION_ID) # Create globals UEM = WSO() CONFIG = Auth().read_config("uem.json") CONFIG_DIR = "config-wso-tests" # Init package AUTH = Auth(config_dir=CONFIG_DIR) # Tests def test_bad_config_folder(): """Tests bad config""" with pytest.raises(SystemExit) as pytest_wrapped_e: WSO('notexistantfolder') assert pytest_wrapped_e.type == SystemExit assert pytest_wrapped_e.value.code == 2
"""Testing debugs""" import sys import wso from basic_auth import Auth UEM = wso.WSO(debug=True) # Get device ID from serial SERIAL = Auth().ask("Device serial") DEVICE_ID = UEM.get_device(serial_number=SERIAL)['Id']['Value'] # Get user ID USER = Auth().ask("New user") USERNAME_ID = UEM.get_user(username=USER)['Users'][0]['Id']['Value'] # cChange users if UEM.change_user(DEVICE_ID, USERNAME_ID): # Verify change completed new_user = UEM.get_device(serial_number=SERIAL)['UserName'] if new_user == USER: print("Device %s's owner has been changed to %s" % (SERIAL, new_user)) sys.exit() print("Error changing owner on device %s" % SERIAL)
"""Example on reading config""" from basic_auth import Auth # Get the config from the file CONFIG = Auth().read_config("general.json") if CONFIG: # Print the details print(CONFIG["url"]) print(CONFIG["authorization"]) else: print('Unable to read config')