def main(): loop = GLib.MainLoop() bus = pydbus.SystemBus() obj = PolicyAgent() bus.publish('org.qubesos.PolicyAgent', obj) loop.run()
import pydbus from gi.repository import GObject sysbus = pydbus.SystemBus() systemd = sysbus.get('io.qtc.wxagent') def handler1(a, b, c, d, e): print(11111, a, b, c, d, e) return # help(sysbus.subscribe) sysbus.subscribe(iface='io.qtc.wxagent.signals', signal='newmessage', signal_fired=handler1) GObject.MainLoop().run()
def main(args=None): args = parser.parse_args(args) # Add source domain information, required by qrexec-client for establishing # connection caller_ident = args.process_ident + "," + args.domain + "," + args.domain_id log = logging.getLogger('qubespolicy') log.setLevel(logging.INFO) if not log.handlers: handler = logging.handlers.SysLogHandler(address='/dev/log') log.addHandler(handler) log_prefix = 'qrexec: {}: {} -> {}: '.format(args.service_name, args.domain, args.target) try: system_info = qubespolicy.get_system_info() except qubespolicy.QubesMgmtException as e: log.error(log_prefix + 'error getting system info: ' + str(e)) return 1 try: try: policy = qubespolicy.Policy(args.service_name) except qubespolicy.PolicyNotFound: service_name = args.service_name.split('+')[0] import pydbus bus = pydbus.SystemBus() proxy = bus.get('org.qubesos.PolicyAgent', '/org/qubesos/PolicyAgent') create_policy = proxy.ConfirmPolicyCreate(args.domain, service_name) if create_policy: create_default_policy(service_name) policy = qubespolicy.Policy(args.service_name) else: raise action = policy.evaluate(system_info, args.domain, args.target) if args.assume_yes_for_ask and action.action == qubespolicy.Action.ask: action.action = qubespolicy.Action.allow if args.just_evaluate: return { qubespolicy.Action.allow: 0, qubespolicy.Action.deny: 1, qubespolicy.Action.ask: 1, }[action.action] if action.action == qubespolicy.Action.ask: # late import to save on time for allow/deny actions import pydbus bus = pydbus.SystemBus() proxy = bus.get('org.qubesos.PolicyAgent', '/org/qubesos/PolicyAgent') icons = { name: system_info['domains'][name]['icon'] for name in system_info['domains'].keys() } for dispvm_base in system_info['domains']: if not (system_info['domains'][dispvm_base] ['template_for_dispvms']): continue dispvm_api_name = '@dispvm:' + dispvm_base icons[dispvm_api_name] = \ system_info['domains'][dispvm_base]['icon'] icons[dispvm_api_name] = \ icons[dispvm_api_name].replace('app', 'disp') response = proxy.Ask(args.domain, args.service_name, action.targets_for_ask, action.target or '', icons) if response: action.handle_user_response(True, response) else: action.handle_user_response(False) log.info(log_prefix + 'allowed to {}'.format(action.target)) action.execute(caller_ident) except qubespolicy.PolicySyntaxError as e: log.error(log_prefix + 'error loading policy: ' + str(e)) return 1 except qubespolicy.AccessDenied as e: log.info(log_prefix + 'denied: ' + str(e)) return 1 return 0
def __init__(self) -> None: system_bus = pydbus.SystemBus() # Check if timewarpd is already running. try: system_bus.get("com.branchonequal.TimeWarp") running = True except GLib.Error: running = False if running: raise timewarp.error.InitializationError( "timewarpd is already running") self._in_init = True self._userdata = {} # Set up a signal handler to cleanly quit the main event loop on # Ctrl+C and SIGTERM. signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGTERM, self._signal_handler) # Set up the main event loop. self._loop = GLib.MainLoop() # Load the configuration. Raises InitializationError if the # configuration file could not be found or the configuration is # invalid. self._configuration = timewarp.configuration.Configuration() self._bootenvs = pathlib.Path(self._configuration.bootenv) self._linux = self._configuration.package.linux self._mount_point = pathlib.Path(self._configuration.boot.mount_point) self._snapshots = pathlib.Path(self._configuration.snapshots) boot_on_root = self._configuration.boot.boot_on_root \ if "boot_on_root" in self._configuration.boot else False database = self._configuration.package.database loader = self._configuration.boot.loader machine_id = self._configuration.machine_id snapper = self._configuration.snapper # Import the boot loader module. try: importlib.import_module(f"timewarp.service.boot.loader.{loader}") except ModuleNotFoundError as e: raise timewarp.error.InitializationError( f"Boot loader module {loader} not found") # Import the package database module. try: importlib.import_module( f"timewarp.service.package.database.{database}") except ModuleNotFoundError as e: raise timewarp.error.InitializationError( f"Package database module {database} not found") # Check if the /boot mount point exists and the partition is mounted. if not self._mount_point.exists(): raise timewarp.error.InitializationError( f"Boot partition mount point {self._mount_point} " f"does not exist") if not list(self._mount_point.glob("*")): raise timewarp.error.InitializationError( "Boot partition is not mounted") # Initialize the boot loader with the /boot mount point. Raises # InitializationError if a boot loader-specific check has failed. self._loader = timewarp.service.boot.Loader.__subclasses__()[0]( self._mount_point, boot_on_root) # As we need to be able to access the package databases of boot # environments we store the package database class for later use and # also initialize the root package database. Raises # InitializationError if the local package database could not be found. self._database = timewarp.service.package.Database.__subclasses__()[0] self._root_database = self._database(pathlib.Path("/")) # Check if we can query the kernel package. try: linux = self._root_database.get_packages_by_name(self._linux)[-1] except timewarp.error.PackageNotFoundError: raise timewarp.error.InitializationError( f"Kernel package {self._linux} not found") except timewarp.error.InvalidPackageInformationError: raise timewarp.error.InitializationError( "Failed to query database package: " "Invalid package information") # Check if the boot environment and snapshot directories exist. if not self._bootenvs.exists(): raise timewarp.error.InitializationError( f"Boot environment directory {self._bootenvs} does not exist") if not self._snapshots.exists(): raise timewarp.error.InitializationError( f"Snapshot directory {self._snapshots} does not exist") # Initialize the GIO file monitor for monitoring the snapshot # directory. self._monitor = Gio.file_new_for_path( bytes(self._snapshots)).monitor(Gio.FileMonitorFlags.NONE, None) self._monitor.connect("changed", self._monitor_handler) # Read the local machine ID. try: with open(machine_id, "r") as f: machine_id_ = f.read().strip() except FileNotFoundError: raise timewarp.error.InitializationError( f"Local machine ID configuration file {machine_id} not found") # This is the default mapping for substituting replacement fields in # boot entry format strings. self._default_mapping = { "architecture": Architecture[platform.machine()].value, "machine_id": machine_id_, "root_file_system": timewarp.service.block.FileSystem("/"), "root_partition": timewarp.service.block.Partition("/") } # Check for invalid replacement fields in the boot entry configuration. # For this we are setting up a dummy snapshot. mapping = { **self._default_mapping, "linux": linux, "snapshot": timewarp.service.snapper.Snapshot( 0, 0, 0, 0, 0, "", "", {}) } try: self._configuration.format(mapping, self._configuration.boot.entry) except (AttributeError, KeyError) as e: raise timewarp.error.InitializationError( f"Invalid replacement field in boot entry configuration: {e}") # Initialize Snapper. Raises InitializationError if snapperd is not # running. self._snapper = timewarp.service.snapper.Snapper( snapper.name, snapper.cleanup_algorithm) # Clean up orphaned boot environments. bootenvs = set([file.name for file in self._bootenvs.glob("*")]) snapshots = set([file.name for file in self._snapshots.glob("*")]) for bootenv in bootenvs - snapshots: try: self._clean_up(int(bootenv), True) except ValueError: pass # Publish the service on the D-Bus system bus. try: system_bus.publish("com.branchonequal.TimeWarp", self) except GLib.Error as e: raise timewarp.error.InitializationError( f"Connection to the D-Bus system bus failed: " f"{timewarp.error.DBusError(e.code)}") # Set syslog logging options. syslog.openlog("timewarpd") self._in_init = False
def get_new_connection(self): """Get a system DBus connection.""" log.info("Connecting to the system bus.") return pydbus.SystemBus()
def __init__(self): self._bus = pydbus.SystemBus() self._bus_handler = None self._mwcapture = MWCapture() self._mainloop = GLib.MainLoop()
def setup_power_saving(self): bus = pydbus.SystemBus() self.upower = bus.get(UPOWER) self.onbattery = None self.upower.onPropertiesChanged = self.power_change
def __init__(self): self.logger = logging.getLogger(self.__class__.__name__) if not os.path.exists(MINIDLNA_CONFIG_DIR): os.mkdir(MINIDLNA_CONFIG_DIR) self.config = MiniDLNAIndicatorConfig(MINIDLNA_INDICATOR_CONFIG) self.set_gnome_autostart(self.config.startup_indicator) self.indicator = AppIndicator3.Indicator.new(APPINDICATOR_ID, MINIDLNA_ICON_GREY, AppIndicator3.IndicatorCategory.APPLICATION_STATUS) self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) self.minidlna_running = False self.minidlna_path = None self.minidlna_port = 0 self.minidlna_dirs = [] self.minidlna_logdir = None self.minidlna_not_installed_menuitem = None self.install_minidlna_menuitem = None self.minidlna_detect_menuitem = None self.reload_configuration_menuitem = None self.start_menuitem = None self.start_reindex_menuitem = None self.restart_menuitem = None self.restart_reindex_menuitem = None self.stop_menuitem = None self.weblink_menuitem = None self.editconfig_menuitem = None self.showlog_menuitem = None self.indicator_startup_menuitem = None self.minidlna_startup_menuitem = None self.minidlna_stop_on_exit_menuitem = None self.item_quit = None self.ensure_menu_shotcut() self.logger.debug(u"Startup: Detecting MiniDLNA...") self.detect_minidlna() # Monitor for usb disks plugs self.current_partitions = [] self.bus = pydbus.SystemBus() self.udisks2_manager = self.bus.get('.UDisks2') for path, properties in self.udisks2_manager.GetManagedObjects().items(): block_properties = properties.get('org.freedesktop.UDisks2.Block') filesystem_properties = properties.get('org.freedesktop.UDisks2.Filesystem') if block_properties and filesystem_properties: self.add_device(path, block_properties, filesystem_properties) self.udisks2_manager.onInterfacesAdded = self.device_added self.udisks2_manager.onInterfacesRemoved = self.device_removed if self.config.startup_minidlna: if not self.get_minidlna_pid(): self.logger.debug(u"Startup: Auto-Starting MiniDLNA...") self.start_minidlna_process() Notify.init(APPINDICATOR_ID) self.logger.debug(u"Starting thread to monitor minidlna status...") self.background_minidlna_running_status_changes_stopevent = threading.Event() self.background_minidlna_running_status_changes_thread = threading.Thread(target=self.background_minidlna_running_status_changes) self.background_minidlna_running_status_changes_thread.start() # Notify if minidlna not found if not self.minidlna_path: Notify.Notification.new( _(u"MiniDLNA not installed"), _(u"MiniDLNA is not installed; please, click in the menu to install it."), None ).show() # http://stackoverflow.com/questions/16410852/keyboard-interrupt-with-with-python-gtk self.mainloop = GObject.MainLoop() try: self.mainloop.run() except KeyboardInterrupt: self.logger.info(u"Ctrl+C hit, quitting") self.quit(None)
def __init__(self): super(MicDeviceExtension, self).__init__() self.bus = pydbus.SystemBus()
from pathlib import Path import distro import pydbus from gi.repository import GLib from semver import VersionInfo try: try: bundle_path = Path(os.environ["RAUC_BUNDLE_MOUNT_POINT"]) except KeyError: bundle_path = Path(os.environ["RAUC_UPDATE_SOURCE"]) # Admin check try: printer0 = pydbus.SystemBus().get("cz.prusa3d.sl1.printer0") admin = printer0.admin_enabled except (GLib.GError, AttributeError) as e: admin = False print("Admin query via DBus failed. Considering admin disabled.") # Downgrade always allowed downgrade_enabled = True # Obtain bundle version manifest = configparser.ConfigParser() manifest.read(bundle_path / "manifest.raucm") bundle_version = manifest["update"]["version"] # Obtain system version system_version = distro.version()
#!/usr/bin/env python from time import sleep import RPi.GPIO as GPIO import pydbus, sys # get active jobs to determine if we are shutting down or rebooting systemd1 = pydbus.SystemBus().get('org.freedesktop.systemd1', '/org/freedesktop/systemd1') job_list = systemd1.ListJobs() is_shutting_down = False is_rebooting = False for active_job in job_list: if active_job[1] == "shutdown.target" and active_job[2] == "start": is_shutting_down = True elif active_job[1] == "reboot.target" and active_job[2] == "start": is_rebooting = True if is_shutting_down: # note: this includes both rebooting and shutting down for powering offf GPIO.setmode(GPIO.BCM) # raspdac poweroff/reboot commands start by maintaining a HIGH level on GPIO04 (reboot doesn't need anything else) GPIO.setup(4, GPIO.OUT) GPIO.output(4, GPIO.HIGH) sleep(1) # maintain the level long enough to be ack by the power manager if is_rebooting: print("Raspdac rebooting...") else:
def __init__(self): # setup dbus self.bus = pydbus.SystemBus() self.mngr = self.bus.get(BLUEZ_SERVICE, '/') self.adapter = self.bus.get(BLUEZ_SERVICE, ADAPTER_PATH)
# HDMI 0 2 # Composite 3 # HDMI 1 7 # # If HDMI-CDC is needed, see: https://pimylifeup.com/raspberrypi-hdmi-cec/ # import time, pygame import os, io import threading import platform import logging from colorsys import rgb_to_hls, hls_to_rgb try: import pydbus timedated = pydbus.SystemBus().get(".timedate1") except ImportError: print("pydbus library not found") timedated = None logger = logging.getLogger(__name__) # This is a value returned from an entity that is unknown (e.g., HA first starting) UNKNOWN_VALUE = "unknown" UNAVAILABLE_VALUE = "unavailable" DEFAULT_DISPLAY_BRIGHTNESS = 50.0 class HdmiDisplay: def __init__(self, ceiling_display):
def __init__(self): super().__init__(pydbus.SystemBus(), 'org.bluez')
def dbus_server(): loop = GLib.MainLoop() bus = pydbus.SystemBus(); bus.publish("xyz.niles.LeslieBot", Listener()) loop.run()
def add_unit_name(self, unit_name): bus = pydbus.SystemBus() self._units[unit_name] = bus.get(SystemdUtils.SYSTEMD_BUS_NAME, get_unit_path(unit_name))