Skip to content

Instantly share code, notes, and snippets.

@AsavarTzeth
Created May 2, 2017 10:05
Show Gist options
  • Save AsavarTzeth/15f85c09d35ce6fa0c6f6135fbf52b89 to your computer and use it in GitHub Desktop.
Save AsavarTzeth/15f85c09d35ce6fa0c6f6135fbf52b89 to your computer and use it in GitHub Desktop.
File used for testing ansible dconf module
#!/bin/python
import os
import psutil
import subprocess
def _get_existing_dbus_session():
"""
Detects and returns as existing D-Bus session bus address.
:returns: string -- D-Bus session bus address. If a running D-Bus session was not detected, returns None.
"""
# We'll be checking the processes of current user only.
uid = os.getuid()
# Go through all the pids for this user, try to extract the D-Bus
# session bus address from environment, and ensure it is possible to
# connect to it.
print ("Trying to detect existing D-Bus user session for user: %d" % uid)
for pid in psutil.pids():
process = psutil.Process(pid)
process_real_uid, _, _ = process.uids()
try:
if process_real_uid == uid and 'DBUS_SESSION_BUS_ADDRESS' in process.environ():
dbus_session_bus_address_candidate = process.environ()['DBUS_SESSION_BUS_ADDRESS']
print ("Found D-Bus user session candidate at address: %s" % dbus_session_bus_address_candidate)
command = ['dbus-send', '--address=%s' % dbus_session_bus_address_candidate, '--type=signal', '/', 'com.example.test']
rc = subprocess.call(command)
if rc == 0:
print ("Verified D-Bus user session candidate as usable at address: %s" % dbus_session_bus_address_candidate)
return dbus_session_bus_address_candidate
# This can happen with things like SSH sessions etc.
except psutil.AccessDenied:
pass
print ("Failed to find running D-Bus user session, will have to start one of our own")
return None
print (_get_existing_dbus_session())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment