Friday, December 10, 2010

SSH and DBUS Sessions

Applications that need access to the current D-BUS session bus, require special attention when launched from within an SSH session.

Sometimes it's enough to just set the DISPLAY environment variable to the appropriate X display number (e.g. localhost:0.0, or localhost:10.0 - the default when forwarding X connections over SSH), but it's usually not enough.

These applications need to know the so called D-BUS session bus address. This may be scraped from the environment of applications that are already running, and do have access to the session bus, as the value of DBUS_SESSION_ADDRESS, like this:
export $(strings /proc/*/environ| grep DBUS_SESSION | tail -1)
But there may be several possible values when more than one X session is used, and you'll need to select the right one, maybe by also matching the value of DISPLAY.

There is, however, a somewhat cleaner way to do this. The D-BUS environment variables may be set by running one of the machine generated files under ~/.dbus/session-bus - the files there all have names like 479864458729b195d5497c4bb663c100-10, where the string of hexadecimal digits before the dash is the machine UUID and the number after the dash is the X display number.

Here's how I do it in my ~/.bashrc:
session="$HOME/.dbus/session-bus/$(dbus-uuidgen --get)-$(echo $DISPLAY | sed -e 's/\([^:]*:\)//g' -e 's/\..*$//g')"
if [ -e $session ] ; then
    source $session


  1. Great, I'm using your code snippet as well.

  2. Thanks, exactly what I needed.