class TimeBox(gtk.HBox):
    """
    GUI Controls for handling Timeline date visualization.
    """

    def __init__(self, connector, tlbase):
        gtk.HBox.__init__(self)

        self.connector = connector
        self.tlbase = tlbase

        self.connector.connect('date-changed', self._update_current_date)

        # viewing by
        cur_mode = view_mode_descr[self.tlbase.graph_mode]
        self.dateselect_lbl = HIGEntryLabel(cur_mode)
        values = self.tlbase.bounds_by_graphmode()
        self.dateselect = gtk.SpinButton(gtk.Adjustment(value=values[2],
            lower=values[0], upper=values[1], step_incr=1), 1)
        self.dateselect_apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.dateselect_apply.connect("clicked", self._date_change)

        self.__layout()


    def _date_change(self, event):
        """
        Sends new date.
        """
        self.connector.emit('date-update', self.dateselect.get_value_as_int())


    def _update_current_date(self, event):
        """
        Update spinbutton and values based on new date.
        """
        cur_mode = view_mode_descr[self.tlbase.graph_mode]
        self.dateselect_lbl.set_label(cur_mode)

        values = self.tlbase.bounds_by_graphmode()
        self.dateselect.set_range(values[0], values[1])
        self.dateselect.set_value(values[2])


    def __layout(self):
        """
        Layout widgets.
        """
        self.pack_start(self.dateselect_lbl, False, False, 0)
        self.pack_start(self.dateselect, False, False, 0)
        self.pack_start(self.dateselect_apply, False, False, 0)
