Best Python code snippet using avocado_python
ctrl_process.py
Source:ctrl_process.py
1#!/usr/aut_env/bin/python3.82'''3CTRL_FREC4Version 1.0.0 15-04-2021 11:195''' 6## LIBRERIAS7import sys8import os9import configparser10## CONEXIONES11from CTRL_FREC.PROCESS.drv_visual import dic12from __CORE__.drv_redis import Redis13from __CORE__.drv_logs import ctrl_logs14from __CORE__.mypython import str2bool, config_var15from __CORE__.drv_dlg import emerg_system, read_param16from time import time 17from __CORE__.drv_config import serv_APP_config18from CTRL_FREC.PROCESS.ctrl_library import ctrlProcess19ctrl_start_time = time() 20def control_process(LIST_CONFIG):21 ''''''22 23 name_function = 'CONTROL_PROCESS'24 25 conf = config_var(LIST_CONFIG)26 27 # VARIABLES DE EJECUCION28 DLGID_CTRL = conf.lst_get('DLGID_CTRL') 29 TYPE = conf.lst_get('TYPE') 30 print_log = str2bool(conf.lst_get('print_log'))31 LOG_LEVEL = conf.lst_get('LOG_LEVEL')32 33 #VARIABLES DE CONFIGURACION34 ENABLE_OUTPUTS = str2bool(conf.lst_get('ENABLE_OUTPUTS'))35 TYPE_IN_FREC = conf.lst_get('TYPE_IN_FREC')36 DLGID_REF = conf.lst_get('DLGID_REF') 37 CHANNEL_REF = conf.lst_get('CHANNEL_REF') 38 DLGID_REF_1 = conf.lst_get('DLGID_REF_1') 39 CHANNEL_REF_1 = conf.lst_get('CHANNEL_REF_1') 40 41 ## INSTANCIAS42 logs = ctrl_logs(TYPE,'CTRL_FREC_process',DLGID_CTRL,print_log,LOG_LEVEL)43 config = configparser.ConfigParser()44 redis = Redis()45 #gda = GDA(serv_APP_config['CONFIG']['working_mode'])46 47 redis.no_execution('MER004')48 49 '''50 # INSTANCIA DE error_process51 import importlib.util52 #spec = importlib.util.spec_from_file_location("archivo", f"../{TYPE}/PROCESS/ctrl_library.py")53 spec = importlib.util.spec_from_file_location("archivo", f"/datos/cgi-bin/spx/AUTOMATISMOS/{TYPE}/PROCESS/ctrl_library.py")54 archivo = importlib.util.module_from_spec(spec)55 spec.loader.exec_module(archivo)56 p = archivo.ctrl_process(LIST_CONFIG)'''57 p = ctrlProcess(LIST_CONFIG)58 59 # OBTENFO LA CARPETA EN DONDE SE ENCUENTRA EL ARCHIVO ACTUAL60 current_path = os.path.dirname(os.path.abspath(__file__))61 # LEO EL ARCHIVO DE CONFIGURACION62 config.read(f"{current_path}/ctrl_config.ini")63 64 #---------------------------------------------------------65 ##PROCESS66 67 logs.basicLog(__doc__)68 69 # ESCRIBO LA EJECUCION DEL SCRIPT70 logs.print_log(f"{name_function}")71 72 #logs.script_performance(f"{name_function}")73 74 75 76 77 # MUESTRO VARIABLES DE ENTRADA78 logs.print_in(name_function, 'print_log', print_log)79 logs.print_in(name_function, 'DLGID_CTRL', DLGID_CTRL)80 logs.print_in(name_function, 'TYPE', TYPE)81 logs.print_in(name_function, 'ENABLE_OUTPUTS', ENABLE_OUTPUTS)82 logs.print_in(name_function, 'TYPE_IN_FREC', TYPE_IN_FREC)83 logs.print_in(name_function, 'DLGID_REF', DLGID_REF)84 logs.print_in(name_function, 'CHANNEL_REF', CHANNEL_REF)85 logs.print_in(name_function, 'DLGID_REF_1', DLGID_REF_1)86 logs.print_in(name_function, 'CHANNEL_REF_1', CHANNEL_REF_1)87 88 89 # ESCRIBO NUMERO DE EJECUCION90 #redis.no_execution(DLGID_CTRL)91 92 93 # CHEQUEO QUE EXISTAN LOS LINES DEL DATALOGGER DE CONTROL Y EL DE REFERENCIA.94 if not(redis.hexist(DLGID_CTRL,'LINE')): 95 #logs.script_performance(f'{name_function} ==> NO EXISTE LINE {DLGID_CTRL}')96 logs.print_inf(name_function,f'NO EXISTE LINE {DLGID_CTRL}')97 logs.print_inf(name_function,'EJECUCION INTERRUMPIDA')98 quit()99 100 if not(redis.hexist(DLGID_REF,'LINE')): 101 #logs.script_performance(f'NO EXISTE LINE {DLGID_REF}')102 logs.print_inf(name_function,f'NO EXISTE LINE {DLGID_REF}')103 logs.print_inf(name_function,'EJECUCION INTERRUMPIDA')104 quit()105 106 #107 logs.print_inf(name_function, 'CHEQUEO_ALARMAS')108 p.chequeo_alarmas()109 #110 #logs.print_inf(name_function, 'CHEQUEO_SENSOR') 111 #p.chequeo_sensor()112 #113 logs.print_inf(name_function, 'MAIN') 114 115 # FUNCION MAIN116 name_function = 'MAIN'117 118 # CONDICIONES INICIALES119 #120 ## ACTIVO BANDERA PARA QUE control_error NOTIFIQUE QUE SE ESTA TRABAJANDO CON REFERENCIA_1121 redis.hset(DLGID_CTRL, 'flag_work_syst_ref_1','NO')122 123 124 # REVISO SI ESTA TRABAJANDO EN MODO LOCAL EN EL TABLERO125 if read_param(DLGID_CTRL,'LM') == '1': 126 logs.print_inf(name_function, 'TRABAJO EN MODO LOCAL')127 redis.hset(DLGID_CTRL, 'LOCAL_MODE', 'SI') 128 elif read_param(DLGID_CTRL,'LM') == '0':129 redis.hset(DLGID_CTRL, 'LOCAL_MODE', 'NO') #VISUALIZACION130 #131 # SI NO EXISTE LA VARIABLE DE SELECCION SW1 LA CREO CON VALOR AUTO132 if not(redis.hexist(DLGID_CTRL, dic.get_dic('WEB_MODE', 'name'))): 133 redis.hset(DLGID_CTRL, dic.get_dic('WEB_MODE', 'name'), dic.get_dic('WEB_MODE', 'True_value'))134 # MUESTRO LOGS DE ADVERTENCIA135 logs.print_inf(name_function, 'NO EXISTE LA VARIABLE SW1 EN REDIS')136 logs.print_inf(name_function, 'SE CREA LA VARIABLE CON VALOR [0]'.format(dic.get_dic('WEB_MODE', 'True_value')))137 #logs.script_performance('error in [0] [1] = ,'.format(name_function,dic.get_dic('WEB_MODE', 'name')))138 #logs.script_performance('error in [0], SE CREA [1] = [2]'.format(name_function,dic.get_dic('WEB_MODE', 'name'),dic.get_dic('WEB_MODE', 'True_value')))139 #140 # LEO VAERIABLE WEB_MODE141 WEB_MODE = redis.hget(DLGID_CTRL, dic.get_dic('WEB_MODE', 'name'))142 143 144 # REVISO EL MODO DE TRABAJO WEB145 if WEB_MODE == 'REMOTO':146 logs.print_inf(name_function, 'TRABAJO EN MODO REMOTO')147 p.modo_remoto()148 149 elif WEB_MODE in [dic.get_dic('WEB_MODE', 'value_1'), dic.get_dic('WEB_MODE', 'value_1'), ]:150 logs.print_inf(name_function, 'TRABAJO EN MODO SISTEMA DE EMERGENCIA')151 # REVISO EL ESTADO DE ENABLE_OUTPUTS152 if ENABLE_OUTPUTS:153 emerg_system(DLGID_CTRL)154 else:155 logs.print_inf(name_function, f"SALIDAS DESCACTIVADAS [ENABLE_OUTPUTS = {ENABLE_OUTPUTS}]") 156 #logs.script_performance(f"{name_function} ==> SALIDAS DESCACTIVADAS [ENABLE_OUTPUTS = {ENABLE_OUTPUTS}]")157 158 elif WEB_MODE == 'AUTO':159 logs.print_inf(name_function, 'TRABAJO EN MODO AUTOMATICO')160 #161 # SI NO EXISTE LA VARIABLE TX_ERROR EN DLGID_REF LA CREO CON VALOR NO162 if not(redis.hexist(DLGID_REF, dic.get_dic('TX_ERROR', 'name'))): 163 redis.hset(DLGID_REF, dic.get_dic('TX_ERROR', 'name'), dic.get_dic('TX_ERROR', 'False_value'))164 #165 # LEO MAG_REF SELECCIONADA POR EL CLIENTE. SI NO EXISTE LMIN LO CREO CON VALOR 1166 if not(redis.hexist(DLGID_CTRL, dic.get_dic('MAG_REF', 'name'))): 167 redis.hset(DLGID_CTRL, dic.get_dic('MAG_REF', 'name'), dic.get_dic('MAG_REF', 'True_value'))168 else:169 MAG_REF = float(redis.hget(DLGID_CTRL, dic.get_dic('MAG_REF', 'name')))170 171 172 # LEO TX_ERROR Y # error_1min173 TX_ERROR = redis.hget(DLGID_REF, dic.get_dic('TX_ERROR', 'name'))174 error_1min = redis.hget(DLGID_REF,'error_1min')175 176 # CHEQUEO ERROR TX EN EL DLG DE REFERENCIA (SE DECLARA ERROR_TX CUANDO PASAN 10 MIN SIN TRANSMITIR)177 if TX_ERROR == 'SI':178 logs.print_inf(name_function, f'ERROR TX EN SISTEMA DE REFERENCIA [ {DLGID_REF} ]')179 #logs.print_inf(name_function, 'AUTOMATISMO TRABAJADO CON SISTEMA DE EMERGENCIA')180 #181 # CHEQUEO QUE SE HAYA ESCRITO LA DIFERENCIA EN MAGNITUD ENTRE LOS SENSORES182 if redis.hexist(DLGID_CTRL,'delta_ref1_ref'):183 #184 # LEO LA DIFERENCIA ENTRE LAS MAGNITUDES DE REFERENCIA185 delta_ref1_ref = float(redis.hget(DLGID_CTRL,'delta_ref1_ref'))186 #187 # CHEQUEO EL ESTADO DEL SENSOR DE REFERENCIA 1188 if not(p.chequeo_sensor(DLGID_REF_1,CHANNEL_REF_1)):189 logs.print_inf(name_function, 'ERROR DE SENSOR EN SISTEMA DE REFERENCIA 1')190 logs.print_inf(name_function, 'AUTOMATISMO TRABAJADO CON SISTEMA DE EMERGENCIA')191 emerg_system(DLGID_CTRL)192 else:193 logs.print_inf(name_function, 'AUTOMATISMO TRABAJADO CON SISTEMA DE REFERENCIA 1')194 #195 # ACTIVO BANDERA PARA QUE control_error NOTIFIQUE QUE SE ESTA TRABAJANDO CON REFERENCIA_1196 redis.hset(DLGID_CTRL, 'flag_work_syst_ref_1','SI')197 #198 # LLAMO AL CONTROL DEL SISTEMA199 p.control_sistema(DLGID_REF_1,CHANNEL_REF_1,MAG_REF + delta_ref1_ref)200 #201 else:202 logs.print_inf(name_function, 'AUTOMATISMO TRABAJADO CON SISTEMA DE EMERGENCIA')203 emerg_system(DLGID_CTRL)204 205 elif TX_ERROR == 'NO':206 # ME ASEGURO QUE LA REFENCIA ME HAYA MANDADO UN DATO NUEVO 207 if error_1min == 'NO':208 # CHEQUEO ERROR EN EL SENSOR209 if not(p.chequeo_sensor(DLGID_REF,CHANNEL_REF)):210 logs.print_inf(name_function, 'ERROR DE SENSOR EN SISTEMA DE REFERENCIA')211 logs.print_inf(name_function, 'AUTOMATISMO TRABAJADO CON SISTEMA DE EMERGENCIA')212 #213 emerg_system(DLGID_CTRL)214 else:215 logs.print_inf(name_function, 'CONTROL_SISTEMA')216 p.control_sistema(DLGID_REF,CHANNEL_REF,MAG_REF)217 #218 logs.print_inf(name_function, 'DELTA_MAG')219 p.delta_mag()220 else:221 logs.print_inf(name_function, 'EN ESPERA DE DATOS DE LA REFERENCIA')222 223 else:224 logs.print_inf(name_function, "error in [0], [1] = [2]".format(name_function,dic.get_dic('TX_ERROR', 'name'),TX_ERROR))225 # DEJAR REGISTRO DEL ERROR226 #logs.script_performance("error in [0], [1] = [2]".format(name_function,dic.get_dic('TX_ERROR', 'name'),TX_ERROR))227 #228 else:229 logs.print_inf(name_function, 'error in [0], [1] = [2]'.format(name_function,dic.get_dic('WEB_MODE', 'name'),WEB_MODE))230 # DEJAR REGISTRO DEL ERROR231 #logs.script_performance('error in [0], [1] = [2]'.format(name_function,dic.get_dic('WEB_MODE', 'name'),WEB_MODE))232 233 else:234 logs.print_inf(name_function, f"error in {name_function}, LM = {read_param(DLGID_CTRL,'LM')}")235 logs.print_inf(name_function,'EJECUCION INTERRUMPIDA')236 # DEJAR REGISTRO DEL ERROR237 #logs.script_performance(f"error in {name_function}, LM = {read_param(DLGID_CTRL,'LM')}")238 239 # LATCHEO LAS SALIDAS240 p.latch__outpust(DLGID_CTRL)241 242 # PREPARO DATA_DATE_TIME PARA MOSTRAR EN LA VISUALIZACION EN EL DATALOGGER DE CONTROL243 logs.print_inf(name_function, 'SHOW_DATA_DATE_TIME')244 p.show_DATA_DATE_TIME(DLGID_CTRL)245 246 # PREPARO DATA_DATE_TIME PARA MOSTRAR EN LA VISUALIZACION EN EL DATALOGGER DE REFERENCIA247 p.show_DATA_DATE_TIME(DLGID_REF)248 249 # PREPARO PUMP1_STATE PARA MOSTRAR EL ESTADO DE LA BOMBA250 logs.print_inf(name_function, 'SHOW_PUMP1_STATE')251 p.show_pump1_state('BR1')252 253 # MUESTRA LA FRECUENCIA ACTUAL A LA QUE SE ESTA TRABAJANDO 254 logs.print_inf(name_function, 'SHOW_WORK_FREQUENCY')255 p.show_work_frequency()256 257 #258 # CALCULO TIEMPO DE DEMORA259 #print('')260 #print('TIME_ALALYSIS')261 #print(f'ctrl_process_frec TERMINADO A {time()-ctrl_start_time} s') 262 263 264 265 266 267## VARIABLES DEL SCRIPT PARA EJECUCION LOCAL 268if __name__ == '__main__':269 # PREPARO EL SCRIPT PARA LLAMADA LOCAL. SE TOMA LA CONFIGURACION ESCRITA AL INICIO270 LIST_CONFIG = [271 #VARIABLES DE EJECUCION272 'print_log', True, # VER LOS LOGS EN CONSOLA [ True | False ]273 'DLGID_CTRL', 'MER007', # ID DATALOGGER QUE EJECUTA LAS ACCIONES DE CONTROL274 'TYPE', 'FREC', # CUANDO TIENE LE VALOR CHARGE SE CARGA LA CONFIGURACION DE LA db275 276 277 #VARIABLES DE CONFIGURACION278 'TYPE_IN_FREC', 'NPN', # FORMA EN QUE EL VARIADOR DE VELOCIDAD DETECTA LAS ENTRADAS [ NPN (not_in)| PNP] 279 'DLGID_REF', 'MER005', # DATALOGGER QUE SE USA DE REFERENCIA PARA EL AUTOMATIMO280 'CHANNEL_REF', 'PMP', # NOMBRE DEL CANAL CON LA MEDIDA DE REFERENCIA PARA EL AUTOMATISMO281 'DLGID_REF_1', '', # DATALOGGER AUXILIAR QUE SE VA A USAR DE REFERENCIA EN CASO DE FALLAS DE COMUNICACION DEL PRINCIPAL282 'CHANNEL_REF_1', '', # NOMBRE DEL CANAL AUXILIAR CON LA MEDIDA DE REFERENCIA PARA EL AUTOMATISMO283 284 ] 285 286 control_process(LIST_CONFIG)287 288 289 ...
dockdet
Source:dockdet
1#!/usr/bin/env python32import dataclasses3import enum4import os5import pathlib6import re7import subprocess8import tempfile9import typing10@dataclasses.dataclass11class Output:12 name: str13 connected: bool14 resolution: typing.Optional[typing.Tuple[int, int]] = None15 physical_size: typing.Optional[typing.Tuple[int, int]] = None16 @property17 def internal(self):18 return self.name.startswith("eDP")19 @property20 def physical_size_in(self):21 if not self.physical_size:22 return None23 return (self.physical_size[0] / 25.4, self.physical_size[1] / 25.4)24 @property25 def dpi(self):26 if self.resolution and self.physical_size:27 x_res = self.resolution[0] / self.physical_size_in[0]28 y_res = self.resolution[1] / self.physical_size_in[1]29 return (x_res + y_res) / 230 return 9631 @property32 def scaling_factor(self):33 if not self.physical_size_in:34 return 1.035 phys_area = self.physical_size_in[0] * self.physical_size_in[1]36 for cutoff, factor in (37 (14 * 9, 0.75),38 (21 * 12, 0.8),39 (23.5 * 13.5, 0.85),40 (29 * 17, 0.9),41 ):42 if phys_area <= cutoff:43 return factor44 return 1.045 @property46 def adjusted_dpi(self):47 return max(96, self.dpi * self.scaling_factor)48 def __hash__(self):49 return hash(self.name)50def get_x_display():51 display = os.environ.get("DISPLAY")52 if display:53 return display54 for socket in pathlib.Path("/tmp/.X11-unix").glob("X*"):55 return socket.name[1:]56 raise OSError("Cannot find X display")57def run_xrandr(*args, **kwargs):58 kwargs.setdefault("check", True)59 kwargs.setdefault("stdin", subprocess.DEVNULL)60 kwargs.setdefault("stdout", subprocess.PIPE)61 kwargs.setdefault("encoding", "utf-8")62 kwargs.setdefault("errors", "replace")63 return subprocess.run(["xrandr", "-d", get_x_display(), *map(str, args)], **kwargs)64def get_outputs():65 outputs = []66 run_xrandr("--auto")67 xrandr_result = run_xrandr()68 res_p = re.compile(r"(\d+)x(\d+)")69 phys_p = re.compile(r"(\d+)mm x (\d+)mm")70 for line in xrandr_result.stdout.splitlines():71 parts = line.split()72 if len(parts) >= 2:73 if parts[1] == "connected":74 connected = True75 elif parts[1] == "disconnected":76 connected = False77 elif outputs and not outputs[-1].resolution:78 m = res_p.fullmatch(parts[0])79 if m:80 outputs[-1].resolution = (int(m.group(1)), int(m.group(2)))81 continue82 else:83 continue84 physical_size = None85 m = phys_p.search(line)86 if m:87 physical_size = (int(m.group(1)), int(m.group(2)))88 outputs.append(89 Output(name=parts[0], connected=connected, physical_size=physical_size)90 )91 return outputs92def xrdb_merge(settings):93 with tempfile.NamedTemporaryFile(mode="w+") as f:94 for k, v in settings.items():95 f.write(f"{k}: {v}\n")96 f.flush()97 subprocess.run(98 ["xrdb", "-display", get_x_display(), "-merge", f.name],99 check=True,100 )101class LidState(enum.Enum):102 UNKNOWN = 0103 CLOSED = 1104 OPEN = 2105def get_lid_state():106 def get_possible_states():107 switches_dir = pathlib.Path("/proc/acpi/button/lid")108 if not switches_dir.is_dir():109 return110 for switch in switches_dir.iterdir():111 state_file = switch / "state"112 if state_file.is_file():113 contents = state_file.read_text()114 if "open" in contents:115 yield LidState.OPEN116 elif "closed" in contents:117 yield LidState.CLOSED118 states = set(get_possible_states())119 if not states:120 return LidState.UNKNOWN121 if len(states) == 1:122 return states.pop()123 raise RuntimeError(f"Lid is in multiple states: {states}")124def show_outputs(outputs):125 for output in outputs:126 print(output.name)127 for prop in (128 "connected",129 "resolution",130 "physical_size",131 "physical_size_in",132 "internal",133 "dpi",134 "scaling_factor",135 "adjusted_dpi",136 ):137 print(f" {prop} = {getattr(output, prop)}")138def main():139 outputs = get_outputs()140 show_outputs(outputs)141 internal_displays = {d for d in outputs if d.internal and d.connected}142 external_displays = {d for d in outputs if not d.internal and d.connected}143 disconnected_outputs = {d for d in outputs if not d.connected}144 lid_state = get_lid_state()145 print(f"Lid State: {lid_state}")146 if lid_state == LidState.CLOSED and external_displays:147 enable_outputs = external_displays148 disable_outputs = internal_displays149 elif external_displays:150 enable_outputs = internal_displays | external_displays151 disable_outputs = set()152 else:153 enable_outputs = internal_displays154 disable_outputs = external_displays155 disable_outputs |= disconnected_outputs156 max_dpi_output = max(enable_outputs, key=lambda output: output.dpi)157 target_dpi = int(max_dpi_output.adjusted_dpi)158 print(f"target_dpi={target_dpi}")159 xrandr_opts = []160 for output in enable_outputs:161 xrandr_opts.extend(["--output", output.name, "--auto"])162 for output in disable_outputs:163 xrandr_opts.extend(["--output", output.name, "--off"])164 if xrandr_opts:165 run_xrandr(*xrandr_opts)166 run_xrandr("--dpi", target_dpi)167 cursor_size = 24 if target_dpi < 120 else 48168 xrdb_merge(169 {170 "Xft.dpi": target_dpi,171 "Xcursor.size": cursor_size,172 }173 )174 subprocess.run(["i3-msg", "restart"], check=True)175if __name__ == "__main__":...
IAMInitADUser.py
Source:IAMInitADUser.py
1import demistomock as demisto # noqa: F4012from CommonServerPython import * # noqa: F4013def main():4 outputs: Dict[str, Any] = {}5 readable_output = ''6 err = None7 args = demisto.args()8 pwd_generation_script = args.get("pwdGenerationScript")9 username = args.get("sAMAccountName")10 user_email = args.get("email")11 display_name = args.get("displayname")12 to_email = args.get("to_email")13 inc_id = args.get("inc_id")14 email_subject = args.get("email_subject")15 password = None16 try:17 # Generate a random password18 pwd_generation_script_output = demisto.executeCommand(pwd_generation_script, {})19 if is_error(pwd_generation_script_output):20 raise Exception(f'An error occurred while trying to generate a new password for the user. '21 f'Error is:\n{get_error(pwd_generation_script_output)}')22 else:23 password_output = demisto.get(pwd_generation_script_output[0], 'Contents')24 if isinstance(password_output, dict):25 password = password_output.get("NEW_PASSWORD")26 elif isinstance(password_output, str):27 password = password_output28 else:29 raise Exception(f'Could not parse the generated password from {pwd_generation_script} outputs. '30 f'Please make sure the output of the script is a string.')31 # set a new password32 ad_create_user_arguments = {33 'username': username,34 'password': password,35 'attribute-name': 'pwdLastSet',36 'attribute-value': -137 }38 set_password_outputs = demisto.executeCommand("ad-set-new-password", ad_create_user_arguments)39 if is_error(set_password_outputs):40 err = get_error(set_password_outputs)41 if '5003' in err:42 raise Exception(f"An error occurred while trying to set a new password for the user. "43 f"Please make sure that \"{pwd_generation_script}\" script "44 f"complies with your domain's password complexity policy.")45 raise Exception(f"An error occurred while trying to set a new password for the user. "46 f"Error is:\n{err}")47 else:48 enable_outputs = demisto.executeCommand("ad-enable-account", ad_create_user_arguments)49 if is_error(enable_outputs):50 raise Exception(f'An error occurred while trying to enable the user account. '51 f'Error is:\n{get_error(enable_outputs)}')52 else:53 update_outputs = demisto.executeCommand("ad-update-user", ad_create_user_arguments)54 if is_error(update_outputs):55 raise Exception(f'An error occurred while trying to update the user account. '56 f'Error is:\n{get_error(update_outputs)}')57 outputs['success'] = True58 except Exception as e:59 outputs['success'] = False60 outputs['errorDetails'] = str(e)61 err = str(e)62 try:63 send_mail_outputs = send_email(display_name, username, user_email, err,64 to_email, password, inc_id, email_subject)65 if is_error(send_mail_outputs):66 raise Exception(f'An error occurred while trying to send mail. Error is:\n{get_error(send_mail_outputs)}')67 outputs['sentMail'] = True68 except Exception as e:69 outputs['sentMail'] = False70 outputs['sendMailError'] = str(e)71 if outputs['success'] and outputs['sentMail']:72 readable_output = f'Successfully activated user {username}. ' \73 f'An email with the user details was sent to {to_email}.'74 else:75 if outputs.get('errorDetails'):76 readable_output += f"{outputs.get('errorDetails')}\n"77 if outputs.get('sendMailError'):78 readable_output += str(outputs.get('sendMailError'))79 result = CommandResults(80 outputs_prefix='IAM.InitADUser',81 outputs=outputs,82 readable_output=readable_output83 )84 return_results(result)85def send_email(display_name, username, user_email, err, to_email, password, inc_id, email_subject):86 if not err:87 if not email_subject:88 email_subject = f'[IAM] User {display_name} was successfully activated in Active Directory'89 email_body = 'Hello,\n\n' \90 'The following account has been created in Active Directory:\n\n'91 if display_name:92 email_body += 'Name: ' + display_name + '\n'93 email_body += 'Username: ' + username + '\n' \94 'Email: ' + user_email + '\n' \95 'Password: ' + password + '\n\n' \96 'Regards,\nIAM Team'97 else:98 email_subject = f'"IAM - Activate User In Active Directory" incident {inc_id} failed with user {display_name}'99 email_body = 'Hello,\n\n' \100 'This message was sent to inform you that an error occurred while trying ' \101 'to activate the user account of ' + username + ' in the active Directory.\n\n' \102 'The error is: ' + err + '\n\nRegards,\nIAM Team'103 return demisto.executeCommand("send-mail", {"to": to_email, "subject": email_subject, "body": email_body})104if __name__ in ['__main__', 'builtin', 'builtins']:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!