def va_disable_deceptionserver(self, server=None, commit=None): ''' API to disable the deception server In this case the policy will not be deleted, just disabled state :param data: :param args: :param kwargs: :return: ''' logger.info("We are in ::" + sys._getframe().f_code.co_name) if not server: raise ValueError(" Policy name is mandatory for setting policy") logger.debug('data1........ in darknet,' + str(data1)) cmds = [] cmds.append('set deception server %s disable' % data1['name']) if commit: cmds.append('commit') logger.info('Darknet command :' + str(cmds)) config_status, output = self._access.va_config(cmds) logger.debug('Configuration of Deception disable: {} :: \ {} '.format(config_status, output)) if config_status is False: logger.error('Configuration/commit FAILED') return False, output else: logger.info('Configuration and commit is successful') logger.debug('Configuration of DARKNET: {} \ :: {} '.format(config_status, output)) return True, output
def va_unconfig_deceptionserver(self, server=None, commit=None): """ API to unconfig darknet policy param : pname : darknet policy name pcommit : commit flag set example : va_unconfig_darknet('darknet1') return : True/False """ logger.info("We are in ::" + sys._getframe().f_code.co_name) if not server: raise ValueError(" Policy name is mandatory for setting policy") cmd = [] cmd.append('unset deception server %s' % (server)) logger.info('Unconfiguring the darknet policy' + str(cmd)) if commit: cmd.append('commit') logger.info("Now commiting the configs") logger.info('Unconfiguring the deception server' + str(cmd)) config_status, output = self._access.va_config(cmd) logger.info("the commit status :" + str(config_status) + str(output)) cmd = 'show running | grep \"deception server\"' logger.info("Executing show command" + str(cmd)) cmdkey = 'set deception server ' + str(server) routput = self._access.va_cli(cmd) logger.info("the execution status :" + str(routput)) logger.debug('Command key to check in running config' + cmdkey) if str(cmdkey) in routput: logger.error('The config not removed from running configs' + str(cmd)) return False, routput logger.debug( 'The given deception server is removed from running configs') return config_status, output
def va_delete_zone(self, *args, **kwargs): """ API to delete zone param : kwargs: 'name' : name of zone 'is_negative' : negative test, True|False, False by default 'is_commit' : submit command, True|False, True by default example : va_delete_zone(**kwargs) kwargs = { 'name' : 'testzone', } return: a tuple of True and cmd on success, False and err_msg on failure """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if not 'name' in kwargs: raise ValueError(" name is mandatory parameter!\n") is_commit = True is_negative = False name = kwargs.get('name') if 'is_commit' in kwargs: is_commit = kwargs.get('is_commit') if 'is_negative' in kwargs: is_negative = kwargs.get('is_negative') cmd = 'unset zone {}'.format(name) ret_val, err_msg = self._access.va_config(cmd, commit=is_commit) if ret_val is not None: if not is_negative: logger.error('Failed to delete zone') return False, err_msg cmd = re.sub('^unset', 'set', cmd) logger.info('Succeed to delete zone') return True, cmd
def va_enable_profile_stateful_inspection(self, *args, **kwargs): """ API to enable stateful inspection of profile param : kwargs: 'name' : name of stateful inspection, 'is_negative' : negative test, True|False, False by default 'is_commit' : submit command, True|False, True by default example : va_enable_profile_stateful_inspection(**kwargs) kwargs = { 'name' : 'test_state', } return: a tuple of True and cmd on success, False and err_msg on failure """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if not 'name' in kwargs: raise ValueError(" name is mandatory parameter!\n") is_commit = True is_negative = False name = kwargs.get('name') if 'is_commit' in kwargs: is_commit = kwargs.get('is_commit') if 'is_negative' in kwargs: is_negative = kwargs.get('is_negative') cmd = 'unset profile stateful-inspection {} strict-tcp-check disable'.format( name) ret_val, err_msg = self._access.va_config(cmd, commit=is_commit) if ret_val is not None: if not is_negative: logger.error('Failed to enable stateful inspection of profile') return False, err_msg logger.info('Succeed to enable stateful inspection of profile') return True, cmd[2:]
def va_check_user(self, *args, **kwargs): """ check user is exist param : kwargs : dict kwargs = { 'name' : 'account user name' } return: boolean True False Example : va_check_user(**kwargs) kwargs = { 'name' : 'varmour_no_cli' } """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if not 'name' in kwargs: raise ValueError("name is mandatory parameter!\n") name = kwargs.get('name') info = self.va_get_system_user_info() if name in info: logger.info("the user {} is exist".format(name)) return True else: logger.error("the user {} is not exist".format(name)) return False
def va_check_session_packets_increment(self, session_before, session_after, *args, **kwargs): """ API to check if packets counter of data session increase param : 'session_before', should be single data session before increment 'session_after', should be single data session after increment } example : va_check_session_packets_increment(session_before, session_after) returns: :True|False (bool): True on success, False on failure """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) in_packets_before = int(session_before.get('in_packets')) in_packets_after = int(session_after.get('in_packets')) out_packets_before = int(session_before.get('out_packets')) out_packets_after = int(session_after.get('out_packets')) if in_packets_before > in_packets_after or \ out_packets_before > out_packets_after: logger.debug('In_packets: {}, {}'.format(in_packets_before, in_packets_after)) logger.debug('Out_packets: {}, {}'.format(out_packets_before, out_packets_after)) logger.error('Packet counter of data session is not increasing!') return False logger.info('Packet counter of data session is increasing.') return True
def _va_parse_app_profile(self, output=None): """ Parse the Output of show policy and check the given app profile is associated with policy :param output: :return: """ logger.info("We are in ::" + sys._getframe().f_code.co_name) if not output: logger.error(" The output is empty string and \ nothing to verify") return False logger.debug(" The output :") parsed = list() for line in output.splitlines()[1:]: line = line.strip() if not line.startswith('index') and \ not line.startswith('=') and \ not line.startswith('Total'): parsed.append(line.split()) logger.info(parsed) return parsed
def va_clear_session(self): """ API to clear session param : None example : va_clear_session() returns: :True|False (bool): True if success else False """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) times = 1 sleeptime = 2 self._access.va_cli('clear session') session = self.va_get_session('is_fail') pattern = re.compile(r'((\d+\.){3}\d+)') while pattern.search(session) is not None and times <= 6: time.sleep(sleeptime) logger.debug('Retry {} times to clear session'.format(times)) self._access.va_cli('clear session') session = self.va_get_session('is_fail') times += 1 if pattern.search(session) is not None: logger.error("Session can't be cleared") return False logger.info('Session are cleared') return True
def va_show_flow_address_group(self, name): """ API for show address-group member list,and return the member list Param : name : address-group name Return : Tuple True,list False,err_msg Returns the result as follows: True,['saddr', 'daddr'] False,'Fail to show address group member,address group test_group is not exist' Example : dir_1.va_show_flow_address_group() dir_1.va_show_flow_address_group(name = 'test_group') """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) cmd = 'show address-group {}'.format(name) output = self._access.va_cli(cmd) if re.search('cannot find address group', output) != None: error = 'Fail to show address group member,address group {} is not exist'.format( name) logger.error(error) return False, error else: result = self._va_parse_address_group_member(output) if len(result) < 1: logger.info( "address-group {} don't have any memeber".format(name)) return True, result else: return True, result
def va_unconfig_global_applog(self, application=None, port=None, commit=None): ''' API to configure global applog :param application: :param port: :param commit: :return: ''' logger.info('We are in ::' + sys._getframe().f_code.co_name) if not application: return False, 'Application name is mandotory' if port: cmd = 'unset system app-log %s port %s' %(application, port) else: cmd = 'unset system app-log %s' %(application) if commit : cmd.append('commit') config_status, output = self._access.va_config(cmd) logger.debug('UnConfiguration of Global APPLOG : ' + str(config_status) + str(output)) if config_status is False: logger.error('Global APPLOG Configuration/commit FAILED') return False, output else: logger.info('Global APPLOG Configuration/commit is successful') print('Configuration of GLOBAL APPLOG: ', config_status, output) return True, output
def va_get_epi_mode(self, *args, **kwargs): """ method to get epi mode param : kwargs : dict example : va_get_epi_status(kwargs) kwargs = { 'uuid': 'xxx' } return: 'tap' or 'inline' or 'standy' or None (if epi not found) """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if not 'uuid' in kwargs: raise ValueError(" uuid is mandatory parameter!\n") uuid = kwargs['uuid'] active_info = self.va_show_chassis_epi().get('Active EPI') for info in active_info: if info.uuid == uuid: logger.info('Mode of EPI: {}'.format(info.mode)) return info.mode logger.error('Not found EPI {} in Activate EPI'.format(uuid)) return None
def va_get_epi_status(self, *args, **kwargs): """ method to get epi status param : kwargs : dict example : va_get_epi_status(kwargs) kwargs = { 'uuid': 'xxx' } return: 'active' or 'inactive' or None (if epi not found) """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if not 'uuid' in kwargs: raise ValueError(" uuid is mandatory parameter!\n") uuid = kwargs['uuid'] epi_info = self.va_show_chassis_epi() for active_info in epi_info.get('Active EPI'): if uuid == active_info.uuid: status = 'active' logger.info('Status of EPI: {}'.format(status)) return status for inactive_info in epi_info.get('Inactive EPI'): if uuid == inactive_info.uuid: status = 'inactive' logger.info('Status of EPI: {}'.format(status)) return status logger.error("Not found EPI: {}".format(uuid)) return None
def va_do_ha_failover(self): """ API to do HA failover return: :bool - True on success or False on failure: """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if not self.va_check_ha_is_master(): return False if not self.va_check_ha_ready(): return False cmd = 'request system failover' failover_info = self._access.va_cli(cmd) pat = re.compile(r'FAILED HA FAILOVER') match_result = pat.search(failover_info) if match_result is not None: logger.error(failover_info) return False logger.info('Succeed to do HA failover') return True
def va_unset_orchestration(self, **kwargs): """ API to unset orchestration info Param: kwargs: instance: vcenter instance name orchestration_flag (list) : Need to unset orchestration option flag ('enable'|'port'|'inline-switch-name'|'auto-power-switch') port : Need to unset port id (default:443) is_commit : commit True|False(default:True) is_negative : Negative test True|False(default:False) Returns: Tuple True,cmd False,err log Example: va_unset_orchestration(instance='vcenter_1',orchestration_flag='enable') """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if 'instance' not in kwargs: raise ValueError("'instance' is mandatory in kwargs") pre_cmd = 'unset orchestration {}'.format(kwargs.get('instance')) is_commit = kwargs.get('is_commit', True) is_negative = kwargs.get('is_negative', False) name_list = [ 'enable', 'port', 'inline-switch-name', 'auto-power-switch' ] cmds = list() if 'orchestration_flag' in kwargs: orch_flag = kwargs.get('orchestration_flag') if isinstance(orch_flag, str): orch_flag = orch_flag.split(',') for flag in orch_flag: if flag not in name_list: logger.error('Wrong param {}'.format(flag)) raise ValueError('Invalid param "{}"'.format(flag)) elif flag == 'port': port_id = kwargs.get('port', '443') cmds.append(pre_cmd + ' port {}'.format(port_id)) elif flag == 'auto-power-switch': cmds.append(pre_cmd + ' auto-power-switch enable') else: cmds.append(pre_cmd + ' {}'.format(flag)) else: cmds.append(pre_cmd) ret_val, err_msg = self._access.va_config(cmds, commit=is_commit) if ret_val is not None: if not is_negative: logger.error('Failed to unset orchestration') else: logger.info('Failed to unset orchestration') return False, err_msg cmd_str = ','.join(cmds) cmd_list = re.sub('^unset', 'set', cmd_str) logger.info('Succeed to unset orchestration') return True, cmd_list
def va_add_user(self, *args, **kwargs): """ Add user param : kwargs : dict kwargs = { 'name' : 'account user name', 'password': '******', 'role' : 'account user role' [admin|operator|reader] 'is_commit': True|False, Optional parameters } return: Tuple True, cmd False, error log Example : va_add_user(**kwargs) kwargs = { 'name' : 'varmour_no_cli', 'password': '******', 'role' : 'admin' 'is_commit': True } """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if not 'name' in kwargs: raise ValueError("name is mandatory parameter!\n") if not 'password' in kwargs: raise ValueError("password is mandatory parameter!\n") if not 'role' in kwargs: raise ValueError("role is mandatory parameter!\n") if not 'is_commit' in kwargs: is_commit = True else: is_commit = kwargs.get('is_commit') name = kwargs.get('name') password = kwargs.get('password') role = kwargs.get('role') cmd = 'set system user {} role {}'.format(name, role) cmd1 = 'set system user {} password'.format(name) err_cmd, err_msg = self._access.va_config(cmd, commit=False, exit=False) err_cmd1, err_msg1 = self._access.va_config( cmd1, **{'handle_password': password}) if err_cmd is not None or err_msg is not None or\ err_cmd1 is not None or err_msg1 is not None: logger.error('Failed to add user {}'.format(name)) return False, err_msg logger.info('Succeed to add user {}'.format(name)) return True, [cmd, cmd1]
def va_add_service_group(self, *args, **kwargs): """ Add service group Param : kwargs : dict kwargs = { 'name'(str) : 'Define custom service name' 'member'(str|list) : 'member service(s) to service group' 'is_commit'(boolean) : 'Whether commit command' (default true) Return : Tuple True, cmd False, error log Example : va_add_service_group(**kwargs) kwargs = { 'name' : 'test1' 'member' : 'TCP-ANY' 'is_commit' : True|False } """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if 'name' not in kwargs: raise ValueError("name is mandatory parameter!\n") name = kwargs['name'] cmds = [] if 'member' not in kwargs: cmds.append("set service-group {}".format(name)) else: member = kwargs['member'] if type(member) != str and type(member) != list: raise ValueError("param member must be a list or string\n") if type(member) == str: member = member.split() if type(member) == list: for member_list in member: cmds.append("set service-group {} member {}" \ .format(name,member_list)) if 'is_commit' not in kwargs: is_commit = True else: is_commit = kwargs['is_commit'] err_cmd, err_msg = self._access.va_config(cmds, commit=is_commit) if err_cmd is not None or err_msg is not None: logger.error("Failed to add service-group {}".format(name)) return False, err_msg else: logger.info("Succeed to add service-group {}".format(name)) return True, cmds
def va_unset_chassis_debug(self,*args, **kwargs): """ API unset chassi debug service/control/io/agent/routing-engine/konfd/chassis-d/orchestration/telemetry Param : kwargs : debug_name(list) : Enabled debug name (default: all of debug process list) enable_device : Device ID or all devices (default: all) orchestration_debug(list) : Orchestration debug flag (default: all) is_commit : commit True|False(default:True) Return : Tuple True,cmd False,err log Example : va_unset_chassis_debug(orchestration_debug=['orch-event','orch-deploy',\ 'vcenter-plugin-event']) va_unset_chassis_debug(debug_name='orchestration'), va_unset_chassis_debug() """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) debug_name = ['service','io','agent','control','routing-engine','konfd','chassis-d',\ 'telemetry','orchestration'] cmds = [] pre_cmd = 'unset chassis process ' is_commit = kwargs.get('is_commit',True) debug_name = kwargs.get('debug_name',['service','io','agent','control','routing-engine',\ 'konfd','chassis-d','telemetry','orchestration']) if isinstance(debug_name,str): debug_name = debug_name.split(',') for enable_debug_name in debug_name: if enable_debug_name in ['service','io','agent']: enable_dev = kwargs.get('enable_device','all') cmds.append(pre_cmd + '{} {} debug all'.format(enable_debug_name,enable_dev)) elif enable_debug_name == 'orchestration': orch_debugs = kwargs.get('orchestration_debug','all') if isinstance(orch_debugs,str): orch_debugs = orch_debugs.split(',') for flag in orch_debugs: cmds.append(pre_cmd + 'orchestration debug {}'.format(flag)) else: cmds.append(pre_cmd + '{} debug all'.format(enable_debug_name)) ret_val, err_msg = self._access.va_config(cmds, commit=is_commit) if ret_val is not None: logger.error('Fail to unset chassis debug') return False, err_msg cmd_str = ','.join(cmds) cmd_list = (cmd_str.replace('unset','set')).split(',') logger.info('Succeed to unset chassis debug') return True, cmds
def va_set_admin_auth(self, *args, **kwargs): """ Set the admin-auth policy and admin-auth remote mode Param : kwargs : dict kwargs = { 'mode'(str) : 'admin-auth remote mode' (radius|ladp|ad) 'policy'(str|list) : 'Admin user authentication policy' (fallback-to-next|fallback-if-down) 'is_commit'(boolean): True|False (default:True) } Return : Tuple True,cmd False,error log Example : kwargs = { 'mode' : 'ladp' 'policy' : fallback-to-next 'is_commit' : True } """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) cmds = [] if not 'mode' in kwargs: raise ValueError("mode is mandatory parameter!\n") if not 'is_commit' in kwargs: is_commit = True else: is_commit = kwargs['is_commit'] cmds.append("set system admin-auth remote {}".format(kwargs['mode'])) if 'policy' in kwargs: policy = kwargs['policy'] if type(policy) == str: policy = policy.split() if type(policy) == list: for policy_list in policy: cmds.append("set system admin-auth policy {}" \ .format(policy_list)) err_cmd, err_msg = self._access.va_config(cmds, commit=is_commit) if err_cmd != None or err_msg != None: logger.error("Fail to set admin-auth") return False, err_msg else: logger.info("Succeed to set admin-auth") return True, cmds
def va_set_chassis_fabric(self, *args, **kwargs): """ method set fabric tunnel/secret/heartbeat-interval param : kwargs : dict kwargs = { 'vxlan' : 'vxlan identifier' 'secret' : 'fabric secret key' 'heartbeat_interval' : ' Heartbeat interval in seconds' 'is_commit': 'commit' True|False } return : Tuple True,cmd False,err log Example : va_set_chassis_fabric(**kwargs) kwargs = { 'vxlan' : 10, 'secret' : 'varmour', 'heartbeat_interval' : 3, 'is_commit' : True """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) cmds = [] if 'vxlan' in kwargs: cmds.append('set chassis fabric tunnel vxlan %s' % (kwargs['vxlan'])) if 'heartbeat_interval' in kwargs: cmds.append('set chassis fabric heartbeat_interval %s' % (kwargs['heartbeat_interval'])) if 'secret' in kwargs: cmds.append('set chassis fabric secret %s' % (kwargs['secret'])) if not 'is_commit' in kwargs : is_commit = True else : is_commit = kwargs['is_commit'] err_cmd,err_msg = self._access.va_config(cmds,commit=is_commit) if err_cmd is None or err_msg is None: logger.info("Succeed to set chassis fabric") return True,cmds else: error = "Failed to set chassis fabric" logger.error(error) return False,err_msg
def _va_parse_show_session(self, output=None): """ Parse the Output of show policy and check the given app profile is associated with policy :param output: :return: """ logger.info("We are in ::" + sys._getframe().f_code.co_name) if not output: logger.error(" The output is empty string and \ nothing to verify") return False logger.debug(" The \"show session\" output :")
def _va_verify_ip(self, interface=None, config=None): """ Helper function to compare ip address that is being configured and its actual set value. """ output = self.va_show_interface(interface) if not output: return False if config.with_prefixlen == output['Local address']: logger.info("set/unset ip succeeded") return True else: logger.error("set/unset ip failed") return False
def va_config_inactivity_timeout(self, timeout=250): """ Configure the cli timeout on inactivity, default value is 250 minutes. kwargs: :timeout : int: Inactivity-timeout in minutes Return: Ture/False Examples: va_config_inactivity_timeout(10) va_config_inactivity_timeout() """ return_value, err_msg = \ self.va_config('set system inactivity-timeout {}'.format(timeout)) if return_value is not None: logger.error(err_msg) return False
def va_check_ha_is_master(self): """ API to check if HA is master return: :bool - True on success or False on failure: """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) ha_role = self.va_get_ha_role() if ha_role != 'master': logger.error('The role of director is {}'.format(ha_role)) return False logger.info('The role of director is MASTER') return True
def va_check_ha_is_ineligible(self): """ API to check if HA is ineligible state return: :bool - True on success or False on failure: """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) ha_role = self.va_get_ha_role() if ha_role != 'ineligible': logger.error('The role of director is {}'.format(ha_role)) return False logger.info('The role of director is INELIGIBLE') return True
def va_enable_interface(self, *args, **kwargs): """ Enable interface Param : kwargs : dict kwargs = { 'name'(str) : interface name 'is_commit'(boolean) : True|False (default True) } Return : Tuple True,cmd False,err log Example : va_enable_interface(**kwargs) kwargs = { 'name' : 'xe-4/0/0.1', 'is_commit' : True } """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) if 'name' not in kwargs: raise ValueError("name is mandatory parameter!\n") name = kwargs['name'] cmd = 'unset interface {} disable'.format(name) check_disable = self.va_show_running_config() if "set interface {} disable".format(name) not in check_disable: error = "interface {} is not disabled, can't be enabled again".format( name) logger.error(error) return False .error if "is_commit" not in kwargs: is_commit = True else: is_commit = kwargs['is_commit'] err_cmd, err_msg = self._access.va_config(cmd, commit=is_commit) if err_cmd is not None or err_msg is not None: logger.error("Failed to enable interface {}".format(name)) return False, err_msg else: logger.info("Succeed to enable interface {}".format(name)) cmds = 'set interface {} disable'.format(name) return True, cmds
def va_check_chassis_epi_status(self): """ API to check chassis status of EPI. return: :bool - True on success or False on failure: """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) chassis_info = self.va_show_chassis_epi() inactive_count = int(chassis_info.get('Total inactive EPIs')) if inactive_count != 0: logger.error('Found inactive EPis: {}'.format(inactive_count)) return False logger.info('All EPis are connected') return True
def va_show_ha(self): """ API to show high-availability return: :None or dict - refer to output of _va_parse_ha_status """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) parser = self._va_parse_ha_status cmd = "show high-availability" ha_info = self._access.va_cli(cmd) if 'ha_info' not in dir(): logger.error("Failed to get high availability") return None return parser(ha_info)
def va_check_ha_ready(self): """ API to check if HA ready Returns: :bool - True on success or False on failure: """ logger.info("\nIn subroutine: " + sys._getframe().f_code.co_name) ha_info = self.va_show_ha() ha_state = ha_info.get('HA Failover State') if ha_state != "Failover Ready": logger.error('HA Failover State is not ready') return False logger.info('HA Failover State is ready') return True
def va_deception_pptp_status_in_epi(self, pppid=None): logger.info("We are in ::" + sys._getframe().f_code.co_name) if not pppid: raise ValueError('PPP ID is mandotary') cmd = 'ifconfig' ifstatus = self._access.va_shell(cmd) if 'ppp' + pppid in ifstatus: logger.info('PPP tunnel {} established in EPI {}'.format('ppp' + pppid)) return True, status else: logger.error( 'PPP tunnel {} NOT established in EPI {}'.format('ppp' + pppid)) return False, cstatus
def va_add_varmour_no_cli(self): # add varmour_no_cli user to check core file name = self.cli.user_nocli user = self._resource.get_user() output = self.va_shell("sudo grep -A3 '%s' /etc/bash.bashrc" % name, exit=False) match_nocliuser = re.search(r'\$user\s*==\s*"%s"' % name, output, re.I | re.M) if match_nocliuser is None: self.va_shell("cp /etc/bash.bashrc /etc/bash.bashrc_bak", exit=False) output = self.va_shell("grep '$USER ==' /etc/bash.bashrc", exit=False) match_if_condition = re.search(r'if\s*\[(.*?)\]\s*;', output, re.I | re.M) if match_if_condition is not None: org_if_condition = match_if_condition.group(1).strip() else: org_if_condition = '$USER == "root"' self.va_shell("sed -i 's/%s/$USER == \"%s\" -o %s/g' /etc/bash.bashrc" % \ (org_if_condition, name, org_if_condition)) output = self.va_shell("grep -A3 '%s' /etc/bash.bashrc" % name) if re.search(r'\$user\s*==\s*"%s"' % name, output, re.I | re.M) is None: logger.error( 'Failed to add varmour_no_cli to /etc/bash.bashrc file') else: logger.info( 'Succeed to add varmour_no_cli to /etc/bash.bashrc file') cmd = 'set system user {} role admin'.format(name) cmd1 = 'set system user {} password'.format(name) self.va_cli() err_cmd, err_msg = self.va_config(cmd, commit=False, exit=False) err_cmd1, err_msg1 = self.va_config( cmd1, **{'handle_password': user.get('password')}) if err_cmd is not None or err_msg is not None or \ err_cmd1 is not None or err_msg1 is not None: logger.error('Failed to add user {}'.format(name)) return False logger.info('Succeed to add user {}'.format(name)) return True