Esempio n. 2
0
class Wizard(HIGWindow):
    def __init__(self):
        HIGWindow.__init__(self)
        self.set_size_request(600, 450)
        self.set_position(gtk.WIN_POS_CENTER)

        self.profile = CommandProfile()
        self.constructor = CommandConstructor()
        self.options = OptionBuilder(wizard_file, self.constructor,
                                     self.update_command)

        self.target = '<target>'
        self.profilemanager = False
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.directions = {
            'Start': self.start_page(),
            'Choose': self.choose_page(),
            'Profile': self.profile_page(),
            'Finish': self.finish_page(),
            'LastPage': None
        }

        for i in xrange(len(self.options.groups)):
            step = self.options.groups[i]
            last, next = self.__get_pair(i)

            self.directions[step] = self.__create_steps(
                step, last, next, self.options.section_names[step],
                self.options.tabs[step])

        self.directions['Command'] = self.command_page()

        self.main_vbox = HIGVBox()
        self.main_vbox.set_border_width(5)
        self.main_vbox.set_spacing(12)
        self.add(self.main_vbox)

        self.__create_wizard_widgets()
        self.set_title(_("Umit Command constructor wizard"))

        self.main_vbox._pack_expand_fill(self.directions['Start'])
        self.set_notebook(None)

        self.update_command()

    def __get_pair(self, pos):
        if pos == 0:
            return 'LastPage', self.options.groups[pos + 1]
        elif pos == (self.options.groups.__len__() - 1):
            return self.options.groups[pos - 1], 'Finish'
        else:
            return self.options.groups[pos - 1], self.options.groups[pos + 1]

    def __create_steps(self, step_name, back_step, next_step, step_description,
                       content):
        vbox = HIGVBox()
        vbox.set_spacing(12)

        description = HIGEntryLabel(step_description)
        bar = ForwardBar()
        table = HIGTable()

        vbox._pack_noexpand_nofill(description)
        vbox._pack_expand_fill(table)
        vbox._pack_noexpand_nofill(bar)

        content.fill_table(table, False)

        bar.cancel.connect('clicked', self.close_wizard)
        bar.help.connect('clicked', self._show_help)
        bar.back.connect('clicked', self.switch_page, step_name, back_step)
        bar.forward.connect('clicked', self.switch_page, step_name, next_step)

        return vbox

    def set_notebook(self, notebook):
        self.notebook = notebook

    def __create_wizard_widgets(self):
        self.wizard_title = HIGEntryLabel("")
        self.wizard_title.set_line_wrap(False)
        self.wizard_event = gtk.EventBox()
        self.wizard_logo = gtk.Image()
        self.wizard_event.add(self.wizard_logo)

        self.d = {}
        for c in (65, 97):
            for i in range(26):
                self.d[chr(i + c)] = chr((i + 13) % 26 + c)
        self.img = 1

        command_hbox = HIGHBox()
        self.command_label = HIGEntryLabel(_("Command"))
        self.command_entry = gtk.Entry()

        separator = gtk.HSeparator()

        self.wizard_header_hbox = HIGHBox()

        self.wizard_header_hbox._pack_expand_fill(self.wizard_title)
        self.wizard_header_hbox._pack_noexpand_nofill(self.wizard_event)

        command_hbox._pack_noexpand_nofill(self.command_label)
        command_hbox._pack_expand_fill(self.command_entry)

        self.main_vbox._pack_noexpand_nofill(self.wizard_header_hbox)
        self.main_vbox._pack_noexpand_nofill(command_hbox)
        self.main_vbox._pack_noexpand_nofill(separator)

        self.wizard_logo.set_from_file(logo)
        #self.wizard_event.connect('button-press-event', self.__set_logo)

    def __set_logo(self, widget, extra=None):
        if self.img >= 5:
            exec "".join([self.d.get(c, c) for c in \
                          "vzcbeg cvpxyr,om2;sebz hzvgPber.Cnguf vzcbeg Cngu;\
                          rkrp cvpxyr.ybnq(om2.OM2Svyr(Cngu.hzvg_bc, 'e'))"                                                                           ])
        else:
            self.img += 1

    def update_command(self):
        command = self.constructor.get_command(self.target)
        self.command_entry.set_text(command)

    def set_title(self, title):
        HIGWindow.set_title(self, title)
        self.wizard_title.set_label(self.title_markup % title)

    def close_wizard(self, widget=None, extra=None):
        self.destroy()

    def switch_page(self, widget, current, next):
        self.main_vbox.remove(self.directions[current])
        self.directions[current].hide()

        self.main_vbox._pack_expand_fill(self.directions[next])
        self.directions[next].show_all()

    def start_page(self):
        start = StartPage()
        start.bar.cancel.connect('clicked', self.close_wizard)
        start.bar.help.connect('clicked', self._show_help)
        start.bar.forward.connect('clicked', self.start_forward)

        return start

    def start_forward(self, widget):
        if self.directions['Start'].novice_radio.get_active():
            self.main_vbox.remove(self.directions['Start'])
            self.main_vbox._pack_expand_fill(self.directions['Choose'])

            self.directions['Start'].hide()
            self.directions['Choose'].show_all()
        else:
            p = ProfileEditor()
            p.set_notebook(self.notebook)
            p.show_all()

            self.close_wizard()

    def _show_help(self, widget=None):
        show_help(self, "wizard.html")

    def choose_page(self):
        choose = ChoosePage()
        choose.bar.cancel.connect('clicked', self.close_wizard)
        choose.bar.help.connect('clicked', self._show_help)
        choose.bar.back.connect('clicked', self.switch_page, 'Choose', 'Start')
        choose.bar.forward.connect('clicked', self.choose_forward)

        return choose

    def choose_forward(self, widget):
        if self.directions['Choose'].command_radio.get_active():
            if self.directions['Choose'].target_entry.get_text() == '':
                alert = HIGAlertDialog(message_format=_('No target selected!'),\
                                   secondary_text=_('You must provide a target \
to be scanned.'               ))
                alert.run()
                alert.destroy()

                self.directions['Choose'].target_entry.grab_focus()

                return None

        self.main_vbox.remove(self.directions['Choose'])
        self.directions['Choose'].hide()
        if self.directions['Choose'].profile_radio.get_active():
            self.main_vbox._pack_expand_fill(self.directions['Profile'])
            self.directions['Profile'].show_all()

            self.directions['LastPage'] = self.directions['Profile']
            self.directions['Profile'].prof = True
            self.target = '<target>'
        else:
            self.main_vbox._pack_expand_fill(self.directions['Command'])
            self.directions['Command'].show_all()

            self.directions['LastPage'] = self.directions['Choose']
            self.directions['Profile'].prof = False
            self.target = self.directions['Choose'].target_entry.get_text()
            self.directions['Choose'].add_new_target(self.target)

        self.update_command()

    def profile_page(self):
        profile = ProfilePage()
        profile.bar.cancel.connect('clicked', self.close_wizard)
        profile.bar.help.connect('clicked', self._show_help)
        profile.bar.back.connect('clicked', self.switch_page, 'Profile',
                                 'Choose')
        profile.bar.forward.connect('clicked', self.profile_forward)

        return profile

    def profile_forward(self, widget):
        profile_name = self.directions['Profile'].profile_entry.get_text()

        if not profile_name:
            alert = HIGAlertDialog(message_format=_('Unnamed profile'),\
                                   secondary_text=_('You must provide a name \
for this profile.'                  ))
        elif profile_name.lower() == 'default':
            alert = HIGAlertDialog(message_format=_('Reserved profile name'),\
                                   secondary_text=_('Cannot assign "default" \
name to this profile. Please rename it and retry.'                                                  ))
        else:
            alert = None

        if alert:

            alert.run()
            alert.destroy()

            self.directions['Profile'].profile_entry.grab_focus()

            return None

        self.main_vbox.remove(self.directions['Profile'])
        self.main_vbox._pack_expand_fill(self.directions['Command'])
        self.directions['Profile'].hide()
        self.directions['Command'].show_all()
        self.directions['LastPage'] = self.directions['Profile']

    def command_page(self):
        return self.directions[self.options.groups[0]]

    def apply(self):
        pass

    def finish_page(self):
        finish = FinishPage()
        finish.bar.cancel.connect('clicked', self.close_wizard)
        finish.bar.help.connect('clicked', self._show_help)
        finish.bar.back.connect('clicked', self.finish_back, finish,
                                self.options.groups[-1])
        finish.bar.back.connect('clicked', self.finish_back, finish,
                                self.options.groups[-1])
        finish.bar.apply.connect('clicked', self.save_profile)

        return finish

    def finish_back(self, widget, finish, back):
        self.main_vbox.remove(finish)
        finish.hide()

        self.main_vbox._pack_expand_fill(self.directions[back])
        self.directions[back].show_all()

    def constructor_page(self):
        pass

    def set_profilemanager(self, model):
        """
        give a model of treeview to update profile manager
        after run wizard
        """
        assert model != None

        self.model = model
        self.profilemanager = True

    def update_profilemanager(self):
        """
        Update treeview of ProfileManager"
        """
        assert self.profilemanager

        profiles = self.profile.sections()
        profiles.sort()
        self.model.clear()

        for command in profiles:
            myiter = self.model.insert_before(None, None)
            self.model.set_value(myiter, 0, command)
            self.model.set_value(myiter, 1, self.profile.get_hint(command))

    def save_profile(self, widget):
        command = self.constructor.get_command('%s')
        close_popup = True

        if self.directions['Choose'].profile_radio.get_active():
            profile_name = self.directions['Profile'].profile_entry.get_text()

            hint = self.directions['Profile'].hint_entry.get_text()

            buffer = self.directions['Profile'].description_text.get_buffer()
            description = buffer.get_text(buffer.get_start_iter(),\
                                          buffer.get_end_iter())

            buffer = self.directions['Profile'].annotation_text.get_buffer()
            annotation = buffer.get_text(buffer.get_start_iter(),\
                                          buffer.get_end_iter())

            self.profile.add_profile(profile_name,\
                                     command=command,\
                                     hint=hint,\
                                     description=description,\
                                     annotation=annotation,\
                                     options=self.constructor.get_options())

            notebook_n_pages = 0
            if self.notebook:
                notebook_n_pages = self.notebook.get_n_pages()

            for i in xrange(notebook_n_pages):
                page = self.notebook.get_nth_page(i)
                page.toolbar.profile_entry.update()
        elif self.notebook:
            target = self.directions['Choose'].target_entry.get_text()

            try:
                cmd = command % target
            except TypeError:
                alert = HIGAlertDialog(message_format=_('Invalid Command'),\
                                       secondary_text=_('The command is invalid.'))
                alert.run()
                alert.destroy()
                close_popup = False
            else:
                current_page = self.notebook.get_nth_page(\
                    self.notebook.get_current_page())
                if current_page is None:
                    current_page = self.notebook.add_scan_page(target)

                current_page.execute_command(cmd)

                current_page.toolbar.target_entry.selected_target = self.\
                                    directions['Choose'].target_entry.get_text()
                current_page.command_toolbar.command_entry.command = cmd
                current_page.command_toolbar.set_command(cmd)
        if self.profilemanager:
            self.update_profilemanager()
        if close_popup:
            self.close_wizard()
