def process_args_and_login(parser=None, client=None, showparameter=None, fields=None): # initializing command line arguments and variables to be used later args = args_initializer(parser=parser, param=showparameter) global debug global log_file if not showparameter: showparameter = args.showparameter[0] if args.showparameter else None if not fields: try: fields = { "whitelist": args.fields, "blacklist": [], "translate": [] } except AttributeError: fields = { "whitelist": [], "blacklist": [], "translate": [] } management = args.management[0] if args.management else None domain = args.domain[0] if args.domain else None debug = None log_file = None if args.debug[0] == "on": debug = True if (debug or __debug__) and args.log_file is not None: try: log_file = open(args.log_file, "wb") except IOError: debug_log("Could not open given log file for writing, sending debug information to stderr.") # open the output file if given one output_file = open(args.output[0], "wb") if args.output else None output_file_format = args.format[0].lower() user_created = (args.user_created[0].lower() == "true") if args.user_created else True # trying to get login credentials username, password, session_id = get_login_credentials(args.username[0] if args.username else None, args.password[0] if args.password else None, args.session_id[0] if args.session_id else None, args.session_file[0] if args.session_file else None, args.root[0] if args.root else None) debug_log( "Got the following login credentials:\n Username: {0}\n Password: {1}\n Session ID: {2}".format( username, '*' * len(password) if password else None, session_id)) if not args.root or args.root[0] == "true": unsafe = (args.unsafe[0] == "true") unsafe_auto_accept = (args.unsafe_auto_accept[0] == "true") if not client: client = APIClient(APIClientArgs(server=management)) if unsafe or (unsafe_auto_accept and validate_fingerprint_without_prompt(client, management, auto_accept=unsafe_auto_accept)) or client.check_fingerprint(): login(client, management, domain, username, password, session_id) else: raise APIClientException( "The server's fingerprint is different than your local record of it. The script cannot operate in this unsecure manner (unless running with --unsafe). Exiting...") else: login(client, management, domain, session_id=session_id, username=None, password=None) return output_file, output_file_format, user_created, client, args
def main(): global was_changed # Initializing parameters to variables: command = module.params["command"] parameters = module.params.get("parameters") session_data = module.params.get("session-data") fingerprint = module.params.get("fingerprint") if parameters: parameters = json.loads(parameters.replace("'", '"')) if command == "login": # Login parameters: username = parameters.get("user", parameters.get("username")) password = parameters.get("pass", parameters.get("password")) management = parameters.get("management", "127.0.0.1") port = parameters.get("port", 443) domain = parameters.get("domain") session_timeout = parameters.get("session-timeout", 600) payload = {"session-timeout": session_timeout} client_args = APIClientArgs(server=management, port=port) client = APIClient(client_args) # Validate fingerprint: validate_fingerprint(client, fingerprint) # Tries to login: client.login(username=username, password=password, domain=domain, payload=payload) # Building a session data object session_data = { "url": management + ":" + str(port), "domain": domain, "sid": client.sid, "fingerprint": client.fingerprint } resp = session_data else: # Parsing the session-data argument: try: session_data = ast.literal_eval(session_data)["response"] except (ValueError, KeyError): if not session_data: error("You must specify session-data for commands that are not login (use the command \"login\"" " to obtain the session data).") else: error("session-data variable is invalid.") session_id = session_data["sid"] domain = session_data["domain"] management = session_data["url"].split('//')[1].split('/')[0].split(':')[0] if '//' in session_data["url"] else \ session_data["url"].split('/')[0].split(':')[0] fingerprint = session_data["fingerprint"] client_args = APIClientArgs(server=management, sid=session_id) client = APIClient(client_args) client.domain = domain validate_fingerprint(client, fingerprint) # Doesn't run commands that act immediately (not waiting for 'publish'), like install-policy, publish, etc. if module.check_mode and command in unavailable_in_check_commands: error("Can't run the following commands in check mode: " + str(unavailable_in_check_commands) + ". Know that your script ran fine up to this point " + ("and we've discarded the changes made, you can now run it without check mode." if command == "publish" else "and we are skipping this command."), client=client if command == "publish" else None, discard=True, logout=False, exit=True, fail=False) if command == "install-policy" and module.check_mode: command = "verify-policy" parameters = {"policy-package": parameters["policy-package"]} # Run the command: res = client.api_call(command=command, payload=parameters) if command.split("-")[0] in ["add", "delete", "set"] and res.success and not module.check_mode: was_changed = True if not res.success: error("Command '{} {}' failed{}. All changes are discarded and the session is invalidated." .format(command, parameters, " with error message: " + str(res.error_message) if hasattr(res, "error_message") else ""), client=client) resp = res.data module.exit_json(response=resp, changed=was_changed)
if __name__ == "__main__": arg_parser = argparse.ArgumentParser( description="Package Import and Export Tool, V2.0") args = process_arguments(arg_parser) args_for_client = APIClientArgs(server=args.management, port=args.port, sid=args.session_id, debug_file=log_file, api_version=args.version, proxy_host=args.proxy, proxy_port=args.proxy_port, unsafe=args.unsafe, unsafe_auto_accept=args.unsafe_auto_accept) with APIClient(args_for_client) as client: if args.login == '1': login_reply = client.login( username=args.username, password=args.password, domain=args.domain, payload={ "read-only": "true" if args.operation == "export" else "false" }) handle_login_fail( not login_reply.success, "Login to management server failed. " + str(login_reply)) elif args.login == '2': client.login_as_root(domain=args.domain)