Python gi.repository.GLib.Error() Examples

The following are 30 code examples of gi.repository.GLib.Error(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gi.repository.GLib , or try the search function .
Example #1
Source File: util.py    From python-eduvpn-client with GNU General Public License v3.0 6 votes vote down vote up
def bytes2pixbuf(data,
                 width=icon_size['width'],
                 height=icon_size['height'],
                 display_name=None):  # type: (bytes, int, int, Optional[str]) -> GdkPixbuf.Pixbuf
    """
    converts raw bytes into a GTK PixBug

    args:
        data (bytes): raw bytes
        width (int): width of image
        height (int): height of images

    returns:
        GtkPixbuf: a GTK Pixbuf

    """
    loader = GdkPixbuf.PixbufLoader()
    loader.set_size(width, height)
    try:
        loader.write(data)
        loader.close()
    except (GLib.Error, TypeError) as e:
        logger.error(u"can't process icon for {}: {}".format(display_name, str(e)))
    else:
        return loader.get_pixbuf() 
Example #2
Source File: sniffer.py    From btle-sniffer with MIT License 6 votes vote down vote up
def _connect(self, device):
        def cb_connect():
            try:
                bus = pydbus.SystemBus()
                proxy = bus.get(SERVICE_NAME, device.path)
                proxy.Connect()
            except KeyError:
                self._log.debug("The device has likely disappeared.", exc_info=True)
            except GLib.Error:
                self._log.debug("Connect() failed:", exc_info=True)
            else:
                self._log.info("Connection successful.")

            self.queued_connections -= 1

        if self.queued_connections == 0:
            print_device(device, "Connecting")
            GLib.idle_add(cb_connect)
            device.connected = True
            self.queued_connections += 1 
Example #3
Source File: preview.py    From oomox with GNU General Public License v3.0 6 votes vote down vote up
def get_theme_css_provider(self, theme_plugin):
        css_dir = theme_plugin.gtk_preview_dir

        css_name = "theme{}.css".format(
            '20' if Gtk.get_minor_version() >= 20 else ''
        )
        css_path = os.path.join(css_dir, css_name)
        if not os.path.exists(css_path):
            css_path = os.path.join(css_dir, "theme.css")

        css_provider = self.css_providers.theme.get(css_path)
        if css_provider:
            return css_provider
        css_provider = Gtk.CssProvider()
        try:
            css_provider.load_from_path(css_path)
        except GLib.Error as exc:  # pylint: disable=catching-non-exception
            print(exc)
        self.css_providers.theme[css_path] = css_provider
        return css_provider 
Example #4
Source File: iddialog.py    From syncthing-gtk with GNU General Public License v2.0 6 votes vote down vote up
def cb_syncthing_qr(self, io, results, *a):
		"""
		Called when QR code is loaded or operation fails. Image is then
		displayed in dialog, failure is silently ignored.
		"""
		try:
			ok, contents, etag = io.load_contents_finish(results)
			if ok:
				# QR is loaded, save it to temp file and let GTK to handle
				# rest
				tf = tempfile.NamedTemporaryFile("wb", suffix=".png", delete=False)
				tf.write(contents)
				tf.close()
				self["vQR"].set_from_file(tf.name)
				os.unlink(tf.name)
		except GLib.Error as e:
			if e.code in [14, 15]:
				# Unauthorized. Grab CSRF token from daemon and try again
				log.warning("Failed to load image using glib. Retrying with urllib2.")
				self.load_data_urllib()
		except Exception as e:
			log.exception(e)
			return
		finally:
			del io 
Example #5
Source File: panctl.py    From pantalaimon with Apache License 2.0 6 votes vote down vote up
def main():
    loop = asyncio.get_event_loop()
    glib_loop = GLib.MainLoop()

    try:
        panctl = PanCtl()
    except GLib.Error as e:
        print(f"Error, {e}")
        sys.exit(-1)

    fut = loop.run_in_executor(None, glib_loop.run)

    try:
        loop.run_until_complete(panctl.loop())
    except KeyboardInterrupt:
        pass

    GLib.idle_add(glib_loop.quit)
    loop.run_until_complete(fut) 
Example #6
Source File: notifications.py    From epoptes with GNU General Public License v3.0 6 votes vote down vote up
def show(self):
        """Create, update, or re-create the notification, and show it."""
        if self.notification is None:
            self.notification = self.new_notification(
                self.summary, self.to_string(), self.icon)
        elif not self.notification.update(
                self.summary, self.to_string(), self.icon):
            self.notification = self.new_notification(
                self.summary, self.to_string(), self.icon)
        try:
            self.notification.show()
        # pylint: disable=catching-non-exception
        except GLib.Error as exc:
            # If a notification daemon isn't running, show an error once
            if not self.shown_error:
                self.shown_error = True
                LOG.e("Error while showing notification, is a daemon running?",
                      "\n", str(exc)) 
Example #7
Source File: application.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def load_style_css(self, css_file):
		self.logger.debug('loading style from css file: ' + css_file)
		css_file = Gio.File.new_for_path(css_file)
		style_provider = Gtk.CssProvider()
		style_provider.connect('parsing-error', self.signal_css_provider_parsing_error)
		try:
			style_provider.load_from_file(css_file)
		except GLib.Error:  # pylint: disable=catching-non-exception
			self.logger.error('there was an error parsing the css file, it will not be applied as a style provider')
			return None
		Gtk.StyleContext.add_provider_for_screen(
			Gdk.Screen.get_default(),
			style_provider,
			Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
		)
		return style_provider 
Example #8
Source File: utils.py    From Authenticator with GNU General Public License v2.0 6 votes vote down vote up
def load_pixbuf(icon_name, size):
    pixbuf = None
    theme = Gtk.IconTheme.get_default()
    if icon_name:
        try:
            icon_info = theme.lookup_icon(icon_name, size, 0)
            if icon_info:
                pixbuf = icon_info.load_icon()
        except GLib.Error:
            pass
    if not pixbuf:
        pixbuf = theme.load_icon("com.github.bilelmoussaoui.Authenticator",
                                 size, 0)

    if pixbuf and (pixbuf.props.width != size or pixbuf.props.height != size):
        pixbuf = pixbuf.scale_simple(size, size,
                                     GdkPixbuf.InterpType.BILINEAR)
    return pixbuf 
Example #9
Source File: sink_manager.py    From gateway with Apache License 2.0 5 votes vote down vote up
def process_scratchpad(self):
        ret = GatewayResultCode.GW_RES_OK
        restart = False
        try:
            # Stop the stack if not already stopped
            if self.proxy.StackStatus == 0:
                self.proxy.SetStackState(False)
                restart = True
        except GLib.Error:
            self.logger.error("Sink in invalid state")
            return GatewayResultCode.GW_RES_INVALID_SINK_STATE

        try:
            self.proxy.ProcessScratchpad()
        except GLib.Error as e:
            ret = ReturnCode.error_from_dbus_exception(e.message)
            self.logger.error("Could not restore sink's state: %s", ret.name)

        if restart:
            try:
                self.proxy.SetStackState(True)
            except GLib.Error as e:
                ret = ReturnCode.error_from_dbus_exception(e.message)
                self.logger.debug("Sink in invalid state: %s", ret.name)

        return ret 
Example #10
Source File: sink_manager.py    From gateway with Apache License 2.0 5 votes vote down vote up
def cost(self, new_cost):
        if new_cost is None or new_cost < 0 or new_cost > 254:
            raise ValueError("Wrong sink cost value {}".format(new_cost))

        try:
            self.proxy.SinkCost = new_cost
        except GLib.Error:
            self.logger.error("Cannot set sink cost for sink {}".format(self.sink_id)) 
Example #11
Source File: sink_manager.py    From gateway with Apache License 2.0 5 votes vote down vote up
def cost(self):
        try:
            cost = self.proxy.SinkCost
        except GLib.Error:
            self.logger.error("Cannot get sink cost for sink {}".format(self.sink_id))
            cost = 0
        return cost 
Example #12
Source File: sink_manager.py    From gateway with Apache License 2.0 5 votes vote down vote up
def _get_pair_params(self, dic, key1, att1, key2, att2):
        # Some settings are only relevant if the both can be retrieved
        try:
            att1_val = getattr(self.proxy, att1)
            att2_val = getattr(self.proxy, att2)
        except GLib.Error:
            self.logger.debug("Cannot get one of the pair value (%s-%s)", key1, key2)
            return

        dic[key1] = att1_val
        dic[key2] = att2_val 
Example #13
Source File: sink_manager.py    From gateway with Apache License 2.0 5 votes vote down vote up
def _get_param(self, dic, key, attribute):
        try:
            dic[key] = getattr(self.proxy, attribute)
        except (GLib.Error, AttributeError):
            # Exception raised when getting attribute (probably not set)
            # Discard channel_map as parameter present only for old stacks
            if key != "channel_map":
                # Warning and not an error as normal behavior if not set
                self.logger.warning("Cannot get %s in config (is it set?)", key) 
Example #14
Source File: sink_manager.py    From gateway with Apache License 2.0 5 votes vote down vote up
def upload_scratchpad(self, seq, file):
        ret = GatewayResultCode.GW_RES_OK
        restart = False
        try:
            # Stop the stack if not already stopped
            if self.proxy.StackStatus == 0:
                self.proxy.SetStackState(False)
                restart = True
        except GLib.Error:
            self.logger.error("Sink in invalid state")
            return GatewayResultCode.GW_RES_INVALID_SINK_STATE

        try:
            self.proxy.UploadScratchpad(seq, file)
            self.logger.info(
                "Scratchpad loaded with seq %d on sink %s", seq, self.sink_id
            )
        except GLib.Error as e:
            ret = ReturnCode.error_from_dbus_exception(e.message)
            self.logger.error("Cannot upload local scratchpad: %s", ret.name)
        except OverflowError:
            # It may happens as protobuf has bigger container value
            ret = GatewayResultCode.GW_RES_INVALID_PARAM
            self.logger.error("Invalid range value")

        if restart:
            try:
                # Restart sink if we stopped it for this request
                self.proxy.SetStackState(True)
            except GLib.Error as e:
                ret = ReturnCode.error_from_dbus_exception(e.message)
                self.logger.error("Could not restore sink's state: %s", ret.name)

        return ret 
Example #15
Source File: sink_manager.py    From gateway with Apache License 2.0 5 votes vote down vote up
def send_data(
        self,
        dst,
        src_ep,
        dst_ep,
        qos,
        initial_time,
        data,
        is_unack_csma_ca=False,
        hop_limit=0,
    ):
        try:
            res = self.proxy.SendMessage(
                dst,
                src_ep,
                dst_ep,
                initial_time,
                qos,
                is_unack_csma_ca,
                hop_limit,
                data,
            )
            if res != 0:
                self.logger.error("Cannot send message err=%s", res)
                return ReturnCode.error_from_dbus_return_code(res)
        except GLib.Error as e:
            self.logger.exception("Fail to send message: %s", e.message)
            return ReturnCode.error_from_dbus_exception(e.message)
        except OverflowError:
            # It may happens as protobuf has bigger container value
            self.logger.error("Invalid range value")
            return GatewayResultCode.GW_RES_INVALID_PARAM

        return GatewayResultCode.GW_RES_OK 
Example #16
Source File: ui.py    From pympress with GNU General Public License v2.0 5 votes vote down vote up
def menu_about(self, *args):
        """ Display the "About pympress" dialog.

        Handles clicks on the "about" menu.
        """
        about = Gtk.AboutDialog(transient_for = self.p_win)
        pympress = util.get_pympress_meta()
        about.set_program_name('pympress')
        about.set_version(pympress['version'])
        about.set_copyright(_('Contributors:') + '\n' + pympress['contributors'])
        about.set_comments(_('pympress is a little PDF reader written in Python ' +
                             'using Poppler for PDF rendering and GTK for the GUI.\n') +
                           _('Some preferences are saved in ') + self.config.path_to_config() + '\n' +
                           _('Resources are loaded from ') + os.path.dirname(util.get_locale_dir()) + '\n' +
                           _('The log is written to ') + util.get_log_path() + '\n\n' +
                           _('Media support uses {}.').format(self.medias.backend_version()) + '\n' +
                           _('Python version {}').format(sys.version))
        about.set_website('https://github.com/Cimbali/pympress')
        try:
            about.set_logo(GdkPixbuf.Pixbuf.new_from_file(util.get_icon_path('pympress-128.png')))
        except Exception:
            logger.exception(_('Error loading icon for about window'))
        about.run()
        about.destroy()


    ##############################################################################
    ############################ Document manangement ############################
    ############################################################################## 
Example #17
Source File: sink_manager.py    From gateway with Apache License 2.0 5 votes vote down vote up
def get_network_address(self, force=False):
        if self.network_address is None or force:
            # Network address is not known or must be updated
            try:
                self.network_address = self.proxy.NetworkAddress
            except GLib.Error:
                self.logger.exception("Could not get network address")

        return self.network_address 
Example #18
Source File: __init__.py    From signal-curses with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        log('message thread')

        if self.app.state.bus == 'system':
            self.bus = pydbus.SystemBus()
        else:
            self.bus = pydbus.SessionBus()

        log('waiting for ({}) dbus...'.format(self.app.state.bus))
        self.signal = exception_waitloop(self.get_message_bus, GLib.Error, 60)
        if not self.signal:
            log('dbus err')
            npyscreen.notify_wait('Unable to get signal {} bus. Messaging functionality will not function.'.format(
                self.app.state.bus), title='Error in SignalDaemonThread')
            exit(1)
        log('got dbus')
        # self.signal.onMessageReceived

        while True:
            item = self.queue.get()
            log('queue item', item)
            if 'exit' in item:
                break
            self.do_action(**item)
            self.queue.task_done()
        log('message thread exit') 
Example #19
Source File: ui.py    From pympress with GNU General Public License v2.0 5 votes vote down vote up
def error_opening_file(self, filename):
        """ Remove the current document.
        """
        # Check if the path is valid
        if not os.path.exists(filename):
            msg = _('Could not find the file "{}"').format(filename)
        else:
            msg = _('Error opening the file "{}"').format(filename)
        dialog = Gtk.MessageDialog(transient_for = self.p_win, flags = Gtk.DialogFlags.MODAL,
                                   message_type = Gtk.MessageType.ERROR, message_format = msg)
        dialog.add_buttons(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)
        dialog.set_position(Gtk.WindowPosition.CENTER)
        dialog.run()
        dialog.destroy() 
Example #20
Source File: ui.py    From pympress with GNU General Public License v2.0 5 votes vote down vote up
def load_icons(self):
        """ Set the icon list for both windows.
        """
        try:
            icon_list = [GdkPixbuf.Pixbuf.new_from_file(i) for i in util.list_icons()]
        except Exception:
            logger.exception('Error loading icons')
            return

        self.c_win.set_icon_list(icon_list)
        self.p_win.set_icon_list(icon_list) 
Example #21
Source File: utils.py    From nautilus-folder-icons with GNU General Public License v3.0 5 votes vote down vote up
def load_pixbuf(theme, icon_name):
    pixbuf = None
    try:
        icon_info = theme.lookup_icon(icon_name, 64, 0)
        if not icon_info.is_symbolic():
            icon_path = icon_info.get_filename()
            if not path.islink(icon_path) and icon_name.startswith("folder"):
                pixbuf = icon_info.load_icon()
    except GLib.Error:
        pixbuf = theme.load_icon("image-missing", 64, 0)
    if pixbuf and (pixbuf.props.width != 64 or pixbuf.props.height != 64):
        pixbuf = pixbuf.scale_simple(64, 64,
                                     GdkPixbuf.InterpType.BILINEAR)
    return pixbuf 
Example #22
Source File: panctl.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def unverified_devices(self, pan_user, room_id, display_name):
        self.completer.rooms[pan_user].add(room_id)
        print(
            f"Error sending message for user {pan_user}, "
            f"there are unverified devices in the room {display_name} "
            f"({room_id}).\nUse the send-anyways or cancel-sending commands "
            f"to ignore the devices or cancel the sending."
        ) 
Example #23
Source File: panctl.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def error(self, message):
        message = f"Error: {message} " f"(see help)"
        print(message)
        raise ParseError 
Example #24
Source File: gtk.py    From kickoff-player with GNU General Public License v3.0 5 votes vote down vote up
def image_from_path(path, size=48, image=None):
  gimage = Gtk.Image() if image is None else image

  try:
    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(path, size, size, True)
    gimage.set_from_pixbuf(pixbuf)
  except GLib.Error:
    pass

  return gimage 
Example #25
Source File: sniffer.py    From btle-sniffer with MIT License 5 votes vote down vote up
def __enter__(self):
        self._log.debug("Choosing the first available Bluetooth adapter and "
                        "starting device discovery.")
        self._log.debug("The discovery filter is set to Bluetooth LE only.")
        try:
            self.adapter = find_adapter()
            self.adapter.SetDiscoveryFilter({"Transport": pydbus.Variant("s", "le")})
            self.adapter.StartDiscovery()
        except GLib.Error as ex:
            self._log.exception("Is the bluetooth controller powered on? "
                                "Use `bluetoothctl`, `power on` otherwise.")
            raise ex
        return self 
Example #26
Source File: ui.py    From pympress with GNU General Public License v2.0 4 votes vote down vote up
def swap_document(self, docpath, page = 0, reloading = False):
        """ Replace the currently open document with a new one.

        The new document is possibly and EmptyDocument if docpath is None.
        The state of the ui and cache are updated accordingly.

        Args:
            docpath (`str`): the absolute path to the new document
            page (`int`): the page at which to start the presentation
            reloading (`bool`): whether we are reloading or detecting stuff from the document
        """
        try:
            self.doc = document.Document.create(self, docpath)

            if not reloading and docpath:
                Gtk.RecentManager.get_default().add_item(self.doc.get_uri())
                extras.FileWatcher.watch_file(docpath, self.reload_document)

        except GLib.Error:
            if reloading:
                return
            self.doc = document.Document.create(self, None)
            self.error_opening_file(docpath)
            extras.FileWatcher.stop_watching()

        # Guess notes mode by default if the document has notes
        if not reloading:
            hpref = self.config.get('notes position', 'horizontal')
            vpref = self.config.get('notes position', 'vertical')
            self.chosen_notes_mode = target_mode = self.doc.guess_notes(hpref, vpref)

            # don't toggle from NONE to NONE
            if self.chosen_notes_mode == document.PdfPage.NONE:
                self.chosen_notes_mode = document.PdfPage.RIGHT

            if self.notes_mode != target_mode:
                self.switch_mode('swap_document', docpath, target_mode = target_mode)

        # Some things that need updating
        self.cache.swap_document(self.doc)
        self.page_number.set_last(self.doc.pages_number())
        self.page_number.enable_labels(self.doc.has_labels())
        self.doc.goto(page)
        self.medias.purge_media_overlays()

        # Draw the new page(s)
        if not reloading:
            self.talk_time.pause()
            self.timing.reset(int(self.talk_time.delta))
            self.talk_time.reset_timer()

        self.on_page_change(False) 
Example #27
Source File: information.py    From vimiv with MIT License 4 votes vote down vote up
def show_version_info(self, running_tests=False):
        """Show information about current version in a Gtk pop-up.

        Args:
            running_tests: If True running from testsuite. Do not show pop-up.
        """
        # Popup with buttons
        popup = Gtk.Dialog(title="vimiv - Info", transient_for=Gtk.Window())
        licence_button = popup.add_button(" Licence", Gtk.ResponseType.HELP)
        popup.add_button("Close", Gtk.ResponseType.CLOSE)
        # Different widgets
        licence_button.connect("clicked", self.show_licence)
        licence_icon = Gtk.Image.new_from_icon_name(
            "text-x-generic-symbolic", 0)
        licence_button.set_image(licence_icon)
        licence_button.set_always_show_image(True)

        version_label = Gtk.Label()
        version_label.set_markup(
            '<span size="xx-large">' + self.get_version() + "</span>")

        info_label = Gtk.Label()
        info_label.set_text("vimiv - an image viewer with vim-like keybindings")
        info_label.set_hexpand(True)

        website_label = Gtk.Label()
        website_label.set_halign(Gtk.Align.END)
        website_label.set_markup('<a href="http://karlch.github.io/vimiv"'
                                 'title="vimiv website">Website</a>')
        github_label = Gtk.Label()
        github_label.set_halign(Gtk.Align.START)
        github_label.set_markup('<a href="https://www.github.com/karlch/vimiv"'
                                'title="vimiv on GitHub">GitHub</a>')

        icon_theme = Gtk.IconTheme.get_default()
        # Icon not available in theme when icon cache was not updated
        try:
            vimiv_pixbuf = icon_theme.load_icon("vimiv", 128, 0)
            vimiv_image = Gtk.Image.new_from_pixbuf(vimiv_pixbuf)
            load_image = True
        except GLib.Error:
            load_image = False

        # Layout
        box = popup.get_child()
        box.set_border_width(12)
        grid = Gtk.Grid()
        grid.set_column_spacing(12)
        grid.set_row_spacing(12)
        box.pack_start(grid, False, False, 12)
        grid.attach(version_label, 0, 0, 2, 1)
        if load_image:
            grid.attach(vimiv_image, 0, 1, 2, 1)
        grid.attach(info_label, 0, 2, 2, 1)
        grid.attach(website_label, 0, 3, 1, 1)
        grid.attach(github_label, 1, 3, 1, 1)
        popup.show_all()
        if not running_tests:
            popup.run()
            popup.destroy() 
Example #28
Source File: sink_manager.py    From gateway with Apache License 2.0 4 votes vote down vote up
def read_config(self):
        config = {}
        config["sink_id"] = self.sink_id

        # Should always be available
        try:
            config["started"] = (self.proxy.StackStatus & 0x01) == 0
        except GLib.Error as e:
            error = ReturnCode.error_from_dbus_exception(e.message)
            self.logger.exception("Cannot get Stack state: %s", error)
            return None

        self._get_param(config, "node_address", "NodeAddress")
        self._get_param(config, "node_role", "NodeRole")
        self._get_param(config, "network_address", "NetworkAddress")
        self._get_param(config, "network_channel", "NetworkChannel")
        self._get_param(config, "channel_map", "ChannelMap")
        self._get_pair_params(config, "max_ac", "ACRangeMax", "min_ac", "ACRangeMin")
        self._get_pair_params(
            config, "max_ac_cur", "ACRangeMaxCur", "min_ac_cur", "ACRangeMinCur"
        )
        self._get_pair_params(config, "max_ch", "ChRangeMax", "min_ch", "ChRangeMin")
        self._get_param(config, "max_mtu", "MaxMtu")
        self._get_param(config, "hw_magic", "HwMagic")
        self._get_param(config, "stack_profile", "StackProfile")
        self._get_param(config, "firmware_version", "FirmwareVersion")
        self._get_param(config, "app_config_max_size", "AppConfigMaxSize")

        try:
            are_keys_set = self.proxy.AuthenticationKeySet and self.proxy.CipherKeySet

            config["are_keys_set"] = are_keys_set
        except GLib.Error:
            self.logger.error("Cannot get key status")

        try:
            seq, diag, data = self.proxy.GetAppConfig()
            config["app_config_seq"] = seq
            config["app_config_diag"] = diag
            config["app_config_data"] = bytearray(data)
        except GLib.Error:
            # If node is blank it is not a sink
            # so app config cannot be accessed
            self.logger.warning("Cannot get App Config")

        return config 
Example #29
Source File: sink_manager.py    From gateway with Apache License 2.0 4 votes vote down vote up
def get_scratchpad_status(self):
        d = {}

        dbus_to_gateway_satus = dict(
            [
                (0, ScratchpadStatus.SCRATCHPAD_STATUS_SUCCESS),
                (255, ScratchpadStatus.SCRATCHPAD_STATUS_NEW)
                # Anything else is ERROR
            ]
        )
        try:
            status = self.proxy.StoredStatus
            d["stored_status"] = dbus_to_gateway_satus[status]
        except GLib.Error:
            # Exception raised when getting attribute (probably not set)
            self.logger.error("Cannot get stored status in config")
        except KeyError:
            # Between 1 and 254 => Error
            self.logger.error("Scratchpad stored status has error: %s", status)
            d["stored_status"] = ScratchpadStatus.SCRATCHPAD_STATUS_ERROR

        dbus_to_gateway_type = dict(
            [
                (0, ScratchpadType.SCRATCHPAD_TYPE_BLANK),
                (1, ScratchpadType.SCRATCHPAD_TYPE_PRESENT),
                (2, ScratchpadType.SCRATCHPAD_TYPE_PROCESS),
            ]
        )
        try:
            stored_type = self.proxy.StoredType
            d["stored_type"] = dbus_to_gateway_type[stored_type]
        except GLib.Error:
            # Exception raised when getting attribute (probably not set)
            self.logger.error("Cannot get stored type in config\n")

        stored = {}
        self._get_param(stored, "seq", "StoredSeq")
        self._get_param(stored, "crc", "StoredCrc")
        self._get_param(stored, "len", "StoredLen")
        d["stored_scartchpad"] = stored

        processed = {}
        self._get_param(processed, "seq", "ProcessedSeq")
        self._get_param(processed, "crc", "ProcessedCrc")
        self._get_param(processed, "len", "ProcessedLen")
        d["processed_scartchpad"] = processed

        self._get_param(d, "firmware_area_id", "FirmwareAreaId")

        return d 
Example #30
Source File: application.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _create_ssh_forwarder(self, server, username, password, window=None):
		"""
		Create and set the
		:py:attr:`~.KingPhisherClientApplication._ssh_forwarder` attribute.

		:param tuple server: The server information as a host and port tuple.
		:param str username: The username to authenticate to the SSH server with.
		:param str password: The password to authenticate to the SSH server with.
		:param window: The GTK window to use as the parent for error dialogs.
		:type window: :py:class:`Gtk.Window`
		:rtype: int
		:return: The local port that is forwarded to the remote server or None if the connection failed.
		"""
		window = window or self.get_active_window()
		title_ssh_error = 'Failed To Connect To The SSH Service'
		server_remote_port = self.config['server_remote_port']

		try:
			self._ssh_forwarder = ssh_forward.SSHTCPForwarder(
				server,
				username,
				password,
				('127.0.0.1', server_remote_port),
				private_key=self.config.get('ssh_preferred_key'),
				missing_host_key_policy=ssh_host_key.MissingHostKeyPolicy(self)
			)
			self._ssh_forwarder.start()
		except ssh_forward.KingPhisherSSHKeyError as error:
			gui_utilities.show_dialog_error('SSH Key Configuration Error', window, error.message)
		except errors.KingPhisherAbortError as error:
			self.logger.info("ssh connection aborted ({0})".format(error.message))
		except paramiko.PasswordRequiredException:
			gui_utilities.show_dialog_error(title_ssh_error, window, 'The specified SSH key requires a password.')
		except paramiko.AuthenticationException:
			self.logger.warning('failed to authenticate to the remote ssh server')
			gui_utilities.show_dialog_error(title_ssh_error, window, 'The server responded that the credentials are invalid.')
		except paramiko.SSHException as error:
			self.logger.warning("failed with ssh exception '{0}'".format(error.args[0]))
		except socket.error as error:
			gui_utilities.show_dialog_exc_socket_error(error, window, title=title_ssh_error)
		except Exception as error:
			self.logger.warning('failed to connect to the remote ssh server', exc_info=True)
			gui_utilities.show_dialog_error(title_ssh_error, window, "An {0}.{1} error occurred.".format(error.__class__.__module__, error.__class__.__name__))
		else:
			return self._ssh_forwarder.local_server
		self.emit('server-disconnected')
		return