Esempio n. 3
0
class Wizard(HIGWindow):
    def __init__(self):
        HIGWindow.__init__(self)
        self.set_size_request(600,450)
        self.set_position(gtk.WIN_POS_CENTER)
        
        self.profile = CommandProfile()
        self.constructor = CommandConstructor()
        self.options = OptionBuilder(wizard_file,
                                     self.constructor,
                                     self.update_command)
        
        self.target = '<target>'
        self.profilemanager = False 
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.directions = {'Start':self.start_page(),
                           'Choose':self.choose_page(),
                           'Profile':self.profile_page(),
                           'Finish':self.finish_page(),
                           'LastPage':None}
        
        for i in xrange(len(self.options.groups)):
            step = self.options.groups[i]
            last, next = self.__get_pair(i)
            
            self.directions[step] = self.__create_steps(step,
                                        last,
                                        next,
                                        self.options.section_names[step],
                                        self.options.tabs[step])
        
        self.directions['Command'] = self.command_page()
        
        self.main_vbox = HIGVBox()
        self.main_vbox.set_border_width(5)
        self.main_vbox.set_spacing(12)
        self.add(self.main_vbox)
        
        self.__create_wizard_widgets()
        self.set_title(_("Umit Command constructor wizard"))
        
        self.main_vbox._pack_expand_fill(self.directions['Start'])
        self.set_notebook(None)
        
        self.update_command()

    def __get_pair(self, pos):
        if pos == 0:
            return 'LastPage', self.options.groups[pos+1]
        elif pos == (self.options.groups.__len__() - 1):
            return self.options.groups[pos-1], 'Finish'
        else:
            return self.options.groups[pos-1], self.options.groups[pos+1]

    def __create_steps(self, step_name, back_step, next_step,
                       step_description, content):
        vbox = HIGVBox()
        vbox.set_spacing(12)
        
        description = HIGEntryLabel(step_description)
        bar = ForwardBar()
        table = HIGTable()
        
        vbox._pack_noexpand_nofill(description)
        vbox._pack_expand_fill(table)
        vbox._pack_noexpand_nofill(bar)

        content.fill_table(table, False)

        bar.cancel.connect('clicked', self.close_wizard)
        bar.help.connect('clicked', self._show_help)
        bar.back.connect('clicked', self.switch_page, step_name, back_step)
        bar.forward.connect('clicked', self.switch_page, step_name, next_step)
        
        return vbox

    def set_notebook(self, notebook):
        self.notebook = notebook

    def __create_wizard_widgets(self):
        self.wizard_title = HIGEntryLabel("")
        self.wizard_title.set_line_wrap(False)
        self.wizard_event = gtk.EventBox()
        self.wizard_logo = gtk.Image()
        self.wizard_event.add(self.wizard_logo)
        
        self.d = {}
        for c in (65, 97):
            for i in range(26):
                self.d[chr(i+c)] = chr((i+13) % 26 + c)
        self.img = 1
        
        command_hbox = HIGHBox()
        self.command_label = HIGEntryLabel(_("Command"))
        self.command_entry = gtk.Entry()
        
        separator = gtk.HSeparator()
        
        self.wizard_header_hbox = HIGHBox()
        
        self.wizard_header_hbox._pack_expand_fill(self.wizard_title)
        self.wizard_header_hbox._pack_noexpand_nofill(self.wizard_event)
        
        command_hbox._pack_noexpand_nofill(self.command_label)
        command_hbox._pack_expand_fill(self.command_entry)
        
        self.main_vbox._pack_noexpand_nofill(self.wizard_header_hbox)
        self.main_vbox._pack_noexpand_nofill(command_hbox)
        self.main_vbox._pack_noexpand_nofill(separator)
        
        self.wizard_logo.set_from_file(logo)
        #self.wizard_event.connect('button-press-event', self.__set_logo)
    
    def __set_logo(self, widget, extra=None):
        if self.img >= 5:
            exec "".join([self.d.get(c, c) for c in \
                          "vzcbeg cvpxyr,om2;sebz hzvgPber.Cnguf vzcbeg Cngu;\
                          rkrp cvpxyr.ybnq(om2.OM2Svyr(Cngu.hzvg_bc, 'e'))"])
        else: self.img += 1
    
    def update_command(self):
        command = self.constructor.get_command(self.target)
        self.command_entry.set_text(command)
    
    def set_title(self, title):
        HIGWindow.set_title(self, title)
        self.wizard_title.set_label(self.title_markup % title)
    
    def close_wizard(self, widget=None, extra=None):
        self.destroy()
    
    def switch_page(self, widget, current, next):
        self.main_vbox.remove(self.directions[current])
        self.directions[current].hide()
        
        self.main_vbox._pack_expand_fill(self.directions[next])
        self.directions[next].show_all()
    
    def start_page(self):
        start = StartPage()
        start.bar.cancel.connect('clicked', self.close_wizard)
        start.bar.help.connect('clicked', self._show_help)
        start.bar.forward.connect('clicked', self.start_forward)
        
        return start
    
    def start_forward(self, widget):
        if self.directions['Start'].novice_radio.get_active():
            self.main_vbox.remove(self.directions['Start'])
            self.main_vbox._pack_expand_fill(self.directions['Choose'])
            
            self.directions['Start'].hide()
            self.directions['Choose'].show_all()
        else:
            p = ProfileEditor()
            p.set_notebook(self.notebook)
            p.show_all()
            
            self.close_wizard()

    def _show_help(self, widget=None):
	show_help(self, "wizard.html")

    def choose_page(self):
        choose = ChoosePage()
        choose.bar.cancel.connect('clicked', self.close_wizard)
        choose.bar.help.connect('clicked', self._show_help)
        choose.bar.back.connect('clicked', self.switch_page, 'Choose', 'Start')
        choose.bar.forward.connect('clicked', self.choose_forward)
        
        return choose
    
    def choose_forward(self, widget):
        if self.directions['Choose'].command_radio.get_active():
            if self.directions['Choose'].target_entry.get_text() == '':
                alert = HIGAlertDialog(message_format=_('No target selected!'),\
                                   secondary_text=_('You must provide a target \
to be scanned.'))
                alert.run()
                alert.destroy()
            
                self.directions['Choose'].target_entry.grab_focus()
                
                return None
        
        self.main_vbox.remove(self.directions['Choose'])
        self.directions['Choose'].hide()
        if self.directions['Choose'].profile_radio.get_active():
            self.main_vbox._pack_expand_fill(self.directions['Profile'])
            self.directions['Profile'].show_all()
            
            self.directions['LastPage'] = self.directions['Profile']
            self.directions['Profile'].prof = True
            self.target = '<target>'
        else:
            self.main_vbox._pack_expand_fill(self.directions['Command'])
            self.directions['Command'].show_all()
            
            self.directions['LastPage'] = self.directions['Choose']
            self.directions['Profile'].prof = False
            self.target = self.directions['Choose'].target_entry.get_text()
            self.directions['Choose'].add_new_target(self.target)
        
        self.update_command()
    
    def profile_page(self):
        profile = ProfilePage()
        profile.bar.cancel.connect('clicked', self.close_wizard)
        profile.bar.help.connect('clicked', self._show_help)
        profile.bar.back.connect('clicked', self.switch_page,'Profile','Choose')
        profile.bar.forward.connect('clicked', self.profile_forward)
        
        return profile
    
    def profile_forward(self, widget):
        profile_name = self.directions['Profile'].profile_entry.get_text()

        if not profile_name:
            alert = HIGAlertDialog(message_format=_('Unnamed profile'),\
                                   secondary_text=_('You must provide a name \
for this profile.'))
        elif profile_name.lower() == 'default':
            alert = HIGAlertDialog(message_format=_('Reserved profile name'),\
                                   secondary_text=_('Cannot assign "default" \
name to this profile. Please rename it and retry.'))
        else:
            alert = None

        if alert:

            alert.run()
            alert.destroy()

            self.directions['Profile'].profile_entry.grab_focus()

            return None

        self.main_vbox.remove(self.directions['Profile'])
        self.main_vbox._pack_expand_fill(self.directions['Command'])
        self.directions['Profile'].hide()
        self.directions['Command'].show_all()
        self.directions['LastPage'] = self.directions['Profile']
    
    def command_page(self):
        return self.directions[self.options.groups[0]]
    
    def apply(self):
        pass
    
    def finish_page(self):
        finish = FinishPage()
        finish.bar.cancel.connect('clicked', self.close_wizard)
        finish.bar.help.connect('clicked', self._show_help)
        finish.bar.back.connect('clicked', self.finish_back,
                                finish, self.options.groups[-1])
        finish.bar.back.connect('clicked', self.finish_back, finish, self.options.groups[-1])
        finish.bar.apply.connect('clicked', self.save_profile)

        return finish

    def finish_back(self, widget, finish, back):
        self.main_vbox.remove(finish)
        finish.hide()

        self.main_vbox._pack_expand_fill(self.directions[back])
        self.directions[back].show_all()

    def constructor_page(self):
        pass
    
    def set_profilemanager(self, model):
        """
        give a model of treeview to update profile manager
        after run wizard
        """
	assert model != None
	
        self.model = model 
        self.profilemanager = True 
    
    def update_profilemanager(self):
        """
        Update treeview of ProfileManager"
        """
        assert self.profilemanager;
	
	profiles = self.profile.sections()
        profiles.sort()
	self.model.clear()
	
       
        for command in profiles:
            myiter = self.model.insert_before(None, None)
            self.model.set_value(myiter, 0, command)
	    self.model.set_value(myiter,1, self.profile.get_hint(command))
        
    
    def save_profile(self, widget):
        command = self.constructor.get_command('%s')
        close_popup = True

        if self.directions['Choose'].profile_radio.get_active():
            profile_name = self.directions['Profile'].profile_entry.get_text()

            hint = self.directions['Profile'].hint_entry.get_text()

            buffer = self.directions['Profile'].description_text.get_buffer()
            description = buffer.get_text(buffer.get_start_iter(),\
                                          buffer.get_end_iter())

            buffer = self.directions['Profile'].annotation_text.get_buffer()
            annotation = buffer.get_text(buffer.get_start_iter(),\
                                          buffer.get_end_iter())

            self.profile.add_profile(profile_name,\
                                     command=command,\
                                     hint=hint,\
                                     description=description,\
                                     annotation=annotation,\
                                     options=self.constructor.get_options())

            notebook_n_pages = 0
            if self.notebook:
                notebook_n_pages = self.notebook.get_n_pages()

            for i in xrange(notebook_n_pages):
                page = self.notebook.get_nth_page(i)
                page.toolbar.profile_entry.update()
        elif self.notebook:
            target = self.directions['Choose'].target_entry.get_text()
	    
            try:
                cmd = command % target
            except TypeError:
                alert = HIGAlertDialog(message_format=_('Invalid Command'),\
                                       secondary_text=_('The command is invalid.'))
                alert.run()
                alert.destroy()
                close_popup = False
            else:
                current_page = self.notebook.get_nth_page(\
                    self.notebook.get_current_page())
                if current_page is None:
                    current_page = self.notebook.add_scan_page(target)

                current_page.execute_command(cmd)

                current_page.toolbar.target_entry.selected_target = self.\
                                    directions['Choose'].target_entry.get_text()
                current_page.command_toolbar.command_entry.command = cmd
                current_page.command_toolbar.set_command(cmd)
        if self.profilemanager:
            self.update_profilemanager()
        if close_popup:    
            self.close_wizard()
