5.2. Running X Programs as root

Problem

While logged in as a normal user, you need to run an X window application as root. You get this error message:

 ** WARNING ** cannot open display

Solution

Create a shell script called, say, xsu:

#!/bin/sh
su - -c "exec env DISPLAY='$DISPLAY' \
        XAUTHORITY='${XAUTHORITY-$HOME/.Xauthority}' \
        "'"$SHELL"'" -c '$*'"

and run it with the desired command as its argument list:

# xsu  ...command line...

Discussion

The problem is that root’s .Xauthority file does not have the proper authorization credentials to access your X display.

This script invokes a login shell [Recipe 5.1] and the env program sets the environment variables DISPLAY and XAUTHORITY. The values are set to be the same as the invoking user’s. Otherwise they would be set to root’s values, but root doesn’t own the display.

So in this solution, XAUTHORITY remains ~user/.Xauthority instead of changing to ~root/.Xauthority. Since root can read any user’s .Xauthority file, including this one, it works.

This trick will not work if the user’s home directory is NFS-mounted without remote root access.

See Also

env(1), su(1), xauth(1).

Get Linux Security Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.