def init_bulb(): bus = dbus.SystemBus() ble_manager = bus.get_object(DBUS_BUS_BLE_NAME, '/') bulb_path = ble_manager.Create( BULB_ADDRESS, dbus_interface='com.devicehive.BluetoothManager') return bus.get_object(DBUS_BUS_BLE_NAME, bulb_path)
def get_adapter_property(device_name, prop): bus = dbus.SystemBus() adapter_path = find_adapter(device_name).object_path adapter = dbus.Interface(bus.get_object(SERVICE_NAME, adapter_path), "org.freedesktop.DBus.Properties") return adapter.Get(ADAPTER_INTERFACE, prop)
time.sleep(1) # Give NetworkManager a bit of time to start and rediscover itself. for key in self.handlers: val, self.handlers[key] = self.handlers[key], [] for obj, func, args, kwargs in val: try: # This resets the object path if needed obj.proxy self.add_signal_receiver(key[0], key[1], obj, func, args, kwargs) except ObjectVanished: pass SignalDispatcher = SignalDispatcher() # We completely dynamically generate all classes using introspection data. As # this is done at import time, use a special dbus connection that does not get # in the way of setting a mainloop and doing async stuff later. init_bus = dbus.SystemBus(private=True) xml_cache = {} class NMDbusInterfaceType(type): """Metaclass that generates our classes based on introspection data""" dbus_service = 'org.freedesktop.NetworkManager' def __new__(type_, name, bases, attrs): attrs['dbus_service'] = type_.dbus_service attrs['properties'] = [] attrs['introspection_data'] = None attrs['signals'] = [] # Derive the interface name from the name of the class, but let classes # override it if needed if 'interface_names' not in attrs and 'NMDbusInterface' not in name:
def __init__(self): self.bus = dbus.SystemBus() self.obj = self.bus.get_object('org.freedesktop.Hal', '/org/freedesktop/Hal/Manager') self.manager = dbus.Interface(self.obj, 'org.freedesktop.Hal.Manager')
def __init__(self): self.bus = dbus.service.BusName('org.tf101', bus=dbus.SystemBus()) dbus.service.Object.__init__(self, self.bus, '/org/tf101') self.lid_status = 0
''' Classes and utilities for monitoring the current state of the network, allowing plugins that declare "needs_network" to be enabled or disabled depending on this state. This is done using the NetworkManager DBUS interface, although the number of states available is reduced to connected/disconnected ''' import dbus # Logging import logging logger = logging.getLogger(__name__) _system_bus = dbus.SystemBus() NM_BUS_NAME = 'org.freedesktop.NetworkManager' NM_OBJECT_PATH = '/org/freedesktop/NetworkManager' NM_INTERFACE_NAME = 'org.freedesktop.NetworkManager' NM_STATE_INDEX = { 0: 'Unknown', 10: 'Asleep', 20: 'Disconnected', 30: 'Disconnecting', 40: 'Connecting', 50: 'Connected (Local)', 60: 'Connected (Site)', 70: 'Connected (Global)' } class NetworkManager(): def __init__(self, screen):
def __init__(self): self._sysbus = dbus.SystemBus() self._certmonger_bus_obj = self._sysbus.get_object( self.DBUS_CM_IF, self.DBUS_CM_PATH)
def __init__(self): self.bus = dbus.SystemBus() self.proxy = self.bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
def __init__(self): self._bus = dbus.SystemBus() self._bluez = dbus.Interface(self._bus.get_object('org.bluez', '/'), 'org.freedesktop.DBus.ObjectManager')
def _connectSleepHandler(self): bus = dbus.SystemBus() bus.add_signal_receiver(self.PrepareForSleepHandler, self.SLEEP_PREPARE_SIGNAL, self.LOGIND_MANAGER_INTERFACE, self.LOGIND_NAME)
def __init__(self): self.bus = dbus.SystemBus() self.proxy = self.bus.get_object("org.freedesktop.ModemManager", "/org/freedesktop/ModemManager") modem_manager = dbus.Interface(self.proxy, self.MM_DBUS_IFACE) self.modems = modem_manager.EnumerateDevices()
def _connectPropsChangedHandler(self): bus = dbus.SystemBus() bus.add_signal_receiver(self.PropsChangedHandler, self.PROPS_CHANGED_SIGNAL, self.PROPS_INTERFACE, self.UPOWER_NAME)
def __init__(self, phone_service): bus_name = dbus.service.BusName(BUSNAME, bus=dbus.SystemBus()) dbus.service.Object.__init__(self, bus_name=bus_name, object_path=SUPPORT_OBJECTPATH) self.phone_service = phone_service
def get_ble(): obj = dbus.SystemBus().get_object("com.devicehive.bluetooth", "/com/devicehive/bluetooth") return dbus.Interface(obj, "com.devicehive.bluetooth")
def run(): obj = dbus.SystemBus().get_object("org.freedesktop.hostname1", "/org/freedesktop/hostname1") print(obj.Introspect(dbus_interface="org.freedesktop.DBus.Introspectable"))
def has_connection(): import dbus bus = dbus.SystemBus() manager = bus.get_object(NM, '/org/freedesktop/NetworkManager') state = get_prop(manager, NM, 'State') return state == NM_STATE_CONNECTED_GLOBAL
def on_load(self, applet): self.bus = dbus.SystemBus()
type, list_type, key, value) cmd = os.popen(command) output = cmd.read().strip() return output @dbus.service.method(INTERFACE, in_signature='ss', out_signature='b', sender_keyword='sender') def set_config_setting(self, key, value, sender=None): self._check_permission(sender, PK_ACTION_TWEAK) log.debug('set_config_setting: %s to %s' % (key, value)) cs = ConfigSetting(key) cs.set_value(value) if cs.is_override_schema(): os.system('glib-compile-schemas /usr/share/glib-2.0/schemas/') return value == cs.get_value() @dbus.service.method(INTERFACE, in_signature='', out_signature='') def exit(self): self.mainloop.quit() if __name__ == '__main__': dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) mainloop = GObject.MainLoop() Daemon(dbus.SystemBus(), mainloop) mainloop.run()
def get_bus(self): bus = dbus.SystemBus() return bus
dumpfile(skypedir + "callmember256.dbb") dumpfile(skypedir + "chatmember256.dbb") dumpfile(skypedir + "user256.dbb", cls=SkypeContactDBB) dumpfile(skypedir + "user1024.dbb", cls=SkypeContactDBB) dumpfile(skypedir + "voicemail256.dbb") ########NEW FILE######## __FILENAME__ = dbusapi #!/usr/bin/env python import dbus import sys try: skype = dbus.SystemBus().get_object('com.Skype.API', '/com/Skype') except: try: skype = dbus.SessionBus().get_object('com.Skype.API', '/com/Skype') except: print "Can't find Skype API" sys.exit() print skype.Invoke("NAME python") print skype.Invoke("PROTOCOL 9999") print skype.Invoke("SEARCH CHATS") ########NEW FILE######## __FILENAME__ = skypelog #!/usr/bin/env python # Copyright 2011 Valery Yundin
configFile = "accounts-service-migrated" configPath = os.environ['HOME'] + "/.config/telephony-service" configFilePath = configPath + "/" + configFile #create config dir if it does not exist os.makedirs(configPath, exist_ok=True) if os.path.isfile(configFilePath): sys.exit(0) # do not allow this script running again Path(configFilePath).touch() dict = {} proxy = dbus.SystemBus().get_object('org.freedesktop.Accounts','/org/freedesktop/Accounts/User%d' % os.getuid()) properties_manager = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties') currentSimNames = properties_manager.Get('com.ubuntu.touch.AccountsService.Phone', 'SimNames') print("Migrating gsettings to Accounts Service") gsettings = Gio.Settings.new('com.ubuntu.phone') currentSimNames = gsettings.get_value("sim-names") currentDefaultSimForCalls = gsettings.get_string("default-sim-for-calls") currentDefaultSimForMessages = gsettings.get_string("default-sim-for-messages") currentMmsGroupChatEnabled = gsettings.get_boolean("mms-group-chat-enabled") properties_manager.Set('com.ubuntu.touch.AccountsService.Phone', 'DefaultSimForCalls', dbus.String(currentDefaultSimForCalls)) properties_manager.Set('com.ubuntu.touch.AccountsService.Phone', 'DefaultSimForMessages', dbus.String(currentDefaultSimForMessages)) properties_manager.Set('com.ubuntu.touch.AccountsService.Phone', 'MmsGroupChatEnabled', dbus.Boolean(currentMmsGroupChatEnabled))
def details_udisks2(usb_disk_part): """ Get details of USB disk detail. usb_disk_part: It is the partition of an USB removable disk. """ import dbus bus = dbus.SystemBus() mount_point = '' uuid = '' file_system = '' vendor = '' model = '' label = '' devtype = "disk" bd = bus.get_object( 'org.freedesktop.UDisks2', '/org/freedesktop/UDisks2/block_devices%s' % usb_disk_part[4:]) device = bd.Get('org.freedesktop.UDisks2.Block', 'Device', dbus_interface='org.freedesktop.DBus.Properties') device = bytearray(device).replace(b'\x00', b'').decode('utf-8') if device[-1].isdigit() is True: uuid = bd.Get('org.freedesktop.UDisks2.Block', 'IdUUID', dbus_interface='org.freedesktop.DBus.Properties') file_system = bd.Get('org.freedesktop.UDisks2.Block', 'IdType', dbus_interface='org.freedesktop.DBus.Properties') mount_point = bd.Get('org.freedesktop.UDisks2.Filesystem', 'MountPoints', dbus_interface='org.freedesktop.DBus.Properties') devtype = 'partition' else: devtype = 'disk' file_system = 'No_File_System' if mount_point: # mount_point = str(bytearray(mount_point[0]).decode('utf-8').replace(b'\x00', b'')) mount_point = bytearray(mount_point[0]).replace(b'\x00', b'').decode('utf-8') else: try: mount_point = u.mount(usb_disk_part) except: mount_point = "No_Mount" try: label = bd.Get('org.freedesktop.UDisks2.Block', 'IdLabel', dbus_interface='org.freedesktop.DBus.Properties') except: label = "No_Label" usb_drive_id = (bd.Get('org.freedesktop.UDisks2.Block', 'Drive', dbus_interface='org.freedesktop.DBus.Properties')) bd1 = bus.get_object('org.freedesktop.UDisks2', usb_drive_id) try: vendor = bd1.Get('org.freedesktop.UDisks2.Drive', 'Vendor', dbus_interface='org.freedesktop.DBus.Properties') except: vendor = str('No_Vendor') try: model = bd1.Get('org.freedesktop.UDisks2.Drive', 'Model', dbus_interface='org.freedesktop.DBus.Properties') except: model = str('No_Model') if not mount_point == "No_Mount": size_total = shutil.disk_usage(mount_point)[0] size_used = shutil.disk_usage(mount_point)[1] size_free = shutil.disk_usage(mount_point)[2] else: size_total = str('No_Mount') size_used = str('No_Mount') size_free = str('No_Mount') return { 'uuid': uuid, 'file_system': file_system, 'label': label, 'mount_point': mount_point, 'size_total': size_total, 'size_used': size_used, 'size_free': size_free, 'vendor': vendor, 'model': model, 'devtype': devtype }
def getManagedObjects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects()
def list_devices(fixed=False): """ List inserted USB devices. :return: USB devices as list. """ devices = [] if platform.system() == "Linux": try: # pyudev is good enough to detect USB devices on modern Linux machines. gen.log("Using pyudev for detecting USB drives...") try: import pyudev except Exception as e: gen.log( 'PyUdev is not installed on host system, using built-in.') from . import pyudev context = pyudev.Context() for device in context.list_devices(subsystem='block'): if fixed is True: if device.get('DEVTYPE') in [ 'disk', 'partition' ] and device.get('ID_PART_TABLE_TYPE'): devices.append(str(device.get('DEVNAME'))) gen.log("\t" + device.get('DEVNAME')) else: if device.get('ID_BUS') in [ 'usb' ] and device.get('ID_PART_TABLE_TYPE'): devices.append(str(device.get('DEVNAME'))) gen.log("\t" + device.get('DEVNAME')) except Exception as e: gen.log(e) import dbus bus = dbus.SystemBus() try: # You should come here only if your system does'nt have udev installed. # We will use udiskd2 for now. gen.log("Falling back to Udisks2..") ud_manager_obj = bus.get_object('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2') ud_manager = dbus.Interface( ud_manager_obj, 'org.freedesktop.DBus.ObjectManager') for k, v in ud_manager.GetManagedObjects().items(): drive_info = v.get('org.freedesktop.UDisks2.Block', {}) if fixed is True: if drive_info.get( 'IdUsage' ) == "filesystem" and not drive_info.get('ReadOnly'): device = drive_info.get('Device') device = bytearray(device).replace( b'\x00', b'').decode('utf-8') devices.append(device) else: if drive_info.get( 'IdUsage' ) == "filesystem" and not drive_info.get( 'HintSystem') and not drive_info.get( 'ReadOnly'): device = drive_info.get('Device') device = bytearray(device).replace( b'\x00', b'').decode('utf-8') devices.append(device) except Exception as e: gen.log(e, error=True) try: # You must be using really old distro. Otherwise, the code # should not reach here. gen.log("Falling back to Udisks1...") ud_manager_obj = bus.get_object("org.freedesktop.UDisks", "/org/freedesktop/UDisks") ud_manager = dbus.Interface(ud_manager_obj, 'org.freedesktop.UDisks') for dev in ud_manager.EnumerateDevices(): device_obj = bus.get_object("org.freedesktop.UDisks", dev) device_props = dbus.Interface(device_obj, dbus.PROPERTIES_IFACE) if device_props.Get( 'org.freedesktop.UDisks.Device', "DriveConnectionInterface" ) == "usb" and device_props.Get( 'org.freedesktop.UDisks.Device', "DeviceIsPartition"): if device_props.Get( 'org.freedesktop.UDisks.Device', "DeviceIsMounted"): device_file = device_props.Get( 'org.freedesktop.UDisks.Device', "DeviceFile") devices.append(device_file) except Exception as e: gen.log(e, error=True) gen.log("No USB device found...") devices.sort() elif platform.system() == "Windows": if fixed is True: for drive in psutil.disk_partitions(): if 'cdrom' in drive.opts or drive.fstype == '': # Skip cdrom drives or the disk with no filesystem continue devices.append(drive[0][:-1]) else: try: # Try new method using psutil. It should also detect USB 3.0 (but not tested by me) for drive in psutil.disk_partitions(): if 'cdrom' in drive.opts or drive.fstype == '': # Skip cdrom drives or the disk with no filesystem continue if 'removable' in drive.opts: devices.append(drive[0][:-1]) except: # Revert back to old method if psutil fails (which is unlikely) oFS = win32com.client.Dispatch("Scripting.FileSystemObject") oDrives = oFS.Drives for drive in oDrives: if drive.DriveType == 1 and drive.IsReady: devices.append(drive) if devices: return devices else: gen.log("No USB device found...") return None
def get_managed_objects(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object(SERVICE_NAME, "/"), "org.freedesktop.DBus.ObjectManager") return manager.GetManagedObjects()
def dbus_connect(self): self.odm = dbus.SystemBus().get_object(self.drbdmanage_dbus_name, self.drbdmanage_dbus_interface) self.odm.ping()
import dbus.glib # This import is needed for main loop to work. (Is this a bug?) import dbus import gobject SERVICE = "com.example.virtled" OBJECT = "/com/example/virtled/Manager" IFACE = "com.example.virtled.Manager" bus = dbus.SystemBus() def led_status(*args, **kwargs): led = bus.get_object(SERVICE, OBJECT) props_iface = dbus.Interface(led, 'org.freedesktop.DBus.Properties') properties = props_iface.GetAll(IFACE) print "*** LED STATE: ***" for k, v in properties.iteritems(): print "%s: %s" % (k, v) print if __name__ == '__main__': loop = gobject.MainLoop() led_status() bus.add_signal_receiver(led_status, dbus_interface=IFACE, signal_name='StateChange') loop.run()
#def system_resumed(*args): # alert("System resumed") # run_prey() ####################### # main ####################### if __name__ == '__main__': log("Initializing") run_at = None # Setup message bus. bus = dbus.SystemBus(mainloop=DBusGMainLoop()) # Connect to StateChanged signal from NetworkManager try: nm = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager') nm_interface = dbus.Interface(nm, 'org.freedesktop.NetworkManager') nm_interface.connect_to_signal('StateChanged', network_state_changed) except dbus.exceptions.DBusException: print "NetworkManager DBus interface not found! Please make sure NM is installed." sys.exit(1) if connected(): run_prey() # upower = bus.get_object('org.freedesktop.UPower', '/org/freedesktop/UPower') # if upower.CanSuspend:
def listen_for_restarts(self): # If we have a mainloop, listen for disconnections if not NMDbusInterface.last_disconnect and dbus.get_default_main_loop(): dbus.SystemBus().add_signal_receiver(self.handle_restart, 'NameOwnerChanged', 'org.freedesktop.DBus') NMDbusInterface.last_disconnect = 1
def setUpModule(): try: env = os.environ.copy() env['PATH'] = env['PATH'] + ":/usr/local/bin" # Run init_tpm_server and tpm_serverd (start fresh) its = subprocess.Popen(["init_tpm_server"], shell=False, env=env) its.wait() tsd = subprocess.Popen(["tpm_serverd"], shell=False, env=env) tsd.wait() except Exception: print("WARNING: Restarting TPM emulator failed!") # Note: the following is required as abrmd is failing to reconnect to MSSIM, once # MSSIM is killed and restarted. If this is an proved an actual bug and is # fixed upstream, the following dbus restart call can be removed. try: sysbus = dbus.SystemBus() systemd1 = sysbus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1') manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager') # If the systemd service exists, let's restart it. for service in sysbus.list_names(): if "com.intel.tss2.Tabrmd" in service: print("Found dbus service:", str(service)) try: print("Restarting tpm2-abrmd.service.") manager.RestartUnit('tpm2-abrmd.service', 'fail') except dbus.exceptions.DBusException as e: print(e) except Exception: print("Non systemd agent detected, no tpm2-abrmd restart required.") try: # Start with a clean slate for this test fileRemove(config.WORK_DIR + "/tpmdata.yaml") fileRemove(config.WORK_DIR + "/cv_data.sqlite") fileRemove(config.WORK_DIR + "/reg_data.sqlite") shutil.rmtree(config.WORK_DIR + "/cv_ca", True) except Exception: print("WARNING: Cleanup of TPM files failed!") # CV must be run first to create CA and certs! launch_cloudverifier() launch_registrar() # launch_cloudagent() # Make the Tenant do a lot of set-up work for us global tenant_templ tenant_templ = tenant.Tenant() tenant_templ.agent_uuid = config.get('cloud_agent', 'agent_uuid') tenant_templ.cloudagent_ip = "localhost" tenant_templ.cloudagent_port = config.get('cloud_agent', 'cloudagent_port') tenant_templ.verifier_ip = config.get('cloud_verifier', 'cloudverifier_ip') tenant_templ.verifier_port = config.get('cloud_verifier', 'cloudverifier_port') tenant_templ.registrar_ip = config.get('registrar', 'registrar_ip') tenant_templ.registrar_boot_port = config.get('registrar', 'registrar_port') tenant_templ.registrar_tls_boot_port = config.get('registrar', 'registrar_tls_port') tenant_templ.registrar_base_url = f'{tenant_templ.registrar_ip}:{tenant_templ.registrar_boot_port}' tenant_templ.registrar_base_tls_url = f'{tenant_templ.registrar_ip}:{tenant_templ.registrar_tls_boot_port}' tenant_templ.agent_base_url = f'{tenant_templ.cloudagent_ip}:{tenant_templ.cloudagent_port}' tenant_templ.supported_version = "2.0" # Set up TLS tenant_templ.cert, tenant_templ.agent_cert = tenant_templ.get_tls_context()