def add_agent(system_info, hardware, username=None, customer_name=None, uri=None, method=None): """Add a new agent to the database Args: system_info (dict): Dictionary with system related info hardware (list): List of dictionaries that rpresent the hardware Kwargs: user_name (str): The name of the user who called this function. customer_name (str): The name of the customer. uri (str): The uri that was used to call this function. method (str): The HTTP methos that was used to call this function. Basic Usage: >>> from vFense.core.agent.agents import add_agent Returns: Dictionary """ results = {ApiResultKeys.USERNAME: username, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method} try: now = time() agent_data = {} agent_data[AgentKey.AgentStatus] = AgentStatusKeys.UP agent_data[AgentKey.MachineType] = AgentVirtualKeys.PHYSICAL agent_data[AgentKey.Tags] = [] agent_data[AgentKey.NeedsReboot] = CommonKeys.NO agent_data[AgentKey.DisplayName] = None agent_data[AgentKey.HostName] = None agent_data[AgentKey.CustomerName] = customer_name agent_data[AgentKey.Hardware] = hardware if not AgentKey.ProductionLevel in system_info: agent_data[AgentKey.ProductionLevel] = ProductionLevels.PRODUCTION if customer_name != "default": cexists = get_customer(customer_name) if not cexists and len(customer_name) >= 1: customer = Customer(customer_name) create_customer(customer, username=username, uri=uri, method=method) for key, value in system_info.items(): agent_data[key] = value agent_data[AgentKey.LastAgentUpdate] = DbTime.epoch_time_to_db_time(now) object_status, object_count, error, generated_ids = insert_agent_data(agent_data) if object_status == DbCodes.Inserted and object_count > 0: agent_id = generated_ids.pop() Hardware().add(agent_id, agent_data[AgentKey.Hardware]) data = { AgentKey.AgentId: agent_id, AgentKey.CustomerName: agent_data[AgentKey.CustomerName], AgentKey.ComputerName: agent_data[AgentKey.ComputerName], AgentKey.Hardware: agent_data[AgentKey.Hardware], AgentKey.Tags: agent_data[AgentKey.Tags], AgentKey.OsCode: agent_data[AgentKey.OsCode], AgentKey.OsString: agent_data[AgentKey.OsString], } msg = "new agent_operation succeeded" generic_status_code = GenericCodes.ObjectCreated vfense_status_code = AgentResultCodes.NewAgentSucceeded results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code results[ApiResultKeys.MESSAGE] = msg results[ApiResultKeys.DATA] = [data] results[ApiResultKeys.GENERATED_IDS] = [agent_id] elif object_status == DbCodes.Errors: msg = "new agent operation failed" % (error) generic_status_code = GenericFailureCodes.FailedToCreateObject vfense_status_code = AgentFailureResultCodes.NewAgentFailed results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code results[ApiResultKeys.MESSAGE] = msg except Exception as e: logger.exception(e) msg = "new agent operation failed" % (e) generic_status_code = GenericFailureCodes.FailedToCreateObject vfense_status_code = AgentFailureResultCodes.NewAgentFailed results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code results[ApiResultKeys.MESSAGE] = msg return results
def delete(self, customer_name): active_user = self.get_current_user() uri = self.request.uri method = self.request.method try: deleted_agents = ( self.arguments.get( ApiArguments.DELETE_ALL_AGENTS ) ) move_agents_to_customer = ( self.arguments.get( ApiArguments.MOVE_AGENTS_TO_CUSTOMER, None ) ) sched = self.application.scheduler jobs = sched.get_jobs(name=customer_name) if move_agents_to_customer: customer_exist = get_customer(move_agents_to_customer) if not customer_exist: msg = 'customer %s does not exist' % (move_agents_to_customer) data = { ApiResultKeys.INVALID_ID: move_agents_to_customer, ApiResultKeys.MESSAGE: msg, ApiResultKeys.VFENSE_STATUS_CODE: CustomerFailureCodes.CustomerDoesNotExist } results = ( Results( active_user, uri, method ).invalid_id(**data) ) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) else: results = ( remove_customer( customer_name, active_user, uri, method ) ) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) if (results[ApiResultKeys.VFENSE_STATUS_CODE] == CustomerCodes.CustomerDeleted): change_customer_for_all_agents_in_customer( customer_name, move_agents_to_customer ) change_customer_for_apps_in_customer( customer_name, move_agents_to_customer ) for job in jobs: sched.unschedule_job(job) elif deleted_agents == ApiValues.YES: results = ( remove_customer( customer_name, active_user, uri, method ) ) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) if (results[ApiResultKeys.VFENSE_STATUS_CODE] == CustomerCodes.CustomerDeleted): remove_all_agents_for_customer(customer_name) remove_all_apps_for_customer(customer_name) for job in jobs: sched.unschedule_job(job) elif deleted_agents == ApiValues.NO: results = ( remove_customer( customer_name, active_user, uri, method ) ) for job in jobs: sched.unschedule_job(job) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) else: results = ( GenericResults( active_user, uri, method ).incorrect_arguments() ) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) except Exception as e: results = ( GenericResults( active_user, uri, method ).something_broke(active_user, 'User', e) ) logger.exception(e) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4))
def add_agent(system_info, hardware, username=None, customer_name=None, uri=None, method=None): """Add a new agent to the database Args: system_info (dict): Dictionary with system related info hardware (list): List of dictionaries that rpresent the hardware Kwargs: user_name (str): The name of the user who called this function. customer_name (str): The name of the customer. uri (str): The uri that was used to call this function. method (str): The HTTP methos that was used to call this function. Basic Usage: >>> from vFense.core.agent.agents import add_agent Returns: Dictionary """ results = { ApiResultKeys.USERNAME: username, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method } try: now = time() agent_data = {} agent_data[AgentKey.AgentStatus] = AgentStatusKeys.UP agent_data[AgentKey.MachineType] = AgentVirtualKeys.PHYSICAL agent_data[AgentKey.Tags] = [] agent_data[AgentKey.NeedsReboot] = CommonKeys.NO agent_data[AgentKey.DisplayName] = None agent_data[AgentKey.HostName] = None agent_data[AgentKey.CustomerName] = customer_name agent_data[AgentKey.Hardware] = hardware if not AgentKey.ProductionLevel in system_info: agent_data[AgentKey.ProductionLevel] = ProductionLevels.PRODUCTION if customer_name != 'default': cexists = get_customer(customer_name) if not cexists and len(customer_name) >= 1: customer = Customer(customer_name) create_customer(customer, username=username, uri=uri, method=method) for key, value in system_info.items(): agent_data[key] = value agent_data[AgentKey.LastAgentUpdate] = ( DbTime.epoch_time_to_db_time(now)) object_status, object_count, error, generated_ids = ( insert_agent_data(agent_data)) if object_status == DbCodes.Inserted and object_count > 0: agent_id = generated_ids.pop() Hardware().add(agent_id, agent_data[AgentKey.Hardware]) data = { AgentKey.AgentId: agent_id, AgentKey.CustomerName: agent_data[AgentKey.CustomerName], AgentKey.ComputerName: agent_data[AgentKey.ComputerName], AgentKey.Hardware: agent_data[AgentKey.Hardware], AgentKey.Tags: agent_data[AgentKey.Tags], AgentKey.OsCode: agent_data[AgentKey.OsCode], AgentKey.OsString: agent_data[AgentKey.OsString], } msg = 'new agent_operation succeeded' generic_status_code = GenericCodes.ObjectCreated vfense_status_code = AgentResultCodes.NewAgentSucceeded results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code results[ApiResultKeys.MESSAGE] = msg results[ApiResultKeys.DATA] = [data] results[ApiResultKeys.GENERATED_IDS] = [agent_id] elif object_status == DbCodes.Errors: msg = 'new agent operation failed' % (error) generic_status_code = GenericFailureCodes.FailedToCreateObject vfense_status_code = AgentFailureResultCodes.NewAgentFailed results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code results[ApiResultKeys.MESSAGE] = msg except Exception as e: logger.exception(e) msg = 'new agent operation failed' % (e) generic_status_code = GenericFailureCodes.FailedToCreateObject vfense_status_code = AgentFailureResultCodes.NewAgentFailed results[ApiResultKeys.GENERIC_STATUS_CODE] = generic_status_code results[ApiResultKeys.VFENSE_STATUS_CODE] = vfense_status_code results[ApiResultKeys.MESSAGE] = msg return results
def delete(self, customer_name): active_user = self.get_current_user() uri = self.request.uri method = self.request.method try: deleted_agents = (self.arguments.get( ApiArguments.DELETE_ALL_AGENTS)) move_agents_to_customer = (self.arguments.get( ApiArguments.MOVE_AGENTS_TO_CUSTOMER, None)) sched = self.application.scheduler jobs = sched.get_jobs(name=customer_name) if move_agents_to_customer: customer_exist = get_customer(move_agents_to_customer) if not customer_exist: msg = 'customer %s does not exist' % ( move_agents_to_customer) data = { ApiResultKeys.INVALID_ID: move_agents_to_customer, ApiResultKeys.MESSAGE: msg, ApiResultKeys.VFENSE_STATUS_CODE: CustomerFailureCodes.CustomerDoesNotExist } results = (Results(active_user, uri, method).invalid_id(**data)) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) else: results = (remove_customer(customer_name, active_user, uri, method)) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) if (results[ApiResultKeys.VFENSE_STATUS_CODE] == CustomerCodes.CustomerDeleted): change_customer_for_all_agents_in_customer( customer_name, move_agents_to_customer) change_customer_for_apps_in_customer( customer_name, move_agents_to_customer) for job in jobs: sched.unschedule_job(job) elif deleted_agents == ApiValues.YES: results = (remove_customer(customer_name, active_user, uri, method)) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) if (results[ApiResultKeys.VFENSE_STATUS_CODE] == CustomerCodes.CustomerDeleted): remove_all_agents_for_customer(customer_name) remove_all_apps_for_customer(customer_name) for job in jobs: sched.unschedule_job(job) elif deleted_agents == ApiValues.NO: results = (remove_customer(customer_name, active_user, uri, method)) for job in jobs: sched.unschedule_job(job) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) else: results = (GenericResults(active_user, uri, method).incorrect_arguments()) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4)) except Exception as e: results = (GenericResults(active_user, uri, method).something_broke( active_user, 'User', e)) logger.exception(e) self.set_status(results['http_status']) self.set_header('Content-Type', 'application/json') self.write(json.dumps(results, indent=4))
def create_user( username, fullname, password, group_ids, customer_name, email, enabled=CommonKeys.YES, user_name=None, uri=None, method=None ): """Add a new user into vFense Args: username (str): The name of the user you are creating. fullname (str): The full name of the user you are creating. password (str): The unencrypted password of the user. group_ids (list): List of vFense group ids to add the user too. customer_name (str): The customer, this user will be part of. email (str): Email address of the user. enabled (str): yes or no Default=no Kwargs: user_name (str): The name of the user who called this function. uri (str): The uri that was used to call this function. method (str): The HTTP methos that was used to call this function. Basic Usage: >>> from vFense.user.users import create_user >>> username = '******' >>> fullname = 'testing 4 life' >>> password = '******' >>> group_ids = ['8757b79c-7321-4446-8882-65457f28c78b'] >>> customer_name = 'default' >>> email = '*****@*****.**' >>> enabled = 'yes' >>> create_user( username, fullname, password, group_ids, customer_name, email, enabled ) Return: Dictionary of the status of the operation. { 'uri': None, 'rv_status_code': 1010, 'http_method': None, 'http_status': 200, 'message': 'None - create user testing123 was created', 'data': { 'current_customer': 'default', 'full_name': 'tester4life', 'default_customer': 'default', 'password': '******', 'user_name': 'testing123', 'enabled': 'yes', 'email': '*****@*****.**' } } """ user_exist = get_user(username) pass_strength = check_password(password) status = create_user.func_name + ' - ' generated_ids = [] generic_status_code = 0 vfense_status_code = 0 user_data = ( { UserKeys.CurrentCustomer: customer_name, UserKeys.DefaultCustomer: customer_name, UserKeys.FullName: fullname, UserKeys.UserName: username, UserKeys.Enabled: enabled, UserKeys.Email: email } ) if enabled != CommonKeys.YES or enabled != CommonKeys.NO: enabled = CommonKeys.NO valid_user_name = ( re.search('([A-Za-z0-9_-]{1,24})', username) ) valid_user_length = ( len(username) <= DefaultStringLength.USER_NAME ) try: if (not user_exist and pass_strength[0] and valid_user_length and valid_user_name): encrypted_password = Crypto().hash_bcrypt(password) user_data[UserKeys.Password] = encrypted_password customer_is_valid = get_customer(customer_name) validated_groups, _, invalid_groups = validate_group_ids( group_ids, customer_name ) if customer_is_valid and validated_groups: object_status, _, _, generated_ids = ( insert_user(user_data) ) generated_ids.append(username) add_user_to_customers( username, [customer_name], user_name, uri, method ) add_user_to_groups( username, customer_name, group_ids, user_name, uri, method ) if object_status == DbCodes.Inserted: msg = 'user name %s created' % (username) generic_status_code = GenericCodes.ObjectCreated vfense_status_code = UserCodes.UserCreated user_data.pop(UserKeys.Password) elif not customer_is_valid and validated_groups: msg = 'customer name %s does not exist' % (customer_name) object_status = DbCodes.Skipped generic_status_code = GenericCodes.InvalidId vfense_status_code = CustomerFailureCodes.CustomerDoesNotExist elif not validated_groups and customer_is_valid: msg = 'group ids %s does not exist' % (invalid_groups) object_status = DbCodes.Skipped generic_status_code = GenericCodes.InvalidId vfense_status_code = GroupFailureCodes.InvalidGroupId else: group_error = ( 'group ids %s does not exist' % (invalid_groups) ) customer_error = ( 'customer name %s does not exist' % (customer_name) ) msg = group_error + ' and ' + customer_error object_status = DbCodes.Errors generic_status_code = GenericFailureCodes.FailedToCreateObject vfense_status_code = UserFailureCodes.FailedToCreateUser elif user_exist: msg = 'username %s already exists' % (username) object_status = GenericCodes.ObjectExists generic_status_code = GenericCodes.ObjectExists vfense_status_code = UserFailureCodes.UserNameExists elif not pass_strength[0]: msg = ( 'password does not meet the min requirements: strength=%s' % (pass_strength[1]) ) object_status = GenericFailureCodes.FailedToCreateObject generic_status_code = GenericFailureCodes.FailedToCreateObject vfense_status_code = UserFailureCodes.WeakPassword elif not valid_user_name or not valid_user_length: status_code = DbCodes.Errors msg = ( 'user name is not within the 24 character range '+ 'or contains unsupported characters :%s' % (username) ) generic_status_code = GenericCodes.InvalidId vfense_status_code = UserFailureCodes.InvalidUserName results = { ApiResultKeys.DB_STATUS_CODE: object_status, ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code, ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code, ApiResultKeys.MESSAGE: status + msg, ApiResultKeys.GENERATED_IDS: generated_ids, ApiResultKeys.DATA: [user_data], ApiResultKeys.USERNAME: user_name, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method } except Exception as e: logger.exception(e) msg = 'Failed to create user %s: %s' % (username, str(e)) status_code = DbCodes.Errors generic_status_code = GenericFailureCodes.FailedToCreateObject vfense_status_code = UserFailureCodes.FailedToCreateUser results = { ApiResultKeys.DB_STATUS_CODE: status_code, ApiResultKeys.GENERIC_STATUS_CODE: generic_status_code, ApiResultKeys.VFENSE_STATUS_CODE: vfense_status_code, ApiResultKeys.MESSAGE: status + msg, ApiResultKeys.GENERATED_IDS: [], ApiResultKeys.DATA: [user_data], ApiResultKeys.USERNAME: user_name, ApiResultKeys.URI: uri, ApiResultKeys.HTTP_METHOD: method } return(results)