def delete_button(*args): # get index of the currently selected email selected_msg_index = self.cursor_pos # get the uid of the mail num_msgs = len(self.parentApp.mail.inbox_messages) # ensure the last message is not deleted. if num_msgs == 1: npyscreen.notify_ok_cancel("Can't delete last message in box") return msg_uid = self.parentApp.mail.inbox_messages[selected_msg_index].uid # call server to delete the msg with the specified id rv = self.parentApp.mail.delete_msg(msg_uid) if rv == 'OK': del self.parentApp.mail.email_hdr_lst[selected_msg_index] del self.parentApp.mail.inbox_messages[selected_msg_index] del self.msg_headers.msg_unread[selected_msg_index] # upate the indexes of the read and unread emails. self.msg_headers.update() # update the message body being displayed # if we delete the last message show the one above # otherwise show the one below if num_msgs == selected_msg_index + 1: self.parentApp.INBOX_MSG_TXT = self.parentApp.mail.inbox_messages[selected_msg_index - 2].body else: self.parentApp.INBOX_MSG_TXT = self.parentApp.mail.inbox_messages[selected_msg_index].body # update the display self.msg_body.value = self.parentApp.INBOX_MSG_TXT self.msg_body.update() else: npyscreen.notify_confirm("Failed to delete")
def wipeRAID(self): #this function will wipe all the RAID drives that aren't our protected drive. #test resolve message = "This will wipe every RAID drive on the list! It's important to note that the OS is installed on a RAID drive, and I can't protect the OS drive by serial (thanks, MegaCLI). I have to protect it by ASSUMING it's ld #0 on adapter 0... so if it isn't, we're going to have a bad time. Please verify before pressing OK!" confirm = npyscreen.notify_ok_cancel(message, title="Very bad thing could happen!", editw = 1) if not confirm: return message = "I'm serious! You can check LD0 in megacli if you need to. I'll wait! The command is\n /opt/MegaRAID/MegaCli/MegaCli64 -LDInfo -L1 -a0" confirm = npyscreen.notify_ok_cancel(message, title="Not kidding!", editw = 1) if not confirm: return #if we're going for it, assemble information lds = mc.logicaldrives() for ld in lds: if ld['id'] == 0: #if the user is trying to poke ld0, ignore it. Keep that ld. it's important. continue else: try: mc.remove_ld(ld['id'], ld['adapter_id'], force=True) except: npyscreen.notify_confirm("Something went wrong in MegaCLI when destroying ld " + ld['id'], title="Something failed", editw = 1) npyscreen.notify_confirm("RAID drives destroyed!", title="Success!", editw = 1) self.scanAndTest()
def on_ok(self): try: if self.threads_text.value == '': self.threads_text.value = 'auto' int(self.threads_text.value) except ValueError: if self.threads_text.value != 'auto': npyscreen.notify_ok_cancel( 'Worker Threads must be given as an integer.', form_color='DANGER') return if not self.net_interface_text.value: npyscreen.notify_ok_cancel('Network Interface cannot be blank.', form_color='DANGER') return if self.value: self.parentApp.suricata_config.remove_pfring_interface(self.value) self.parentApp.suricata_config.add_pfring_interface( interface=self.net_interface_text.value, threads=self.threads_text.value, cluster_id=self.cluster_id.value, bpf_filter=self.bpf_filter.value) # Switch back to the main interface npyscreen.notify_wait(self.net_interface_text.value + ' has been updated!', form_color='GOOD') self.parentApp.suricata_config.write_config() self.parentApp.removeForm('MAIN') self.parentApp.addForm('MAIN', SuricataInstanceSettingsForm, name='Suricata Instance Configuration') self.parentApp.switchForm('MAIN')
def _generateTestData(pager): i = 0 while i <= 6: time.sleep(1) pager.values.append("Test string!!") pager.update() i = i + 1 if i == 3: npyscreen.notify_ok_cancel("procced?")
def on_ok(self, *args, **keywords): npyscreen.notify("Adding new feed...", title = "Status") with session_scope() as session: feed_id = md.add_feed(session, self.feedurl.value) if feed_id == -1: npyscreen.notify_ok_cancel("Failed to add feed.", title = "Error") else: md.update_feeditems(session, feed_id) npyscreen.notify('Feed added!') time.sleep(0.75) self.parentApp.switchFormPrevious()
def on_ok(self, *args, **keywords): npyscreen.notify("Adding new feed...", title="Status") with session_scope() as session: feed_id = md.add_feed(session, self.feedurl.value) if feed_id == -1: npyscreen.notify_ok_cancel("Failed to add feed.", title="Error") else: md.update_feeditems(session, feed_id) npyscreen.notify('Feed added!') time.sleep(0.75) self.parentApp.switchFormPrevious()
def on_cancel(self): """ Message will be send """ if self.current_peer: text = self.chat_box.entry_widget.value.strip() if text: send_status = self.TG.sender.send_msg(self.current_peer.print_name, text) if send_status: self.chat_box.entry_widget.value = "" self.load_history(current_dialog=self.current_peer) self.editw = self._widgets__.index(self.chat_box) else: npyscreen.notify_ok_cancel('Please select receiver first.')
def on_ok(self): kafka_enabled = self.parentApp.filebeat_config.is_kafka_output_enabled( ) if not InstallManager.validate_targets( targets=[self.target_text.value]): npyscreen.notify_ok_cancel( 'Target must be given in the format: host:port (E.G 192.168.0.100:5044)', form_color='DANGER') return if kafka_enabled: kafka_config = self.parentApp.filebeat_config.get_kafka_target_config( ) original_targets = list(kafka_config.get('hosts', [])) else: original_targets = list( self.parentApp.filebeat_config.get_logstash_target_hosts()) if self.value: edit_target_index = original_targets.index(self.value) original_targets[edit_target_index] = self.target_text.value npyscreen.notify_wait(self.target_text.value + ' has been updated!', form_color='GOOD') else: original_targets.append(self.target_text.value) npyscreen.notify_wait(self.target_text.value + ' has been created!', form_color='GOOD') if kafka_enabled: username, password = self.username_text.value, self.password_text.value if self.username_text.value.strip() == '': username = None if self.password_text.value.strip() == '': password = None self.parentApp.filebeat_config.set_kafka_targets( original_targets, topic=self.topic_text.value, username=username, password=password) else: self.parentApp.filebeat_config.set_logstash_targets( original_targets) # Switch back to the main interface self.parentApp.filebeat_config.write_config() self.parentApp.removeForm('MAIN') self.parentApp.addForm('MAIN', FilebeatInstanceSettingsForm, name='FileBeat Configuration') self.parentApp.switchForm('MAIN')
def on_cancel(self): """ Message will be send """ if self.dialog_list.entry_widget and self.dialog_list.entry_widget.value: selected_index = self.dialog_list.entry_widget.value[0] dialog_name = self.dialog_list.values[selected_index] text = self.chat_box.entry_widget.value.strip() if text: send_status = TG.sender.send_msg(dialog_name, text) if send_status: self.chat_box.entry_widget.value = "" self.load_history() self.dialog_list.entry_widget.value = self.dialog_list.values.index(self.current_peer.print_name) self.editw = self._widgets__.index(self.chat_box) else: npyscreen.notify_ok_cancel('Please select receiver first.')
def on_ok(self): pin_cpus = [] for cpu in self.cpus_text.value.split(','): try: pin_cpus.append(int(cpu.strip())) except ValueError: npyscreen.notify_ok_cancel( 'CPU Affinity must be given as a list of integers separated by commas.', form_color='DANGER') return try: int(self.threads_text.value) except ValueError: npyscreen.notify_ok_cancel( 'Worker Threads must be given as an integer.', form_color='DANGER') return if not self.net_interface_text.value: npyscreen.notify_ok_cancel('Network Interface cannot be blank.', form_color='DANGER') return if not self.worker_name_text.value: npyscreen.notify_ok_cancel('Worker name cannot be blank.', form_color='DANGER') return if not self.host_text.value: npyscreen.notify_ok_cancel('Host name cannot be blank.', form_color='DANGER') return if self.value: self.parentApp.zeek_config.remove_worker(self.value) self.parentApp.zeek_config.add_worker( name=self.worker_name_text.value, interface=self.net_interface_text.value, host=self.host_text.value, lb_procs=self.threads_text.value, pin_cpus=tuple(pin_cpus)) # Switch back to the main interface npyscreen.notify_wait(self.worker_name_text.value + ' has been updated!', form_color='GOOD') self.parentApp.zeek_config.write_config() self.parentApp.removeForm('MAIN') self.parentApp.addForm('MAIN', ZeekNodeSettingsForm, name='Zeek Node Configuration') self.parentApp.switchForm('MAIN')
def _do_install(self): global cl_install_without_ticket, cl_install_with_ticket if len(self.selected_values) == 0: npyscreen.notify_confirm('The install list is empty', title='WARNING') return else: if not npyscreen.notify_ok_cancel( 'You are about to download selected title', title='WARNING'): return key_list = [] key_with_ticket = [] key_without_ticket = [] for title_key in self.selected_values: if title_key.ticket: key_with_ticket.append(title_key.tid) else: key_without_ticket.append(title_key.tid) if len(key_with_ticket) > 0: cl_install_with_ticket = '{} -title {} -onlinetickets'.format( funkiiu_exec, ' '.join(key_with_ticket)) if len(key_without_ticket) > 0: cl_install_without_ticket = '{} -title {} -onlinekeys'.format( funkiiu_exec, ' '.join(key_without_ticket)) self._do_exit()
def error_msg(self, message,msg_title): opt = _nps.notify_ok_cancel(message, title=msg_title, form_color='STANDOUT') #user wants to end if opt == True: _APP.setNextForm(None) _APP.editing = False _APP.switchFormNow()
def write_config(self): config = None output_file = None global _conf_file_name _conf_file_name = self.file_name.value global _conf_file_destination _conf_file_destination = self.file_destination.value final_destination = os.path.join(_conf_file_destination,_conf_file_name) try: #check if file exists - stop if it does if os.path.isfile(final_destination): opt = _nps.notify_ok_cancel("A file with the same name already exists at this location. Would you like to add to this file?", title=ERROR_MSGS[2]) if opt == True: output_file = open(final_destination,"a") else: return else: output_file = open(final_destination,"w") #from the _vm_list dict build config strings and write each to the file for key in _vm_list: config = ConfigObj(unrepr=True) vm = _vm_list[key] if vm.os_type == "Linux": config['ostype '] = "\""+vm.os_type+"\";" config['sysmap '] = "\""+vm.linux_sysmap+"\";" config['linux_name '] = vm.linux_name+";" config['linux_tasks '] = vm.linux_tasks+";" config['linux_mm '] = vm.linux_mm+";" config['linux_pid '] = vm.linux_pid+";" config['linux_pgd '] = vm.linux_pgd+";" else: config['ostype '] = "\""+vm.os_type+"\";" config['win_tasks '] = vm.win_tasks+";" config['win_pdbase '] = vm.win_pdbase+";" config['win_pid '] = vm.win_pid+";" output = vm.name+" " output = output+str(config) output = output.replace("'","").replace(",","").replace(":","=") output = output +"\n" self.status.value ="Writing VM "+vm.name self.display() output_file.write(output) self.status.value ="Finished Writing File....Waiting..." self.display() except IOError as e: self.error_msg("There was an error accessing the file: "+e.detail,ERROR_MSGS[2]) return finally: if output_file != None: output_file.close() self.display_text("Finished writing configuration file \""+_conf_file_name+"\" to desintation: "+_conf_file_destination)
def delete_command(self, command): confirmed = npyscreen.notify_ok_cancel(command.command.encode('utf8'), "Delete Command") if confirmed: result = rest_client.delete_command(command.uuid) if result: self.parent.parentApp.commands.remove(command) self.parent.update_list()
def createModuleForm(self): #Create the ModuleForm workflow = self.get_widget("select_workflow").values[self.get_widget( "select_workflow").value[0]] #If the workflow is different, recreate it if self.parentApp.AxAnal: if self.parentApp.AxAnal.workflow != workflow: #Throw up a warning that all options will be overwritten response = nps.notify_ok_cancel( "Warning: Changing workflows will reset all previously entered values (including from loaded .ax file). Do you wish to continue?", title="Warning") if response: self.parentApp.AxAnal = AxiomeAnalysis( self.parentApp.ax_file, workflow) module_form = ModuleForm(parentApp=self.parentApp) self.parentApp.registerForm("MODULE", module_form) else: #We didn't actual create the ModuleForm return False else: self.parentApp.AxAnal = AxiomeAnalysis(self.parentApp.ax_file, workflow) module_form = ModuleForm(parentApp=self.parentApp) self.parentApp.registerForm("MODULE", module_form) #If the page doesn't exist (in case where AxAnal is loaded from # .ax file), then make it if "MODULE" not in self.parentApp.getHistory(): module_form = ModuleForm(parentApp=self.parentApp) self.parentApp.registerForm("MODULE", module_form) return True
def quickWipeAll(self): #Quickwipes all drives #check resolve message = "I will now attempt to quickwipe EVERY drive on this list! Once you hit ok, there's no going back!" confirm = npyscreen.notify_ok_cancel(message, title="Quick Wipe All", editw = 1) if not confirm: return #Init error watcher errors = [] for num in range(len(self.values)): errors.append(self.quickWipeDisk(rowNum = num, suppressMessages = True)) #Start building any error message cleanErrors = [] for error in errors: if error: cleanErrors.append(error) if len(cleanErrors) > 0: for error in cleanErrors: message = error + "\n" message = "Quickwipe is complete, but the following disks ran into problems. Investigate and re-wipe the following:\n" + message npyscreen.notify_confirm(message, title="ErrorList", editw = 1) else: npyscreen.notify_confirm("Quickwipe completed successfully!", title="Success!", editw = 1) #After wiping all, rescan all self.scanAndTest()
def _insert_windows_vm(name, tasks, pdbase, pid): global _vm_list global _vm_list_size global _vm_list_os_windows vm = None vm = _vm_list.get(name) #vm exists, check if the os is the same if vm != None: if vm.os_type == "Windows": #ask the user if they want to write over the machine opt = _nps.notify_ok_cancel( "A virtual machine with the name " + name + " already exists for this config. Would you like to overwrite the entry?", title=ERROR_MSGS[4]) if opt == False: return else: #decrement so the list size is the same _vm_list_size += -1 _vm_list_os_windows += -1 vm = VM(name, "Windows") vm.win_tasks = tasks vm.win_pdbase = pdbase vm.win_pid = pid _vm_list_os_windows += 1 _vm_list[name] = vm _vm_list_size += 1 notify("Added Linux Virtual Machine: " + str(name), NOTIFY_MSGS[0]) return True
def _insert_windows_vm(name,tasks,pdbase,pid): global _vm_list global _vm_list_size global _vm_list_os_windows vm = None vm = _vm_list.get(name) #vm exists, check if the os is the same if vm !=None: if vm.os_type == "Windows": #ask the user if they want to write over the machine opt = _nps.notify_ok_cancel("A virtual machine with the name "+name+" already exists for this config. Would you like to overwrite the entry?", title=ERROR_MSGS[4]) if opt == False: return else: #decrement so the list size is the same _vm_list_size+=-1 _vm_list_os_windows+=-1 vm = VM(name,"Windows") vm.win_tasks = tasks vm.win_pdbase = pdbase vm.win_pid = pid _vm_list_os_windows+=1 _vm_list[name] = vm _vm_list_size+=1 notify("Added Linux Virtual Machine: "+str(name),NOTIFY_MSGS[0]) return True
def delete_command(self, command): confirmed = npyscreen.notify_ok_cancel(str(command), "Delete Command") if confirmed: result = rest_client.delete_command(command.uuid) if result: self.parent.parentApp.commands.remove(command) self.parent.update_list()
def show_help(self, *args): help_message = """ This is the help message so you can read it""" message_to_display = 'You have a choice, to Cancel and return false, or Ok and return true.' notify_result = npyscreen.notify_ok_cancel(message_to_display, title='popup')
def whenPressed(self): kafka_enabled = self.parent.parentApp.filebeat_config.is_kafka_output_enabled() if kafka_enabled: target_type = 'Kafka' else: target_type = 'LogStash' res = npyscreen.notify_ok_cancel( 'Are you sure you want to delete this target - {} {}?'.format(target_type, self.delete_value), form_color='WARNING', ) if not res: return if kafka_enabled: kafka_config = self.parent.parentApp.filebeat_config.get_kafka_target_config() kafka_config['hosts'].remove(self.delete_value) self.parent.parentApp.filebeat_config.kafka_targets = kafka_config else: logstash_config = self.parent.parentApp.filebeat_config.get_logstash_target_config() logstash_config['hosts'].remove(self.delete_value) self.parent.parentApp.filebeat_config.logstash_targets = logstash_config self.parent.parentApp.filebeat_config.write_config() self.parent.parentApp.removeForm('MAIN') self.parent.parentApp.addForm('MAIN', FilebeatInstanceSettingsForm, name='FileBeat Configuration') self.parent.parentApp.switchForm('MAIN')
def system_commands(self, action): """ Perform system commands """ if action == "reset": okay = npyscreen.notify_ok_cancel( "This factory reset will remove ALL of Vent's user data, " "containers, and images. Are you sure?", title="Confirm system command") if okay: d_cli = docker.from_env() # remove containers list = d_cli.containers.list(filters={'label':'vent'}, all=True) for c in list: c.remove(force=True) # remove images list = d_cli.images.list(filters={'label':'vent'}, all=True) for i in list: d_cli.images.remove(image=i.id, force=True) # remove .vent folder try: shutil.rmtree(os.path.join(os.path.expanduser('~'),'.vent')) except Exception as e: # pragma: no cover npyscreen.notify_confirm("Error deleting Vent data: "+repr(e)) else: npyscreen.notify_confirm("Vent reset complete. " "Press OK to exit Vent Manager console.") self.exit() pass elif action == "upgrade": # !! TODO pass return
def createModuleForm(self): #Create the ModuleForm workflow = self.get_widget("select_workflow").values[self.get_widget("select_workflow").value[0]] #If the workflow is different, recreate it if self.parentApp.AxAnal: if self.parentApp.AxAnal.workflow != workflow: #Throw up a warning that all options will be overwritten response = nps.notify_ok_cancel("Warning: Changing workflows will reset all previously entered values (including from loaded .ax file). Do you wish to continue?", title="Warning") if response: self.parentApp.AxAnal = AxiomeAnalysis(self.parentApp.ax_file, workflow) module_form = ModuleForm(parentApp=self.parentApp) self.parentApp.registerForm("MODULE",module_form) else: #We didn't actual create the ModuleForm return False else: self.parentApp.AxAnal = AxiomeAnalysis(self.parentApp.ax_file, workflow) module_form = ModuleForm(parentApp=self.parentApp) self.parentApp.registerForm("MODULE",module_form) #If the page doesn't exist (in case where AxAnal is loaded from # .ax file), then make it if "MODULE" not in self.parentApp.getHistory(): module_form = ModuleForm(parentApp=self.parentApp) self.parentApp.registerForm("MODULE", module_form) return True
def on_cancel(self): response = nps.notify_ok_cancel("Are you sure you want to exit? All unsaved changes will be lost.", title="Exit?", form_color='STANDOUT', wrap=True, editw=0) if response: self.parentApp.setNextForm(None) self.editing = False else: self.editing = True
def _insert_linux_vm(vm_name,tasks,name,mm,pid,pgd,sysmap): global _vm_list global _vm_list_size global _vm_list_os_linux vm = None vm = _vm_list.get(name) #vm exists, check if the os is the same if vm !=None: if vm.os_type == "Linux": #ask the user if they want to write over the machine opt = _nps.notify_ok_cancel("A virtual machine with the name "+name+" already exists for this config. Would you like to overwrite the entry?", title=ERROR_MSGS[4]) if opt == False: return else: #decrement so the list size is the same _vm_list_size+=-1 _vm_list_os_linux+=-1 vm = VM(vm_name,"Linux") vm.linux_tasks = tasks vm.linux_name = name vm.linux_mm = mm vm.linux_pid = pid vm.linux_pgd = pgd vm.linux_sysmap = sysmap _vm_list_os_linux += 1 _vm_list[name] = vm _vm_list_size+=1 notify("Added Linux Virtual Machine: "+str(name),NOTIFY_MSGS[0]) return True
def _insert_linux_vm(vm_name, tasks, name, mm, pid, pgd, sysmap): global _vm_list global _vm_list_size global _vm_list_os_linux vm = None vm = _vm_list.get(name) #vm exists, check if the os is the same if vm != None: if vm.os_type == "Linux": #ask the user if they want to write over the machine opt = _nps.notify_ok_cancel( "A virtual machine with the name " + name + " already exists for this config. Would you like to overwrite the entry?", title=ERROR_MSGS[4]) if opt == False: return else: #decrement so the list size is the same _vm_list_size += -1 _vm_list_os_linux += -1 vm = VM(vm_name, "Linux") vm.linux_tasks = tasks vm.linux_name = name vm.linux_mm = mm vm.linux_pid = pid vm.linux_pgd = pgd vm.linux_sysmap = sysmap _vm_list_os_linux += 1 _vm_list[name] = vm _vm_list_size += 1 notify("Added Linux Virtual Machine: " + str(name), NOTIFY_MSGS[0]) return True
def when_delete_box(self, *args, **kwargs): delete_confirmation = npyscreen.notify_ok_cancel(message="You're about to delete this box. There's NO UNDO. " "Are you sure?", title="WARNING") if delete_confirmation is True: self.parent.parentApp.application_logic.delete_box_by_uuid(self.values[self.cursor_line][0]) self.parent.update_list()
def on_cancel(self): exit = npyscreen.notify_ok_cancel("Are you sure you want to cancell?", title="Exit?", editw=1) if (exit): self.parentApp.setNextForm(None) else: pass
def when_delete_record(self, *args, **keywords): ok = npyscreen.notify_ok_cancel("Sure you want to delete entry?", title="Confirm") if (ok): self.parent.parentApp.gamedata.delete_game( self.values[self.cursor_line]) self.parent.parentApp.gamedata.load_games() self.parent.parentApp.switchFormPrevious()
def terminate_vm(): main.kill_threads() if npyscreen.notify_ok_cancel( "Do you really want to terminate this vm:\nName: " + name + "\nID: " + id, "VM Termination", ): main.GATEWAY.DeleteVms(VmIds=[id]) exit()
def do_quit(self): if npyscreen.notify_ok_cancel("Quit the AAPTOS client?", title="Confirm", form_color='STANDOUT', wrap=True, editw=1): self.parentApp.setNextForm(None) self.editing = False self.parentApp.switchFormNow()
def when_delete_box(self, *args, **kwargs): delete_confirmation = npyscreen.notify_ok_cancel( message="You're about to delete this box. There's NO UNDO. " "Are you sure?", title="WARNING") if delete_confirmation is True: self.parent.parentApp.application_logic.delete_box_by_uuid( self.values[self.cursor_line][0]) self.parent.update_list()
def on_ok(self): ok_cancel = npyscreen.notify_ok_cancel("Are you sure you want to execute selected task?", "Warning", editw=2) if ok_cancel: if self.option.values[self.option.value[0]] == "Shutdown": shutdown() else: reboot() self.parentApp.setNextForm(None) else: self.parentApp.setNextFormPrevious
def delete_cb(): delete = npyscreen.notify_ok_cancel( "You will delete permanently the keypair named " + name, "Warning") if delete: try: val = main.GATEWAY.DeleteKeypair(form=form, KeypairName=name) except BaseException: raise form.current_grid.h_refresh(None) exit()
def terminate_vm(): main.kill_threads() if npyscreen.notify_ok_cancel( "Do you really want to terminate this vm:\nName: " + name + "\nID: " + id, "VM Termination", ): main.GATEWAY.DeleteVms(form=form, VmIds=[id]) form.current_grid.h_refresh(None) exit()
def on_ok(self): if not self.host_text.value: npyscreen.notify_ok_cancel('Host name cannot be blank.', form_color='DANGER') return if not self.component_name_text.value: npyscreen.notify_ok_cancel('{} name cannot be blank.'.format( self.component_type.capitalize()), form_color='DANGER') return if self.value: if self.component_type == 'logger': self.parentApp.zeek_config.remove_logger(self.value) if self.component_type == 'proxy': self.parentApp.zeek_config.remove_proxy(self.value) elif self.component_type == 'manager': self.parentApp.zeek_config.remove_manager(self.value) self.parentApp.zeek_config.add_manager( name=self.component_name_text.value, host=self.host_text.value, ) if self.component_type == 'logger': self.parentApp.zeek_config.add_logger( name=self.component_name_text.value, host=self.host_text.value, ) elif self.component_type == 'proxy': self.parentApp.zeek_config.add_proxy( name=self.component_name_text.value, host=self.host_text.value, ) # Switch back to the main interface self.parentApp.zeek_config.write_config() npyscreen.notify_wait(self.component_name_text.value + ' has been updated!', form_color='GOOD') self.parentApp.removeForm('MAIN') self.parentApp.addForm('MAIN', ZeekNodeSettingsForm, name='Zeek Node Configuration') self.parentApp.switchForm('MAIN')
def selectRow(self, input): selectedRow = self.hoursgrid.selected_row() if selectedRow[4] == "-": # The default No entries-entry has been selected. return result = npyscreen.notify_ok_cancel( "Do you want to delete the entry on {} for {} hour(s)?".format( selectedRow[0], selectedRow[2])) if result: self.parentApp.db.deleteHours(selectedRow[4]) self.parentApp.switchForm('MAIN')
def a_del(self, *args): num = self.wgCards.entry_widget.value if num is None: npyscreen.notify_wait( "No card selected. Use ENTER to select a card") return if not npyscreen.notify_ok_cancel("Really delete {}?".format( hex(self._values[num]))): return del self._values[num] self._refresh_list()
def on_cancel(self): response = nps.notify_ok_cancel( "Are you sure you want to exit? All unsaved changes will be lost.", title="Exit?", form_color='STANDOUT', wrap=True, editw=0) if response: self.parentApp.setNextForm(None) self.editing = False else: self.editing = True
def clearNews(self, *args, **kwargs): action = npyscreen.notify_ok_cancel("Are you sure you want to clear the news?", "Clear news") if action: if not self.parent.librewired.privileges['clearNews']: npyscreen.notify_confirm("Not allowed to clear news!", "Clear News") return 0 self.parent.librewired.clearNews() self.box.values = [] self.box.display() self.populate() return 1 return 0
def del_rule(self): if self.check_data(): if npyscreen.notify_ok_cancel( message='Delete {0} rule in iptables?'.format( self.number.value), title='Warning!', form_color='WARNING'): subprocess.check_output( ['bash', 'sh_script/del_iptables.sh', self.number.value]).decode("utf-8") # subprocess.check_output(['python', 'time_now.py']).decode("utf-8") self.parentApp.switchForm('MAIN')
def execMemoryReport(self): if self.filename is None: npyscreen.notify_confirm("No RDB file selected", title='Please Wait', editw=1) return self.cmd = MEMORY_REPORT_COMMAND.format(self.filename) #estimate needed time if self.fileSize / (1024.0 * 1024.0) < 200.0: self.sec_per_mb *= 2 self.estSecs = int(self.sec_per_mb * self.fileSize / (1024.0 * 1024.0)) #s per Mb estTimeStr = str(timedelta(seconds=self.estSecs)) start = npyscreen.notify_ok_cancel( "Execute a memory report? This operation may take a long time.\nEstimated Time: ~{}" .format(estTimeStr), title='Confirm', editw=1) if start: #set correct types self.activeDB = set() self.keyPerDB = {} self.totKey = 0 self.keyTypeCount = { 'string': 0, 'hash': 0, 'set': 0, 'sortedset': 0, 'list': 0 } self.keyTypeSizeCount = { 'string': 0, 'hash': 0, 'set': 0, 'sortedset': 0, 'list': 0 } self.totKeySize = 0 self.processStartTime = time.time() ntfPopup = npyscreen.notify_confirm( "Memory report in progress... \nResult will be saved in \'mem_report.txt\'.", title='Please Wait', editw=1) #Long command self.memThread = threading.Thread(name='memThread', target=self.memReportFunction) self.memThread.setDaemon(True) self.memThread.start()
def localActionSelected(self, sourcepath, pathtype, action): if 'Upload' in action: if not self.librewired.privileges['uploadAnywhere'] and int(self.remoteview.dirtype) <= 1: npyscreen.notify_confirm("You are not allowed to upload to the remote directory", "Not allowed to upload") return 0 target = self.remoteview.path confirm = npyscreen.notify_ok_cancel("Upload %s to folder %s?" % (sourcepath, target), "Start upload") if not confirm: return 0 transfer = self.librewired.upload(sourcepath, target) self.parent.transfers.append(transfer) return 1
def confirm_remove_vm(self): global _vm_list_size if _vm_list_size == 0: error("There are no virtual machines, please add more virtual machines",ERROR_MSGS[0]) return opt = self.vm_option.get_selected_objects() global _vm_list vm = _vm_list.get(opt[0]) #TODO individual OS count change? name = vm.name confirm = _nps.notify_ok_cancel("Are you sure you want to remove the virtual machine "+name,title="Confirm Remove VM") if confirm == False: return del _vm_list[opt[0]] _vm_list_size+=-1 self.display_text("Removed virtual machine "+name) self.parentApp.switchForm('REMOVE_VM')
def on_ok(self): if not self.validate_forms(): self.editing = True return # Ensure owner_id references valid sin in db. # If not we need to prompt the user to enter the person into the people # db. We will open this form as a popup. query = "SELECT COUNT(sin) FROM people WHERE sin = :sin" if self.parentApp.db.query({'sin':self.owner_id.value.\ ljust(15, ' ')}, query)[0][0] == 0: # Prompt to add a new person. response = npyscreen.notify_ok_cancel( "This person does not currently exist.\n" "Enter a person with this SIN into the database?", title="Alert", form_color='STANDOUT', wrap=True, editw=1) # If user selected ok forward them to the add person form. if response: self.parentApp.AP_default = self.owner_id.value # Set the next form to be the people form. If the add person # form exits with switchFormPrevious we should end up back here. # self.parentApp.setNextFormPrevious('NEWVEHICLEREGISTRATION') self.AP_goto_NVR = True self.parentApp.switchForm('ADDPERSON') else: self.editing=True return if self.is_primary_owner.value[0] == 0: # 'Y' selected self.parentApp.NVR_primary_owner[0] = self.owner_id.value elif self.is_primary_owner.value[0] == 1: # 'N' selected if self.owner_id.value not in self.parentApp.NVR_other_owners and \ self.owner_id.value != self.parentApp.NVR_primary_owner[0]: self.parentApp.NVR_other_owners.append(self.owner_id.value) self.parentApp.switchFormPrevious()
def do_quit(self): if npyscreen.notify_ok_cancel("Quit the AAPTOS client?", title="Confirm", form_color='STANDOUT', wrap=True, editw = 1): self.parentApp.setNextForm(None) self.editing = False self.parentApp.switchFormNow()
def try_exit(self): exit_confirmation = npyscreen.notify_ok_cancel(message="Really wanna exit?", title="Warning") if exit_confirmation is True: npyscreen.blank_terminal() exit(0)
def on_ok(self): # Deal with sin entered not being in db. If not we need to prompt the # user to enter the person into the people table. We will open this form # as a popup. query = "SELECT COUNT(sin) FROM people WHERE sin = :sin" if self.parentApp.db.query( {'sin':self.sin.value.ljust(15, ' ')}, query)[0][0] == 0: # prompt to add a new person. response = npyscreen.notify_ok_cancel( "This person does not exist.\n" "Enter a person with this SIN into the database?", title="Alert", form_color='STANDOUT', wrap=True, editw=1) # If user selected ok forward them to the add person form. if response: # Set the next form to be the people form. # set vehicle_id to match the specified value before switching self.parentApp.AP_default = self.sin.value self.parentApp.switchForm('ADDPERSON') else: return return False # validate the form. if not self.validate_forms(): self.editing = True return # attempt to open the image file if self.photo.value: try: image_file = open(self.photo.value, 'rb') except IOError as exc: error, = exc.args npyscreen.notify_confirm(error.message, editw=1, title='Image Load failure') self.editing = True return # If we are successful in opening, prep image for db entry. if self.photo.value: image = image_file.read() self.parentApp.db.cursor.setinputsizes(photo=cx_Oracle.BLOB) if self.photo.value: image_file.close() else: # Should be null value. image = '' # prep and send db statement insert = """INSERT INTO drive_licence (licence_no, sin, class, photo, issuing_date, expiring_date) VALUES (:licence_no, :sin, :class, :photo, :issuing_date, :expiring_date)""" entry_dict = {'licence_no':str(self.licence_no.value), 'sin':str(self.sin.value), 'class':str(self.licence_class.value), 'photo':image, 'issuing_date':self.issuing_date.value, 'expiring_date':self.expiring_date.value} error = self.parentApp.db.insert(entry_dict, insert) if error: self.editing = True # don't return to main menu # print error to screen npyscreen.notify_confirm(str(error), title="Status", form_color='STANDOUT', wrap=True, wide=False, editw=1) return # If we get here we have a successful entry. Notify the user. npyscreen.notify_confirm("Success!", title="Status", form_color='STANDOUT', wrap=True, wide=False, editw=1) # Clear the form for the next entry self.licence_no.value = '' self.sin.value = '' self.licence_class.value = '' self.photo.value = '' self.issuing_date.value = '' self.expiring_date.value = ''
def on_ok(self): #Get the save file path file_name = self.get_widget("save_filename").value if not file_name: nps.notify_wait("Save File Location must be specified.", title="Error", form_color='STANDOUT', wrap=True, wide=True) self.editing = True return if isdir(file_name): nps.notify_wait("Save File Location must not be a directory.", title="Error", form_color='STANDOUT', wrap=True, wide=True) self.editing = True return #Options are OK. Now write the file: directory = dirname(abspath(file_name)) if not exists(directory): makedirs(directory) try: with open(file_name,'w') as out_ax: #Start with the XML header #We are manually writing XML, because that's how I roll ax_file_string = '<?xml version="1.0"?>\n<axiome workflow="%s">\n' % self.parentApp.AxAnal.workflow submodules = list() for widget_info in self.parentApp.getForm("MODULE")._widget_list: module_name = widget_info["module_name"] #Get the selection(s) from the selection widget widget = widget_info["widget"] selections = widget.value if module_name != "source": for choice in selections: submodules.append([module_name, widget.values[choice]]) else: submodules.append(["source",None]) #For each module, go through the submodule page list to find a match for submodule in submodules: module_name = submodule[0] submodule_name = submodule[1] #Special case: source if module_name == "source": mapping_file = self.parentApp.getForm("MODULE").get_widget("module_source").value ax_file_string += '\t<!--source mapping_file="%s"-->\n' % mapping_file ax_file_string += self.file_mapping_to_ax(mapping_file) else: found = False for submodule_form in self.parentApp.submodule_forms_data: if (submodule_form["module_name"] == module_name) & (submodule_form["submodule_name"] == submodule_name): found = True #If it matches, write a line for it def_string = "" requirements = submodule_form["form"]._value for item in requirements["input"]: #Get the widget and its value widget_id = item["name"] widget_type = item["type"] widget_value = submodule_form["form"].get_widget(widget_id).value if widget_value: #Coerce the string to be an integer if widget_type == "int": widget_value = int(widget_value) def_string += ' %s="%s"' % (widget_id, widget_value) ax_file_string += '\t<%s method="%s"%s/>\n' % (module_name, submodule_name, def_string) if not found: ax_file_string += '\t<%s method="%s"/>\n' % (module_name, submodule_name) ax_file_string += "</axiome>" out_ax.write(ax_file_string) except: nps.notify_wait("Error writing to given directory. Check if folder exists and its permissions.", title="Error", form_color='STANDOUT', wrap=True, wide=True) self.editing = True return response = nps.notify_ok_cancel("File saved successfully to %s. Do you want to exit?" % (file_name), title="Saved!", form_color='STANDOUT', wrap=True, editw=0) if response: self.parentApp.setNextForm(None) self.editing = False else: self.editing = True
def fileInfo(parent, info): form = npyscreen.ActionPopup(name=info.path, lines=20, columns=40) form.show_atx = int((parent.max_x-40)/2) show_aty = 2 form.on_ok = rewireFunctions.on_ok form.on_cancel = rewireFunctions.on_cancel name = form.add_widget(npyscreen.TitleText, name="Name:", value=path.basename(info.path), begin_entry_at=10, rely=2, editable=int(parent.librewired.privileges['alterFiles'])) where = form.add_widget(npyscreen.TitleFixedText, name="Where:", value=path.dirname(info.path), begin_entry_at=12, rely=4, editable=0) types = ['File', 'Folder', 'Upload Folder', 'Dropbox'] objtype = form.add_widget(npyscreen.TitleFixedText, name="Type:", value=types[int(info.type)], begin_entry_at=12, rely=6, editable=0) sizestring = "%s items" % info.size if not int(info.type): sizestring = rewireFunctions.format_size(int(info.size)) size = form.add_widget(npyscreen.TitleFixedText, name="Size:", value=sizestring, begin_entry_at=12, rely=8, editable=0) created = form.add_widget(npyscreen.TitleFixedText, name="Created:", value=str(strftime('%Y/%m/%d %H:%M:%S', localtime(int(rewireFunctions.wiredTimeToTimestamp(info.created))))), begin_entry_at=12, rely=10, editable=0) modified = form.add_widget(npyscreen.TitleFixedText, name="Modified:", value=str(strftime('%Y/%m/%d %H:%M:%S', localtime(int(rewireFunctions.wiredTimeToTimestamp(info.modified))))), begin_entry_at=12, rely=11, editable=0) if not int(info.type): kind = 0 cheksum = form.add_widget(npyscreen.TitleFixedText, name="Checksum:", value=str(info.checksum), begin_entry_at=12, rely=13, editable=0) if int(info.type) in range(1, 4): foldertype = ['Folder', 'Upload Folder', 'Dropbox'] kind = form.add_widget(npyscreen.TitleSelectOne, name="Kind:", values=foldertype, value=int(info.type)-1, rely=13, max_height=2, editable=int(parent.librewired.privileges['alterFiles'])) commentlabel = form.add_widget(npyscreen.FixedText, value="Comment:", rely=15, editable=0) if not info.comment: info.comment = "" comment = form.add_widget(npyscreen.MultiLineEdit, name="Comment:", value=str(info.comment), relx=14, rely=15, max_height=2, max_width=23, editable=int(parent.librewired.privileges['alterFiles'])) form.editw = 8 if info.path == '/': name.value = '/' name.editable = 0 kind.editable = 0 action = form.edit() if action: if name.value != path.basename(info.path): if parent.librewired.privileges['alterFiles']: newpath = path.join(path.dirname(info.path), name.value) confirm = npyscreen.notify_ok_cancel("Rename %s to %s?" % (info.path, newpath)) if confirm: if not parent.librewired.move(info.path, newpath): npyscreen.notify_confirm("Server failed to rename file", "Server Error") else: info.path = newpath parent.remoteview.populate() if kind: if int(kind.value[0] + 1) != int(info.type): if parent.librewired.privileges['alterFiles']: newtype = int(kind.value[0] + 1) if not parent.librewired.changeType(info.path, newtype): npyscreen.notify_confirm("Server failed to change folder Type", "Server Error") else: info.type = newtype parent.remoteview.populate() if comment.value != info.comment: if parent.librewired.privileges['alterFiles']: if not parent.librewired.changeComment(info.path, str(comment.value)): npyscreen.notify_confirm("Server failed to apply new comment", "Server Error") else: info.comment = str(comment.value) return 0
def remoteActionSelected(self, sourcepath, pathtype, action): if 'Download' in action: target = self.localview.path confirm = npyscreen.notify_ok_cancel("Download %s to local folder %s?" % (sourcepath, target), "Start download") if not confirm: return 0 transfer = self.librewired.download(target, sourcepath) self.parent.transfers.append(transfer) elif 'Delete' in action: if npyscreen.notify_ok_cancel("Are you sure you want to delete %s?\nThis action cannot be undone!" % sourcepath, "Delete"): if not self.librewired.delete(sourcepath): npyscreen.notify_confirm("Server failed to delete %s" % sourcepath, "Server Error") return 0 self.remoteview.populate() return 1 return 0 elif 'Rename' in action: oldpath = sourcepath newpath = rewireFunctions.textDialog("Rename %s" % display_path(oldpath, 20), "New Name:", "Rename") if newpath: if not type(newpath) is str or search(r'[^A-Za-z0-9 _\-\.\\]', newpath): npyscreen.notify_confirm("You need to enter a valid new filename!") return 0 newpath = path.join(path.dirname(oldpath), newpath) if not self.librewired.move(oldpath, newpath): npyscreen.notify_confirm("Server failed to move %s to %s" % (oldpath, newpath), "Server Error") return 0 self.remoteview.populate() return 1 return 0 elif 'Create Folder' in action: options = ['Plain Folder'] #npyscreen.notify_confirm(str(pathtype)) if 'FILE' == str(pathtype): sourcepath = path.dirname(sourcepath) if self.librewired.privileges['alterFiles']: options.append('Drop Box') options.append('Uploads Folder') create = createFolder(display_path(sourcepath, 20), options) if create: foldertype = options[create[1]] if "Uploads Folder" == foldertype: foldertype = 2 elif "Drop Box" == foldertype: foldertype = 3 else: foldertype = 1 result = self.librewired.createFolder(path.join(sourcepath, create[0]), foldertype) if result: self.remoteview.populate() return 1 npyscreen.notify_confirm("Server failed to create Folder!", "Server Error") return 0 elif 'Info' in action: info = self.librewired.stat(sourcepath) if not info: npyscreen.notify_confirm("Server failed to deliver Info", "Server Error") return 0 infopopup = fileInfo(self, info) elif 'Move' in action: select = dirpopup(self) select.build() domove = select.edit() if domove: if select.value: name = path.basename(sourcepath) target = path.join(select.value, name) if sourcepath == target: npyscreen.notify_confirm("%s and %s are the same path" % (sourcepath, target), "Unable to move") return 0 if path.commonprefix([sourcepath, target]) == sourcepath: npyscreen.notify_confirm("Can't move %s into a subdir of itself" % sourcepath, "Unable to move") return 0 confirm = npyscreen.notify_ok_cancel("Move %s to %s" % (sourcepath, target), "Confirm move") if not confirm: return 0 result = self.librewired.move(sourcepath, target) if not result: npyscreen.notify_confirm("Failed to move %s" % sourcepath, "Server Error") return 0 self.remoteview.populate() return 1
def on_ok(self): """ Take the tool selections and perform the provided action on them """ def diff(first, second): """ Get the elements that exist in the first list and not in the second """ second = set(second) return [item for item in first if item not in second] def popup(original, orig_type, thr, title): """ Start the thread and display a popup of info until the thread is finished """ thr.start() info_str = '' while thr.is_alive(): if orig_type == 'containers': info = diff(Containers(), original) elif orig_type == 'images': info = diff(Images(), original) if info: info_str = '' for entry in info: info_str = entry[0] + ': ' + entry[1] + '\n' + info_str if self.action['action_name'] != 'configure': npyscreen.notify_wait(info_str, title=title) time.sleep(1) thr.join() try: result = self.api_action.queue.get(False) if isinstance(result, tuple) and isinstance(result[1], tuple): running, failed = result[1] r_str = '' for container in running: r_str += container + ': successful\n' for container in failed: r_str += container + ': failed\n' npyscreen.notify_confirm(r_str) except Exception as e: # pragma: no cover pass return if self.action['type'] == 'images': originals = Images() else: originals = Containers() tool_d = {} if self.action['action_name'] in ['remove', 'stop', 'update']: reconfirmation_str = '' if self.action['cores']: reconfirmation_str = 'Are you sure you want to ' reconfirmation_str += self.action['action_name'] reconfirmation_str += ' core containers?' else: reconfirmation_str = 'Are you sure you want to ' reconfirmation_str += self.action['action_name'] reconfirmation_str += ' plugin containers?' perform = npyscreen.notify_ok_cancel(reconfirmation_str, title='Confirm command') if not perform: return tools_to_configure = [] for repo in self.tools_tc: for tool in self.tools_tc[repo]: if self.tools_tc[repo][tool].value: t = tool.split(':', 2)[2].split('/')[-1] if t.startswith('/:'): t = ' '+t[1:] t = t.split(':') if self.action['action_name'] in ['start', 'stop']: status = self.action['action_object1'](repo, t[0]) elif self.action['action_name'] == 'configure': constraints = {'name': t[0], 'branch': t[1], 'version': t[2], 'repo': repo} options = ['type'] action = self.action['api_action'] tool = self.manifest.constrain_opts(constraints, options)[0] # only one tool should be returned name = list(tool.keys())[0] if tool[name]['type'] == 'registry': registry_image = True else: registry_image = False kargs = {'name': 'Configure ' + t[0], 'tool_name': t[0], 'branch': t[1], 'version': t[2], 'repo': repo, 'next_tool': None, 'get_configure': self.api_action.get_configure, 'save_configure': self.api_action.save_configure, 'restart_tools': self.api_action.restart_tools, 'start_tools': action.start, 'from_registry': registry_image} if tools_to_configure: kargs['next_tool'] = tools_to_configure[-1] self.parentApp.addForm('EDITOR' + t[0], EditorForm, **kargs) tools_to_configure.append('EDITOR' + t[0]) elif self.action['action_name'] == 'remove': status = self.action['action_object1'](repo, t[0]) else: kargs = {'name': t[0], 'branch': t[1], 'version': t[2]} # add core recognition if self.action['cores']: kargs.update({'groups': 'core'}) # use latest version for update, not necessarily # version in manifest if self.action['action_name'] == 'update': if t[2] != 'HEAD': repo_commits = self.tools_inst.repo_commits(repo)[ 1] for branch in repo_commits: if branch[0] == t[1]: kargs.update( {'new_version': branch[1][0]}) else: kargs.update({'new_version': 'HEAD'}) thr = Thread(target=self.action['action_object1'], args=(), kwargs=kargs) popup(originals, self.action['type'], thr, 'Please wait, ' + self.action['present_t'] + '...') if self.action['action_name'] != 'configure': npyscreen.notify_confirm('Done ' + self.action['present_t'] + '.', title=self.action['past_t']) self.quit() else: if len(tools_to_configure) > 0: self.parentApp.change_form(tools_to_configure[-1]) else: npyscreen.notify_confirm('No tools selected, returning to' ' main menu', title='No action taken') self.quit()