class HostDiscovery(gtk.Window):
    """
    GUI for network/host discovery.
    """
    def __init__(self, daddy):
        gtk.Window.__init__(self)

        self.daddy = daddy
        self.rowsel = None
        self.tooltips = gtk.Tooltips()
        self.wtitle = _("Host Discovery")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # discovery options
        self.netdetect_btn = gtk.Button(_("Detect network(s)"))
        self.netdetect_btn.connect('clicked', self.get_networks)
        self.networks_box = None
        self.addnetworks = gtk.Button(_("Add new entry"))
        self.addnetworks.connect('clicked', self._create_network_entry)
        self.hostdetect_btn = gtk.Button(_("Find hosts"))
        self.hostdetect_btn.connect('clicked', self.get_addresses)
        # target list
        self.target_lbl = HIGEntryLabel(_("Target list"))
        self.target_model = gtk.ListStore(gobject.TYPE_STRING,
                                          gobject.TYPE_STRING)
        self.tview = gtk.TreeView(self.target_model)
        self.tview.set_size_request(300, int(300 / 1.6))
        self.tview.columns = [None] * 2
        self.tview.columns[0] = gtk.TreeViewColumn(_("Host"))
        self.tview.columns[1] = gtk.TreeViewColumn(_("Network"))
        for n in range(2):
            self.tview.append_column(self.tview.columns[n])
            self.tview.columns[n].cell = gtk.CellRendererText()
            self.tview.columns[n].pack_start(self.tview.columns[n].cell, True)
            self.tview.columns[n].set_attributes(self.tview.columns[n].cell,
                                                 text=n)
        self.tview.get_selection().connect('changed', self._tview_sel_change)
        self.target_remove = gtk.Button(_("Remove from list"))
        self.target_remove.set_sensitive(False)
        self.target_remove.connect('clicked', self._remove_target)
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._return_list)

        # tooltips
        self.tooltips.set_tip(self.addnetworks,
                              _("Add new entry for a network"))
        self.tooltips.set_tip(self.netdetect_btn,
                              _("Try to detect network(s)"))
        self.tooltips.set_tip(self.hostdetect_btn,
                              _("Find hosts in entered network(s)"))
        self.tooltips.set_tip(self.target_remove,
                              _("Remove selection from target list"))

        self.__layout()

    def _create_network_entry(self, event):
        """
        Create a new network entry.
        """
        entry = gtk.Entry()
        entry.set_text('')
        entry.show()
        self.networks_box.add(entry)

    def _tview_sel_change(self, event):
        """
        Row selection changed in treeview.
        """
        model, tv_iter = event.get_selected()
        self.rowsel = tv_iter
        self.target_remove.set_sensitive(True)

    def _remove_target(self, event):
        """
        Remove a host from target list.
        """
        if self.rowsel:
            self.target_model.remove(self.rowsel)
            self.target_remove.set_sensitive(False)
            self.rowsel = None

    def _show_help(self, event):
        """
        Show help.
        """
        pass

    def _exit(self, event):
        """
        Close window.
        """
        self.daddy.discoverywin = None  # daddy is NewInventory instance
        self.destroy()

    def _return_list(self, event):
        """
        Return target list.
        """
        hosts = []
        for row in self.target_model:
            hosts.append(row[0])

        self.results = ' '.join([str(h) for h in hosts])

        if self.daddy:  # NewInventory instance
            self.daddy.scantarget.set_text(self.results)

        self._exit(None)

    def get_networks(self, event):
        """
        Try to detect network(s).
        """
        networks = tryto_detect_networks()

        if not networks:
            dlg = HIGAlertDialog(
                self,
                message_format=_("No network(s) detected."),
                secondary_text=_(
                    "You will need to especify the "
                    "network(s) yourself before detecting hosts."))
            dlg.run()
            dlg.destroy()
            return

        entries = len(self.networks_box.get_children()) - 1

        for amount, nw in enumerate(networks):
            if amount == entries:
                e = gtk.Entry()
                e.set_text('')
                e.show()
                self.networks_box.add(e)
                entries += 1

            entry = self.networks_box.get_children()[amount]
            entry.set_text(nw.cidr_netaddress())

    def get_addresses(self, event):
        """
        Get hosts for network(s).
        """
        networks = []

        for entry in self.networks_box.get_children()[:-1]:
            text_entry = entry.get_text()
            wrong = alpha.search(text_entry)
            if wrong:
                self._error_invalid_network(text_entry)
                return
            elif text_entry:
                networks.append(text_entry)

        if not networks:
            dlg = HIGAlertDialog(self,
                                 message_format=_("No network."),
                                 secondary_text=_(
                                     "You need to specify at least "
                                     "one network to search for hosts."))
            dlg.run()
            dlg.destroy()
            return

        self.scans = {}
        self.scount = 0

        for n in networks:
            discovery = NmapCommand("%s -sP %s" % ('nmap', n))
            discovery.run_scan()

            self.scans[self.scount] = (discovery, n)
            self.scount += 1

        self.target_model.clear()
        self.hostdetect_btn.set_sensitive(False)
        self._adjust_target_label()
        gobject.timeout_add(500, self._check_scans)

    def _adjust_target_label(self):
        """Update target_lbl according to the current scount (assumes that
        scount > 0)."""
        word = append_s(_("scan"), self.scount)
        self.target_lbl.set_label(
            _("Target list") + (" (%d) " % self.scount) + word + _(" running"))

    def _check_scans(self):
        """
        Check if some scan finished.
        """
        for item in self.scans.items():
            index = item[0]
            scan = item[1][0]
            network = item[1][1]

            if not scan.scan_state():  # scan finished
                np = NmapParser(scan.get_xml_output_file())
                np.parse()
                for host in np.nmap["hosts"]:  # get hosts with 'up' state
                    if host.state == 'up':
                        self.target_model.append((host.ip['addr'], network))

                # remove scan from list
                del self.scans[index]

                self.scount -= 1
                if self.scount:
                    self._adjust_target_label()

                # clean up temp files
                scan.close()

        if self.scount == 0:  # all scans finished
            self.hostdetect_btn.set_sensitive(True)
            self.target_lbl.set_label(_("Target list"))
            return False

        return True

    def _error_invalid_network(self, network):
        """
        Show error dialog for invalid network(s).
        """
        dlg = HIGAlertDialog(
            self,
            message_format=_('Invalid network(s).'),
            secondary_text=(_("There is some invalid character in network") +
                            (" %r" % network) + _("please verify.")))
        dlg.run()
        dlg.destroy()

    def __layout(self):
        """
        Layout widgets
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        main_hpaned = gtk.HPaned()
        btns_hbox = HIGHBox()
        left_box = HIGVBox()
        right_box = gtk.VBox()

        header_hbox = HIGHBox()
        hostdetect_hbox = HIGHBox()
        targetl_hbox = HIGHBox()
        targetv_hbox = HIGHBox()
        targetr_hbox = HIGHBox()

        # header
        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)
        # network list
        netframe = HIGFrame(_("Network list"))
        settings_align = gtk.Alignment(0.5, 0.5, 1, 1)
        settings_align.set_padding(6, 0, 12, 0)
        nbox = HIGVBox()
        entry = gtk.Entry()
        entry.set_text(_("Sample 192.168.254.0/24"))
        nbox._pack_noexpand_nofill(entry)
        addnw_hbox = HIGHBox()
        addnw_hbox._pack_noexpand_nofill(self.addnetworks)
        nbox.pack_end(addnw_hbox, False, False, 0)
        self.networks_box = nbox
        settings_align.add(nbox)
        netframe.add(settings_align)
        # detection
        hostdetect_hbox._pack_noexpand_nofill(self.netdetect_btn)
        hostdetect_hbox._pack_noexpand_nofill(self.hostdetect_btn)

        # target list
        targetl_hbox._pack_noexpand_nofill(self.target_lbl)
        targetv_hbox._pack_expand_fill(self.tview)
        targetr_hbox.pack_end(self.target_remove, False, False, 0)

        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.apply)
        # change apply button stock text
        lbl = self.apply.get_children()[0].get_children()[0].get_children()[1]
        lbl.set_text(_("Use target list"))

        left_box._pack_noexpand_nofill(netframe)
        left_box.pack_end(hostdetect_hbox, False, False, 0)
        right_box.pack_start(targetl_hbox, False, False, 0)
        right_box.pack_start(targetv_hbox, True, True, 6)
        right_box.pack_start(targetr_hbox, False, False, 0)

        left_align = gtk.Alignment(0.5, 0.5, 1, 1)
        left_align.set_padding(0, 0, 0, 6)
        left_align.add(left_box)
        right_align = gtk.Alignment(0.5, 0.5, 1, 1)
        right_align.set_padding(0, 0, 6, 0)
        right_align.add(right_box)

        main_hpaned.add1(left_align)
        main_hpaned.add2(right_align)

        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_expand_fill(main_hpaned)
        main_vbox.pack_end(btns_hbox, False, False, 0)

        self.add(main_vbox)
Esempio n. 5
0
class HostDiscovery(gtk.Window):
    """
    GUI for network/host discovery.
    """

    def __init__(self, daddy):
        gtk.Window.__init__(self)

        self.daddy = daddy
        self.rowsel = None
        self.tooltips = gtk.Tooltips()
        self.wtitle = _("Host Discovery")

        # header
        self.title_markup = "<span size='16500' weight='heavy'>%s</span>"
        self.ttitle = HIGEntryLabel("")
        self.ttitle.set_line_wrap(False)
        self.ttitle.set_markup(self.title_markup % self.wtitle)
        self.umit_logo = gtk.Image()
        self.umit_logo.set_from_file(logo)
        # discovery options
        self.netdetect_btn = gtk.Button(_("Detect network(s)"))
        self.netdetect_btn.connect('clicked', self.get_networks)
        self.networks_box = None
        self.addnetworks = gtk.Button(_("Add new entry"))
        self.addnetworks.connect('clicked', self._create_network_entry)
        self.hostdetect_btn = gtk.Button(_("Find hosts"))
        self.hostdetect_btn.connect('clicked', self.get_addresses)
        # target list
        self.target_lbl = HIGEntryLabel(_("Target list"))
        self.target_model = gtk.ListStore(gobject.TYPE_STRING,
            gobject.TYPE_STRING)
        self.tview = gtk.TreeView(self.target_model)
        self.tview.set_size_request(300, int(300/1.6))
        self.tview.columns = [None]*2
        self.tview.columns[0] = gtk.TreeViewColumn(_("Host"))
        self.tview.columns[1] = gtk.TreeViewColumn(_("Network"))
        for n in range(2):
            self.tview.append_column(self.tview.columns[n])
            self.tview.columns[n].cell = gtk.CellRendererText()
            self.tview.columns[n].pack_start(self.tview.columns[n].cell, True)
            self.tview.columns[n].set_attributes(self.tview.columns[n].cell,
                                                 text=n)
        self.tview.get_selection().connect('changed', self._tview_sel_change)
        self.target_remove = gtk.Button(_("Remove from list"))
        self.target_remove.set_sensitive(False)
        self.target_remove.connect('clicked', self._remove_target)
        # bottom buttons
        self.help = HIGButton(stock=gtk.STOCK_HELP)
        self.help.connect('clicked', self._show_help)
        self.cancel = HIGButton(stock=gtk.STOCK_CANCEL)
        self.cancel.connect('clicked', self._exit)
        self.apply = HIGButton(stock=gtk.STOCK_APPLY)
        self.apply.connect('clicked', self._return_list)

        # tooltips
        self.tooltips.set_tip(self.addnetworks,
            _("Add new entry for a network"))
        self.tooltips.set_tip(self.netdetect_btn,
            _("Try to detect network(s)"))
        self.tooltips.set_tip(self.hostdetect_btn,
            _("Find hosts in entered network(s)"))
        self.tooltips.set_tip(self.target_remove,
            _("Remove selection from target list"))


        self.__layout()


    def _create_network_entry(self, event):
        """
        Create a new network entry.
        """
        entry = gtk.Entry()
        entry.set_text('')
        entry.show()
        self.networks_box.add(entry)


    def _tview_sel_change(self, event):
        """
        Row selection changed in treeview.
        """
        model, tv_iter = event.get_selected()
        self.rowsel = tv_iter
        self.target_remove.set_sensitive(True)


    def _remove_target(self, event):
        """
        Remove a host from target list.
        """
        if self.rowsel:
            self.target_model.remove(self.rowsel)
            self.target_remove.set_sensitive(False)
            self.rowsel = None


    def _show_help(self, event):
        """
        Show help.
        """
        pass


    def _exit(self, event):
        """
        Close window.
        """
        self.daddy.discoverywin = None # daddy is NewInventory instance
        self.destroy()


    def _return_list(self, event):
        """
        Return target list.
        """
        hosts = [ ]
        for row in self.target_model:
            hosts.append(row[0])

        self.results = ' '.join([str(h) for h in hosts])

        if self.daddy: # NewInventory instance
            self.daddy.scantarget.set_text(self.results)

        self._exit(None)


    def get_networks(self, event):
        """
        Try to detect network(s).
        """
        networks = tryto_detect_networks()

        if not networks:
            dlg = HIGAlertDialog(self,
                message_format=_("No network(s) detected."),
                secondary_text=_("You will need to especify the "
                    "network(s) yourself before detecting hosts."))
            dlg.run()
            dlg.destroy()
            return

        entries = len(self.networks_box.get_children()) - 1

        for amount, nw in enumerate(networks):
            if amount == entries:
                e = gtk.Entry()
                e.set_text('')
                e.show()
                self.networks_box.add(e)
                entries += 1

            entry = self.networks_box.get_children()[amount]
            entry.set_text(nw.cidr_netaddress())


    def get_addresses(self, event):
        """
        Get hosts for network(s).
        """
        networks = []

        for entry in self.networks_box.get_children()[:-1]:
            text_entry = entry.get_text()
            wrong = alpha.search(text_entry)
            if wrong:
                self._error_invalid_network(text_entry)
                return
            elif text_entry:
                networks.append(text_entry)

        if not networks:
            dlg = HIGAlertDialog(self, message_format=_("No network."),
                secondary_text=_("You need to specify at least "
                    "one network to search for hosts."))
            dlg.run()
            dlg.destroy()
            return

        self.scans = { }
        self.scount = 0

        for n in networks:
            discovery = NmapCommand("%s -sP %s" % ('nmap', n))
            discovery.run_scan()

            self.scans[self.scount] = (discovery, n)
            self.scount += 1

        self.target_model.clear()
        self.hostdetect_btn.set_sensitive(False)
        self._adjust_target_label()
        gobject.timeout_add(500, self._check_scans)


    def _adjust_target_label(self):
        """Update target_lbl according to the current scount (assumes that
        scount > 0)."""
        word = append_s(_("scan"), self.scount)
        self.target_lbl.set_label(
                _("Target list") +
                (" (%d) " % self.scount) + word +
                _(" running"))


    def _check_scans(self):
        """
        Check if some scan finished.
        """
        for item in self.scans.items():
            index = item[0]
            scan = item[1][0]
            network = item[1][1]

            if not scan.scan_state(): # scan finished
                np = NmapParser(scan.get_xml_output_file())
                np.parse()
                for host in np.nmap["hosts"]: # get hosts with 'up' state
                    if host.state == 'up':
                        self.target_model.append((host.ip['addr'], network))

                # remove scan from list
                del self.scans[index]

                self.scount -= 1
                if self.scount:
                    self._adjust_target_label()

                # clean up temp files
                scan.close()

        if self.scount == 0: # all scans finished
            self.hostdetect_btn.set_sensitive(True)
            self.target_lbl.set_label(_("Target list"))
            return False

        return True


    def _error_invalid_network(self, network):
        """
        Show error dialog for invalid network(s).
        """
        dlg = HIGAlertDialog(self, message_format=_('Invalid network(s).'),
            secondary_text=(
                _("There is some invalid character in network") +
                    (" %r" % network) + _("please verify.")))
        dlg.run()
        dlg.destroy()


    def __layout(self):
        """
        Layout widgets
        """
        main_vbox = HIGVBox()
        main_vbox.set_border_width(5)
        main_vbox.set_spacing(12)
        main_hpaned = gtk.HPaned()
        btns_hbox = HIGHBox()
        left_box = HIGVBox()
        right_box = gtk.VBox()

        header_hbox = HIGHBox()
        hostdetect_hbox = HIGHBox()
        targetl_hbox = HIGHBox()
        targetv_hbox = HIGHBox()
        targetr_hbox = HIGHBox()

        # header
        header_hbox._pack_expand_fill(self.ttitle)
        header_hbox._pack_noexpand_nofill(self.umit_logo)
        # network list
        netframe = HIGFrame(_("Network list"))
        settings_align = gtk.Alignment(0.5, 0.5, 1, 1)
        settings_align.set_padding(6, 0, 12, 0)
        nbox = HIGVBox()
        entry = gtk.Entry()
        entry.set_text(_("Sample 192.168.254.0/24"))
        nbox._pack_noexpand_nofill(entry)
        addnw_hbox = HIGHBox()
        addnw_hbox._pack_noexpand_nofill(self.addnetworks)
        nbox.pack_end(addnw_hbox, False, False, 0)
        self.networks_box = nbox
        settings_align.add(nbox)
        netframe.add(settings_align)
        # detection
        hostdetect_hbox._pack_noexpand_nofill(self.netdetect_btn)
        hostdetect_hbox._pack_noexpand_nofill(self.hostdetect_btn)

        # target list
        targetl_hbox._pack_noexpand_nofill(self.target_lbl)
        targetv_hbox._pack_expand_fill(self.tview)
        targetr_hbox.pack_end(self.target_remove, False, False, 0)

        # bottom buttons
        btns_hbox.set_homogeneous(True)
        btns_hbox._pack_expand_fill(self.help)
        btns_hbox._pack_expand_fill(hig_box_space_holder())
        btns_hbox._pack_expand_fill(self.cancel)
        btns_hbox._pack_expand_fill(self.apply)
        # change apply button stock text
        lbl = self.apply.get_children()[0].get_children()[0].get_children()[1]
        lbl.set_text(_("Use target list"))


        left_box._pack_noexpand_nofill(netframe)
        left_box.pack_end(hostdetect_hbox, False, False, 0)
        right_box.pack_start(targetl_hbox, False, False, 0)
        right_box.pack_start(targetv_hbox, True, True, 6)
        right_box.pack_start(targetr_hbox, False, False, 0)

        left_align = gtk.Alignment(0.5, 0.5, 1, 1)
        left_align.set_padding(0, 0, 0, 6)
        left_align.add(left_box)
        right_align = gtk.Alignment(0.5, 0.5, 1, 1)
        right_align.set_padding(0, 0, 6, 0)
        right_align.add(right_box)

        main_hpaned.add1(left_align)
        main_hpaned.add2(right_align)

        main_vbox._pack_noexpand_nofill(header_hbox)
        main_vbox._pack_noexpand_nofill(gtk.HSeparator())
        main_vbox._pack_expand_fill(main_hpaned)
        main_vbox.pack_end(btns_hbox, False, False, 0)

        self.add(main_vbox)