How to get graphical display when executing commands as another user, through terminal? [duplicate]

Solution 1:

Running Graphical Commands from Another User's Shell

The sux Install sux command (see man sux) takes care of this for you, and takes the same syntax as su.

sux - nextuser
gedit test.c

This will automatically ensure the .Xauthority is correct, so you don't have to run any commands to manually authorize anything.

Graphical applications tend to write configuration files in your home directory, and if you run them as another user while preserving $HOME, they'll attempt to write configuration files as that user, in your home directory. This will result in failing to write the configuration, or the configuration getting messed up for the original user (or some combination of the two). That's why it's advisable to use the - flag with sux (or su) when running graphical applications. (For sudo, you can instead use graphical frontends like gksu/gksudo and kdesudo.)

Running Graphical Commands Directly as Another User

You can use gksu in su-mode (with the -w flag) to run the command as another user (with the -u flag):

gksu -w -u nextuser gedit test.c

However, you might still have to run xhost local:nextuser first (as you detailed in your quite good answer) for this to work. It's less likely to need that if you use sudo-mode, but then you can only do it if you're an administrator (and you'll be authenticating with your password rather than nextuser's password, as sudo rather than su is the backend):

gksu -u nextuer gedit test.c

Running the Terminal (Not Just the Shell) as Another User

You may just want to run the graphical Terminal program (that the shell runs "inside") as the other user. Once it's running, graphical programs launched from it will work seamlessly as well.

You can use the same methods described above for running gedit as the other user.

gksu -w -u nextuser gnome-terminal
gksu -u nextuser gnome-terminal

Solution 2:

As root, run

echo $DISPLAY
xhost local:nextuser

Then

su - nextuser
export DISPLAY=<the value got from echo $DISPLAY above>
(or SET DISPLAY.. if export does not work)

And you are good to go. :)

Solution 3:

Use the -p option with su to preserve environment variables including DISPLAY; alternately set it explicitly with export or prefix it on a per command basis.