def save_profile(self, widget): if self.overwrite: self.profile.remove_profile(self.profile_name) profile_name = self.profile_name_entry.get_text() if profile_name == '': alert = HIGAlertDialog(message_format=_('Unnamed profile'),\ secondary_text=_('You must provide a name \ for this profile.' )) alert.run() alert.destroy() self.profile_name_entry.grab_focus() return None command = self.constructor.get_command('%s') buf = self.profile_description_text.get_buffer() description = buf.get_text(buf.get_start_iter(),\ buf.get_end_iter()) self.profile.add_profile(profile_name,\ command=command,\ description=description,\ options=self.constructor.get_options()) self.scan_interface.toolbar.profile_entry.update() self.scan_interface.refresh_command(None) self.destroy()
def help(self, widget): d = HIGAlertDialog( parent=self, message_format=_("Help not implemented"), secondary_text=_("Profile editor help is not implemented yet.")) d.run() d.destroy()
def execute_command(self, command, target = None, profile = None): """Run the given Nmap command. Add it to the list of running scans. Schedule a timer to refresh the output and check the scan for completion.""" command_execution = NmapCommand(command) command_execution.profile = profile try: command_execution.run_scan() except Exception, e: text = str(e) if isinstance(e, OSError): # Handle ENOENT specially. if e.errno == errno.ENOENT: # nmap_command_path comes from zenmapCore.NmapCommand. text += "\n\n" + _("This means that the nmap executable was not found in your system PATH, which is") + "\n\n" + os.getenv("PATH", _("<undefined>")) path_env = os.getenv("PATH") if path_env is None: default_paths = [] else: default_paths = path_env.split(os.pathsep) extra_paths = get_extra_executable_search_paths() extra_paths = [p for p in extra_paths if p not in default_paths] if len(extra_paths) > 0: if len(extra_paths) == 1: text += "\n\n" + _("plus the extra directory") else: text += "\n\n" + _("plus the extra directories") text += "\n\n" + os.pathsep.join(extra_paths) warn_dialog = HIGAlertDialog(message_format=_("Error executing command"), secondary_text=text, type=gtk.MESSAGE_ERROR) warn_dialog.run() warn_dialog.destroy() return
def __response_cb(self, widget, response_id): """Intercept the "response" signal to check if someone used the "By extension" file type with an unknown extension.""" if response_id == gtk.RESPONSE_OK and self.get_filetype() is None: ext = self.__get_extension() if ext == "": filename = self.get_filename() or "" dir, basename = os.path.split(filename) alert = HIGAlertDialog( message_format=_("No filename extension"), secondary_text=_("""\ The filename "%s" does not have an extension, \ and no specific file type was chosen. Enter a known extension or select the file type from the list.""" % basename)) else: alert = HIGAlertDialog( message_format=_("Unknown filename extension"), secondary_text=_("""\ There is no file type known for the filename extension "%s". Enter a known extension or select the file type from the list.\ """) % self.__get_extension()) alert.run() alert.destroy() # Go back to the dialog. self.emit_stop_by_name("response")
def start_search(self): if not self.options["search_db"] and not self.options["directory"]: d = HIGAlertDialog( message_format=_("No search method selected!"), secondary_text=_("%s can search results on directories or \ inside it's own database. Please, select a method by choosing a directory or by checking \ the search data base option at the 'Search options' tab before start the search" % APP_DISPLAY_NAME)) d.run() d.destroy() return self.clear_result_list() matched = 0 total = 0 if self.options["search_db"]: total += len(self.search_db.get_scan_results()) for result in self.search_db.search(**self.search_dict): self.append_result(result) matched += 1 for search_dir in self.search_dirs.itervalues(): total += len(search_dir.get_scan_results()) for result in search_dir.search(**self.search_dict): self.append_result(result) matched += 1 #total += len(self.search_tabs.get_scan_results()) #for result in self.search_tabs.search(**self.search_dict): # self.append_result(result) # matched += 1 self.search_window.set_label_text("Matched <b>%s</b> out of <b>%s</b> scans." % \ (str(matched), str(total)))
def open_file(self, widget): file_chooser = ResultsFileSingleChooserDialog(_("Select Scan Result")) response = file_chooser.run() file_chosen = file_chooser.get_filename() file_chooser.destroy() if response == gtk.RESPONSE_OK: try: parser = NmapParser() parser.parse_file(file_chosen) except xml.sax.SAXParseException, e: alert = HIGAlertDialog( message_format='<b>%s</b>' % _('Error parsing file'), secondary_text=_( "The file is not an Nmap XML output file. \ The parsing error that occurred was\n%s") % str(e)) alert.run() alert.destroy() return False except Exception, e: alert = HIGAlertDialog( message_format='<b>%s</b>' % _('Cannot open selected file'), secondary_text= _("This error occurred while trying to open the file:\n%s") % str(e)) alert.run() alert.destroy() return False
def run(): if os.name == "posix": signal.signal(signal.SIGHUP, safe_shutdown) signal.signal(signal.SIGTERM, safe_shutdown) signal.signal(signal.SIGINT, safe_shutdown) try: # Create the ~/.zenmap directory by copying from the system-wide # template directory. zenmapCore.Paths.create_user_config_dir(Path.user_config_dir, Path.config_dir) except (IOError, OSError), e: error_dialog = HIGAlertDialog(message_format = _("Error creating the per-user configuration directory"), secondary_text = _("""\ There was an error creating the directory %s or one of the files in it. \ The directory is created by copying the contents of %s. \ The specific error was\n\ \n\ %s\n\ \n\ %s needs to create this directory to store information such as the list of \ scan profiles. Check for access to the directory and try again.\ """) % (Path.user_config_dir, Path.config_dir, str(e), APP_DISPLAY_NAME)) error_dialog.run() error_dialog.destroy() sys.exit(1)
def run(): if os.name == "posix": signal.signal(signal.SIGHUP, safe_shutdown) signal.signal(signal.SIGTERM, safe_shutdown) signal.signal(signal.SIGINT, safe_shutdown) DEVELOPMENT = os.environ.get(APP_NAME.upper() + "_DEVELOPMENT", False) if not DEVELOPMENT: install_excepthook() zenmapCore.I18N.install_gettext(Path.locale_dir) try: # Create the ~/.zenmap directory by copying from the system-wide # template directory. create_user_config_dir(Path.user_config_dir, Path.config_dir) except (IOError, OSError), e: error_dialog = HIGAlertDialog( message_format=_( "Error creating the per-user configuration directory"), secondary_text=_("""\ There was an error creating the directory %s or one of the files in it. \ The directory is created by copying the contents of %s. \ The specific error was %s %s needs to create this directory to store information such as the list of \ scan profiles. Check for access to the directory and try again.""") % (repr(Path.user_config_dir), repr(Path.config_dir), repr( str(e)), APP_DISPLAY_NAME)) error_dialog.run() error_dialog.destroy() sys.exit(1)
def excepthook(type, value, tb): import traceback traceback.print_exception(type, value, tb) # Cause an exception if PyGTK can't open a display. Normally this just # produces a warning, but the lack of a display eventually causes a # segmentation fault. See http://live.gnome.org/PyGTK/WhatsNew210. import warnings warnings.filterwarnings("error", module="gtk") import gtk warnings.resetwarnings() gtk.gdk.threads_enter() from zenmapGUI.higwidgets.higdialogs import HIGAlertDialog from zenmapGUI.CrashReport import CrashReport if type == ImportError: d = HIGAlertDialog(type=gtk.MESSAGE_ERROR, message_format=_("Import error"), secondary_text=_("""A required module was not found. """ + unicode(value))) d.run() d.destroy() else: c = CrashReport(type, value, tb) c.show_all() gtk.main() gtk.gdk.threads_leave() gtk.main_quit()
def run(): if os.name == "posix": signal.signal(signal.SIGHUP, safe_shutdown) signal.signal(signal.SIGTERM, safe_shutdown) signal.signal(signal.SIGINT, safe_shutdown) DEVELOPMENT = os.environ.get(APP_NAME.upper() + "_DEVELOPMENT", False) if not DEVELOPMENT: install_excepthook() zenmapCore.I18N.install_gettext(Path.locale_dir) try: # Create the ~/.zenmap directory by copying from the system-wide # template directory. zenmapCore.Paths.create_user_config_dir(Path.user_config_dir, Path.config_dir) except (IOError, OSError), e: error_dialog = HIGAlertDialog(message_format = _("Error creating the per-user configuration directory"), secondary_text = _("""\ There was an error creating the directory %s or one of the files in it. \ The directory is created by copying the contents of %s. \ The specific error was\n\ \n\ %s\n\ \n\ %s needs to create this directory to store information such as the list of \ scan profiles. Check for access to the directory and try again.\ """) % (repr(Path.user_config_dir), repr(Path.config_dir), repr(str(e)), APP_DISPLAY_NAME)) error_dialog.run() error_dialog.destroy() sys.exit(1)
def _save(self, scan_interface, saved_filename, selected_index, format="xml"): """Saves the scan into a file with a given filename. Displays an alert dialog if the save fails.""" log.debug(">>> File being saved: %s" % saved_filename) try: scan_interface.inventory.save_to_file( saved_filename, selected_index, format) scan_interface.inventory.get_scans()[selected_index].unsaved = False # noqa except (OSError, IOError) as e: alert = HIGAlertDialog( message_format=_("Can't save file"), secondary_text=_("Can't open file to write.\n%s") % str(e)) alert.run() alert.destroy() else: scan_interface.saved_filename = saved_filename log.debug(">>> Changes on page? %s" % scan_interface.changed) log.debug(">>> File saved at: %s" % scan_interface.saved_filename) if format == "xml": # Saving recent scan information try: recent_scans.add_recent_scan(saved_filename) recent_scans.save() except (OSError, IOError) as e: alert = HIGAlertDialog( message_format=_( "Can't save recent scan information"), secondary_text=_( "Can't open file to write.\n%s") % str(e)) alert.run() alert.destroy()
def refresh_diff(self, widget): """This method is called whenever the diff output might have changed, such as when a different scan was selected in one of the choosers.""" log.debug("Refresh diff.") if (self.ndiff_process is not None and self.ndiff_process.poll() is None): # Put this in the list of old processes we keep track of. self.old_processes.append(self.ndiff_process) self.ndiff_process = None scan_a = self.scan_chooser_a.parsed_scan scan_b = self.scan_chooser_b.parsed_scan if scan_a is None or scan_b is None: self.diff_view.clear() else: try: self.ndiff_process = zenmapCore.Diff.ndiff(scan_a, scan_b) except OSError as e: alert = HIGAlertDialog( message_format=_("Error running ndiff"), secondary_text=_( "There was an error running the ndiff program.\n\n") + str(e).decode(sys.getdefaultencoding(), "replace")) alert.run() alert.destroy() else: self.progress.show() if self.timer_id is None: self.timer_id = gobject.timeout_add( NDIFF_CHECK_TIMEOUT, self.check_ndiff_process)
def send_report(self, widget): bug_register = BugRegister() description_text = self.description private = False if self.email != "": description_text += "\n\n" + self.email private = True report_url = bug_register.get_report_url(self.summary, description_text, private = private) # First we try reporting the bug with a web browser because that gives # better feedback on what happened. If that doesn't work try with # urllib2. try: webbrowser.open(report_url) except webbrowser.Error: try: urllib2.urlopen(report_url) ok_dialog = HIGAlertDialog(type=gtk.MESSAGE_INFO, message_format=_("Bug reported"), secondary_text=_("The bug was successfully reported.")) ok_dialog.run() ok_dialog.destroy() except urllib2.URLError, e: cancel_dialog = HIGAlertDialog(type=gtk.MESSAGE_ERROR, message_format=_("Bug not reported"), secondary_text=_("This error occurred while trying to report the bug:\n\n" + str(e))) cancel_dialog.run() cancel_dialog.destroy()
def _save_to_directory_cb(self, widget): if self.scan_interface.empty: alert = HIGAlertDialog(message_format=_('Nothing to save'), secondary_text=_('\ This scan has not been run yet. Start the scan with the "Scan" button first.')) alert.run() alert.destroy() return num_scans_running = self.scan_interface.num_scans_running() if num_scans_running > 0: if num_scans_running == 1: text = _("There is a scan still running. " "Wait until it finishes and then save.") else: text = _("There are %u scans still running. Wait until they " "finish and then save.") % num_scans_running alert = HIGAlertDialog(message_format=_('Scan is running'), secondary_text=text) alert.run() alert.destroy() return # We have multiple scans in our network inventory, so we need to # display a directory chooser dialog dir_chooser = SaveToDirectoryChooserDialog( title=_("Choose a directory to save scans into")) if dir_chooser.run() == gtk.RESPONSE_OK: self._save_all(self.scan_interface, dir_chooser.get_filename()) dir_chooser.destroy()
def _save_all(self, scan_interface, directory): """Saves all scans in saving_page's inventory to a given directory. Displays an alert dialog if the save fails.""" try: filenames = scan_interface.inventory.save_to_dir(directory) for scan in scan_interface.inventory.get_scans(): scan.unsaved = False except Exception as ex: alert = HIGAlertDialog(message_format=_('Can\'t save file'), secondary_text=str(ex)) alert.run() alert.destroy() else: scan_interface.saved_filename = directory # Saving recent scan information try: for filename in filenames: recent_scans.add_recent_scan(filename) recent_scans.save() except (OSError, IOError) as e: alert = HIGAlertDialog( message_format=_( "Can't save recent scan information"), secondary_text=_( "Can't open file to write.\n%s") % str(e)) alert.run() alert.destroy()
def open_file(self, widget): file_chooser = ResultsFileSingleChooserDialog(_("Select Scan Result")) response = file_chooser.run() file_chosen = file_chooser.get_filename() file_chooser.destroy() if response == gtk.RESPONSE_OK: try: parser = NmapParser() parser.parse_file(file_chosen) except xml.sax.SAXParseException as e: alert = HIGAlertDialog( message_format='<b>%s</b>' % _('Error parsing file'), secondary_text=_( "The file is not an Nmap XML output file. " "The parsing error that occurred was\n%s") % str(e)) alert.run() alert.destroy() return False except Exception as e: alert = HIGAlertDialog(message_format='<b>%s</b>' % _('Cannot open selected file'), secondary_text=_("""\ This error occurred while trying to open the file: %s""") % str(e)) alert.run() alert.destroy() return False scan_name = os.path.split(file_chosen)[-1] self.add_scan(scan_name, parser) self.combo_scan.set_active(len(self.list_scan) - 1)
def excepthook(type, value, tb): import traceback traceback.print_exception(type, value, tb) # Cause an exception if PyGTK can't open a display. Normally this just # produces a warning, but the lack of a display eventually causes a # segmentation fault. See http://live.gnome.org/PyGTK/WhatsNew210. warnings.filterwarnings("error", module="gtk") import gtk warnings.resetwarnings() gtk.gdk.threads_enter() from zenmapGUI.higwidgets.higdialogs import HIGAlertDialog from zenmapGUI.CrashReport import CrashReport if type == ImportError: d = HIGAlertDialog( type=gtk.MESSAGE_ERROR, message_format=_("Import error"), secondary_text=_("""A required module was not found. """ + unicode(value))) d.run() d.destroy() else: c = CrashReport(type, value, tb) c.show_all() gtk.main() gtk.gdk.threads_leave() gtk.main_quit()
def open_file(self, widget): file_chooser = ResultsFileSingleChooserDialog(_("Select Scan Result")) response = file_chooser.run() file_chosen = file_chooser.get_filename() file_chooser.destroy() if response == gtk.RESPONSE_OK: try: parser = NmapParser() parser.parse_file(file_chosen) except xml.sax.SAXParseException, e: alert = HIGAlertDialog( message_format='<b>%s</b>' % _('Error parsing file'), secondary_text=_( "The file is not an Nmap XML output file. " "The parsing error that occurred was\n%s") % str(e)) alert.run() alert.destroy() return False except Exception, e: alert = HIGAlertDialog( message_format='<b>%s</b>' % _( 'Cannot open selected file'), secondary_text=_("""\ This error occurred while trying to open the file: %s""") % str(e)) alert.run() alert.destroy() return False
def refresh_diff(self, widget): """This method is called whenever the diff output might have changed, such as when a different scan was selected in one of the choosers.""" log.debug("Refresh diff.") if (self.ndiff_process is not None and self.ndiff_process.poll() is None): # Put this in the list of old processes we keep track of. self.old_processes.append(self.ndiff_process) self.ndiff_process = None scan_a = self.scan_chooser_a.parsed_scan scan_b = self.scan_chooser_b.parsed_scan if scan_a is None or scan_b is None: self.diff_view.clear() else: try: self.ndiff_process = zenmapCore.Diff.ndiff(scan_a, scan_b) except OSError, e: alert = HIGAlertDialog( message_format=_("Error running ndiff"), secondary_text=_( "There was an error running the ndiff program.\n\n" ) + str(e).decode(sys.getdefaultencoding(), "replace")) alert.run() alert.destroy() else:
def profile_not_found_dialog(self): warn_dialog = HIGAlertDialog(message_format=_("Profile not found"), secondary_text=_("The profile name you \ selected/typed couldn't be found, and probably doesn't exist. Please, check the profile \ name and try again."), type=gtk.MESSAGE_QUESTION) warn_dialog.run() warn_dialog.destroy()
def check_ndiff_process(self): """Check if the ndiff subprocess is done and show the diff if it is. Also remove any finished processes from the old process list.""" # Check if any old background processes have finished. for p in self.old_processes[:]: if p.poll() is not None: p.close() self.old_processes.remove(p) if self.ndiff_process is not None: # We're running the most recent scan. Check if it's done. status = self.ndiff_process.poll() if status is None: # Keep calling this function on a timer until the process # finishes. self.progress.pulse() return True if status == 0 or status == 1: # Successful completion. try: diff = self.ndiff_process.get_scan_diff() except zenmapCore.Diff.NdiffParseException as e: alert = HIGAlertDialog( message_format=_("Error parsing ndiff output"), secondary_text=str(e)) alert.run() alert.destroy() else: self.diff_view.show_diff(diff) else: # Unsuccessful completion. error_text = _( "The ndiff process terminated with status code %d." ) % status stderr = self.ndiff_process.stderr.read() if len(stderr) > 0: error_text += "\n\n" + stderr alert = HIGAlertDialog( message_format=_("Error running ndiff"), secondary_text=error_text) alert.run() alert.destroy() self.progress.hide() self.ndiff_process.close() self.ndiff_process = None if len(self.old_processes) > 0: # Keep calling this callback. return True else: # All done. self.timer_id = None return False
def store_result(self, scan_interface): """Stores the network inventory into the database.""" log.debug(">>> Saving result into database...") try: scan_interface.inventory.save_to_db() except Exception as e: alert = HIGAlertDialog( message_format=_("Can't save to database"), secondary_text=_("Can't store unsaved scans to the " "recent scans database:\n%s") % str(e)) alert.run() alert.destroy() log.debug(">>> Can't save result to database: %s." % str(e))
def execute_command(self, command, target=None, profile=None): """Run the given Nmap command. Add it to the list of running scans. Schedule a timer to refresh the output and check the scan for completion.""" try: command_execution = NmapCommand(command) except IOError, e: warn_dialog = HIGAlertDialog( message_format=_("Error building command"), secondary_text=_("Error message: %s") % str(e), type=gtk.MESSAGE_ERROR) warn_dialog.run() warn_dialog.destroy() return
def open_browser(self, widget): text1 = self.scan_chooser1.nmap_output text2 = self.scan_chooser2.nmap_output if text1 is None or text2 is None: alert = HIGAlertDialog( message_format='<b>'+_('Select Scan')+'</b>', secondary_text=_("You must select two different scans to \ generate diff.")) alert.run() alert.destroy() return False if text1 == '' and text2 == '': alert = HIGAlertDialog( message_format='<b>'+_('No Text Output')+'</b>', secondary_text=_("Neither of the scans you selected has \ any text output. (Scans loaded from plain Nmap XML output files do not contain \ text output.) The HTML diff shows only differences between text output, so \ there is nothing to show.")) alert.run() alert.destroy() return False # True tells splitlines to keep line endings. text1 = text1.splitlines(True) text2 = text2.splitlines(True) if self.temp_html_file is not None: self.temp_html_file.close() # A NamedTemporaryFile is deleted when it is closed. self.temp_html_file = tempfile.NamedTemporaryFile(suffix = ".html", prefix = "zenmap-diff-") if use_html: diff = DiffHtml(text1, text2) diff = diff.generate() self.temp_html_file.write(''.join(diff)) else: diff = Diff(text1, text2) diff = diff.generate () diff.insert(0, '''<pre>(This diff is been shown in pure text \ because you dont have Python 2.4 or higher.)\n''') diff.append('</pre>') self.temp_html_file.writelines(diff) self.temp_html_file.flush() webbrowser.open("file://" + self.temp_html_file.name, autoraise=1)
def save_profile(self, widget): if self.overwrite: self.profile.remove_profile(self.profile_name) profile_name = self.profile_name_entry.get_text() if profile_name == "": alert = HIGAlertDialog( message_format=_("Unnamed profile"), secondary_text=_( "You must provide a name \ for this profile." ), ) alert.run() alert.destroy() self.profile_name_entry.grab_focus() return None command = self.ops.render_string() buf = self.profile_description_text.get_buffer() description = buf.get_text(buf.get_start_iter(), buf.get_end_iter()) try: self.profile.add_profile(profile_name, command=command, description=description) except ValueError: alert = HIGAlertDialog( message_format=_("Disallowed profile name"), secondary_text=_( 'Sorry, the name "%s" \ is not allowed due to technical limitations. (The underlying ConfigParser \ used to store profiles does not allow it.) Choose a different \ name.' % profile_name ), ) alert.run() alert.destroy() return self.scan_interface.toolbar.profile_entry.update() self.destroy()
def execute_command(self, command, target=None, profile=None): """If scan state is alive and user responds OK, stop the currently active scan and allow creation of another, and if user responds Cancel, wait the current scan to finish. Invokes NmapCommand for execution. Verifies if a valid nmap executable exists in PATH, if not, displays error with the offending PATH. Refreshes and changes to nmap output view from given file.""" command_execution = NmapCommand(command) command_execution.target = target command_execution.profile = profile try: command_execution.run_scan() except Exception, e: text = str(e) if type(e) == OSError: # Handle ENOENT specially. if e.errno == errno.ENOENT: # nmap_command_path comes from zenmapCore.NmapCommand. text += "\n\n" + _( "This means that the nmap executable was not found in your system PATH, which is" ) + "\n\n" + os.getenv("PATH", _("<undefined>")) path_env = os.getenv("PATH") if path_env is None: default_paths = [] else: default_paths = path_env.split(os.pathsep) extra_paths = get_extra_executable_search_paths() extra_paths = [ p for p in extra_paths if p not in default_paths ] if len(extra_paths) > 0: if len(extra_paths) == 1: text += "\n\n" + _("plus the extra directory") else: text += "\n\n" + _("plus the extra directories") text += "\n\n" + os.pathsep.join(extra_paths) warn_dialog = HIGAlertDialog( message_format=_("Error executing command"), secondary_text=text, type=gtk.MESSAGE_ERROR) warn_dialog.run() warn_dialog.destroy() return
def show_help(): import six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error import webbrowser new = 0 if sys.hexversion >= 0x2050000: new = 2 doc_path = abspath(join(Path.docs_dir, "help.html")) url = "file:" + six.moves.urllib.request.pathname2url(fs_enc(doc_path)) try: webbrowser.open(url, new=new) except OSError as e: d = HIGAlertDialog(parent=self, message_format=_("Can't find documentation files"), secondary_text=_("""\ There was an error loading the documentation file %s (%s). See the \ online documentation at %s.\ """) % (doc_path, six.text_type(e), APP_DOCUMENTATION_SITE)) d.run() d.destroy()
def save_profile(self, widget): if self.overwrite: self.profile.remove_profile(self.profile_name) profile_name = self.profile_name_entry.get_text() if profile_name == '': alert = HIGAlertDialog( message_format=_('Unnamed profile'), secondary_text=_( 'You must provide a name for this profile.')) alert.run() alert.destroy() self.profile_name_entry.grab_focus() return None command = self.ops.render_string() buf = self.profile_description_text.get_buffer() description = buf.get_text( buf.get_start_iter(), buf.get_end_iter()) try: self.profile.add_profile( profile_name, command=command, description=description) except ValueError: alert = HIGAlertDialog( message_format=_('Disallowed profile name'), secondary_text=_('Sorry, the name "%s" is not allowed due ' 'to technical limitations. (The underlying ' 'ConfigParser used to store profiles does not allow ' 'it.) Choose a different name.' % profile_name)) alert.run() alert.destroy() return self.scan_interface.toolbar.profile_entry.update() self.destroy()
def _load(self, scan_interface, filename=None, parsed_result=None): """Loads the scan from a file or from a parsed result into the given scan interface.""" if not (filename or parsed_result): return None if filename: # Load scan result from file log.debug(">>> Loading file: %s" % filename) try: # Parse result scan_interface.load_from_file(filename) except Exception as e: alert = HIGAlertDialog(message_format=_('Error loading file'), secondary_text=str(e)) alert.run() alert.destroy() return scan_interface.saved_filename = filename elif parsed_result: # Load scan result from parsed object scan_interface.load_from_parsed_result(parsed_result)
def send_report(self, widget): bug_register = BugRegister() report_url = bug_register.get_report_url(self.summary, "%s\n\nEmail: %s" % (self.description, self.email)) # First we try reporting the bug with a web browser because that gives # better feedback on what happened. If that doesn't work try with # urllib2. try: webbrowser.open(report_url) except webbrowser.Error: try: urllib2.urlopen(report_url) ok_dialog = HIGAlertDialog(type=gtk.MESSAGE_INFO, message_format=_("Bug reported"), secondary_text=_("The bug was successfully reported.")) ok_dialog.run() ok_dialog.destroy() except urllib2.URLError, e: cancel_dialog = HIGAlertDialog(type=gtk.MESSAGE_ERROR, message_format=_("Bug not reported"), secondary_text=_("This error occurred while trying to report the bug:\n\n" + str(e))) cancel_dialog.run() cancel_dialog.destroy()
def start_scan_cb(self, widget=None): target = self.toolbar.selected_target command = self.command_toolbar.command profile = self.toolbar.selected_profile log.debug(">>> Start Scan:") log.debug(">>> Target: '%s'" % target) log.debug(">>> Profile: '%s'" % profile) log.debug(">>> Command: '%s'" % command) ##### If target empty, we are not changing the command if target != '': self.toolbar.add_new_target(target) if (command.find("-iR") == -1 and command.find("-iL") == -1): if command.find("<target>") > 0: warn_dialog = HIGAlertDialog( message_format=_("No Target Host"), secondary_text=_("Target specification \ is mandatory. Either by an address in the target input box or through the '-iR' and \ '-iL' nmap options. Aborting scan."), type=gtk.MESSAGE_ERROR) warn_dialog.run() warn_dialog.destroy() return if command != '': self.execute_command(command, target, profile) else: warn_dialog = HIGAlertDialog( message_format=_("Empty Nmap Command"), secondary_text=_("There is no command to \ execute. Maybe the selected/typed profile doesn't exist. Please, check the profile name \ or type the nmap command you would like to execute."), type=gtk.MESSAGE_ERROR) warn_dialog.run() warn_dialog.destroy()
def __save_image_callback(self, widget): """ """ if self.__save_chooser is None: self.__save_chooser = SaveDialog() response = self.__save_chooser.run() if response == gtk.RESPONSE_OK: filename = self.__save_chooser.get_filename() filetype = self.__save_chooser.get_filetype() try: self.radialnet.save_drawing_to_file(filename, filetype) except Exception as e: alert = HIGAlertDialog( parent=self.__save_chooser, type=gtk.MESSAGE_ERROR, message_format=_("Error saving snapshot"), secondary_text=six.text_type(e)) alert.run() alert.destroy() self.__save_chooser.hide()
def excepthook(type, value, tb): import traceback traceback.print_exception(type, value, tb) # Cause an exception if PyGTK can't open a display. Normally this just # produces a warning, but the lack of a display eventually causes a # segmentation fault. See http://live.gnome.org/PyGTK/WhatsNew210. import warnings warnings.filterwarnings("error", module="gtk") import gtk warnings.resetwarnings() gtk.gdk.threads_enter() from zenmapCore.Version import VERSION from zenmapGUI.higwidgets.higdialogs import HIGAlertDialog from zenmapGUI.CrashReport import CrashReport if type == ImportError: d = HIGAlertDialog( type=gtk.MESSAGE_ERROR, message_format=_("Import error"), secondary_text=_( """\ A required module was not found. """ + value.message ), ) d.run() d.destroy() else: hook = "Type: %s\nValue: %s\n" % (type, value) outputs = ( "CRASH REPORTED:\n\ SYS.PLATFORM: %s\n\ OS.NAME: %s\n\ %s Version: %s\n\ TRACEBACK:\n%s" % ( sys.platform, os.name, APP_DISPLAY_NAME, VERSION, "".join(traceback.format_exception(type, value, tb)), ) ) try: c = CrashReport("%s: %s" % (VERSION, value), outputs) c.show_all() gtk.main() except: d = HIGAlertDialog( type=gtk.MESSAGE_ERROR, message_format=_("Bug not reported"), secondary_text=_( """A critical error \ occurred during %s execution, and it was not properly reported to our bug tracker. Please, copy the error message bellow and report it on our bug tracker. The following error message was NOT reported: %s""" ) % (APP_DISPLAY_NAME, outputs), ) d.run() d.destroy() gtk.gdk.threads_leave() gtk.main_quit()
else: default_paths = path_env.split(os.pathsep) extra_paths = get_extra_executable_search_paths() extra_paths = [p for p in extra_paths if ( p not in default_paths)] if len(extra_paths) > 0: if len(extra_paths) == 1: text += "\n\n" + _("plus the extra directory") else: text += "\n\n" + _("plus the extra directories") text += "\n\n" + os.pathsep.join(extra_paths) warn_dialog = HIGAlertDialog( message_format=_("Error executing command"), secondary_text=text, type=gtk.MESSAGE_ERROR) warn_dialog.run() warn_dialog.destroy() return log.debug("Running command: %s" % command_execution.command) self.jobs.append(command_execution) i = self.scans_store.add_running_scan(command_execution) self.scan_result.scan_result_notebook.nmap_output.set_active_iter(i) # When scan starts, change to nmap output view tab and refresh output self.scan_result.change_to_nmap_output_tab() self.scan_result.refresh_nmap_output() # Add a timeout function self.verify_thread_timeout_id = gobject.timeout_add( NMAP_OUTPUT_REFRESH_INTERVAL, self.verify_execution)
# Read the ~/.zenmap/zenmap.conf configuration file. zenmapCore.UmitConf.config_parser.read(Path.user_config_file) except ConfigParser.ParsingError, e: error_dialog = HIGAlertDialog( message_format=_("Error parsing the configuration file"), secondary_text=_("""\ There was an error parsing the configuration file %s. \ The specific error was\n\ \n\ %s\n\ \n\ %s can continue without this file but any information in it will be ignored \ until it is repaired.\ """) % (Path.user_config_file, str(e), APP_DISPLAY_NAME)) error_dialog.run() error_dialog.destroy() # Display a "you're not root" warning if appropriate. if not is_root(): non_root = NonRootWarning() non_root.run() non_root.destroy() # Load files given as command-line arguments. filenames = option_parser.get_open_results() if len(filenames) == 0: # Open up a blank window. window = new_window() window.show_all() else: for filename in filenames:
def _save_scan_results_cb(self, widget): """'Save Scan' callback function. If it's OK to save the scan, it displays a 'Save File' dialog and saves the scan. If not, it displays an appropriate alert dialog.""" num_scans = len(self.scan_interface.inventory.get_scans()) if num_scans == 0: alert = HIGAlertDialog( message_format=_('Nothing to save'), secondary_text=_( 'There are no scans with results to be saved. ' 'Run a scan with the "Scan" button first.')) alert.run() alert.destroy() return num_scans_running = self.scan_interface.num_scans_running() if num_scans_running > 0: if num_scans_running == 1: text = _("There is a scan still running. " "Wait until it finishes and then save.") else: text = _("There are %u scans still running. Wait until they " "finish and then save.") % num_scans_running alert = HIGAlertDialog(message_format=_('Scan is running'), secondary_text=text) alert.run() alert.destroy() return # If there's more than one scan in the inventory, display a warning # dialog saying that only the most recent scan will be saved selected = 0 if num_scans > 1: #text = _("You have %u scans loaded in the current view. " # "Only the most recent scan will be saved." % num_scans) #alert = HIGAlertDialog( # message_format=_("More than one scan loaded"), # secondary_text=text) #alert.run() #alert.destroy() dlg = HIGDialog( title="Choose a scan to save", parent=self, flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) dlg.vbox.pack_start(gtk.Label( "You have %u scans loaded in the current view.\n" "Select the scan which you would like to save." % num_scans), False) scan_combo = gtk.combo_box_new_text() for scan in self.scan_interface.inventory.get_scans(): scan_combo.append_text(scan.nmap_command) scan_combo.set_active(0) dlg.vbox.pack_start(scan_combo, False) dlg.vbox.show_all() if dlg.run() == gtk.RESPONSE_OK: selected = scan_combo.get_active() dlg.destroy() else: dlg.destroy() return # Show the dialog to choose the path to save scan result self._save_results_filechooser_dialog = \ SaveResultsFileChooserDialog(title=_('Save Scan')) # Supply a default file name if this scan was previously saved. if self.scan_interface.saved_filename: self._save_results_filechooser_dialog.set_filename( self.scan_interface.saved_filename) response = self._save_results_filechooser_dialog.run() filename = None if (response == gtk.RESPONSE_OK): filename = self._save_results_filechooser_dialog.get_filename() format = self._save_results_filechooser_dialog.get_format() # add .xml to filename if there is no other extension if filename.find('.') == -1: filename += ".xml" self._save(self.scan_interface, filename, selected, format) self._save_results_filechooser_dialog.destroy() self._save_results_filechooser_dialog = None
# ParsingError can leave some values as lists instead of strings. Just # blow it all away if we have this problem. zenmapCore.UmitConf.config_parser = zenmapCore.UmitConf.config_parser.__class__( ) error_dialog = HIGAlertDialog( message_format=_("Error parsing the configuration file"), secondary_text=_("""\ There was an error parsing the configuration file %s. \ The specific error was %s %s can continue without this file but any information in it will be ignored \ until it is repaired.""") % (Path.user_config_file, str(e), APP_DISPLAY_NAME)) error_dialog.run() error_dialog.destroy() global_config_path = os.path.join(Path.config_dir, APP_NAME + '.conf') repair_dialog = HIGAlertDialog( type=gtk.MESSAGE_QUESTION, message_format=_("Restore default configuration?"), secondary_text=_("""\ To avoid further errors parsing the configuration file %s, \ you can copy the default configuration from %s. Do this now? \ """) % (Path.user_config_file, global_config_path), ) repair_dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) repair_dialog.set_default_response(gtk.RESPONSE_CANCEL) if repair_dialog.run() == gtk.RESPONSE_OK: shutil.copyfile(global_config_path, Path.user_config_file)
try: # Read the ~/.zenmap/zenmap.conf configuration file. zenmapCore.UmitConf.config_parser.read(Path.user_config_file) except ConfigParser.ParsingError, e: error_dialog = HIGAlertDialog(message_format = _("Error parsing the configuration file"), secondary_text = _("""\ There was an error parsing the configuration file %s. \ The specific error was\n\ \n\ %s\n\ \n\ %s can continue without this file but any information in it will be ignored \ until it is repaired.\ """) % (Path.user_config_file, str(e), APP_DISPLAY_NAME)) error_dialog.run() error_dialog.destroy() # Display a "you're not root" warning if appropriate. if not is_root(): non_root = NonRootWarning() non_root.run() non_root.destroy() # Load files given as command-line arguments. filenames = option_parser.get_open_results() if len(filenames) == 0: # Open up a blank window. window = new_window() window.show_all() else: for filename in filenames:
# ParsingError can leave some values as lists instead of strings. Just # blow it all away if we have this problem. zenmapCore.UmitConf.config_parser = zenmapCore.UmitConf.config_parser.__class__() error_dialog = HIGAlertDialog( message_format=_("Error parsing the configuration file"), secondary_text=_("""\ There was an error parsing the configuration file %s. \ The specific error was %s %s can continue without this file but any information in it will be ignored \ until it is repaired.""") % (Path.user_config_file, str(e), APP_DISPLAY_NAME) ) error_dialog.run() error_dialog.destroy() global_config_path = os.path.join(Path.config_dir, APP_NAME + '.conf') repair_dialog = HIGAlertDialog( type=gtk.MESSAGE_QUESTION, message_format=_("Restore default configuration?"), secondary_text=_("""\ To avoid further errors parsing the configuration file %s, \ you can copy the default configuration from %s. Do this now? \ """) % (Path.user_config_file, global_config_path), ) repair_dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) repair_dialog.set_default_response(gtk.RESPONSE_CANCEL) if repair_dialog.run() == gtk.RESPONSE_OK: shutil.copyfile(global_config_path, Path.user_config_file)