Allowing access to X when running sudo

When using sudo to attempt to run programs it is quite common to receive the following error message :

Xlib: connection to ":0.0" refused by server
Xlib: No protocol specified

Unable to import modules.  Maybe you're not running under X?

Here's an explanation of why you get this message and what you need to do to allow the root user to run X programs when using sudo.

When X first logs in to a user, it creates the .Xauthority file in that users home directory and fills it with a random string called a MIT-MAGIC-COOKIE. Any X client, by default, reads that file to see what the cookie is then sends it to the X server to authenticate itself.

Anyone who can read that file can access the display so that file is normally only readable by the user who logged in, though root can always read it because root is god. When you run an X program as a different user, it will look in that users home directory for the .Xauthority file and so won't be able to find the right cookie unless you used the xauth command to give that user the cookie ahead of time. By setting the XAUTHORITY environment variable to some other file, it will check that file for the magic cookie instead of the current users home directory.

This is useful when running a command as root that you want to access a normal users X server. This is a much more secure way to allow access to X than using xhost since you know what users are able to access X, not just which computers, which may have multiple users on them.

In summary, don't touch xhost, just use:

# XAUTHORITY=/home/user/.Xauthority xscreensaver

or you can use xauth to extract the magic cookie and then import it into the correct users .Xauthority file. As the user of the X server:

# xauth extract my-cookie-file $DISPLAY

Saves the magic cookie to a file called my-cookie-file for the current display. Then as the user who want to access the X display (ie as root):

$ xauth merge my-cookie-file

Adds the cookie stored in my-cookie file to the current users .Xauthority file. Now user B can open an X application on A's X server.