Using Magic Cookies to run programs remotely as root


Some magic cookies

Unbelievable how many times I fell for this – and am still falling.

The situation is as follows: you are on a remote box, using SSH and X-forwarding enabled. You can run any graphical program (say, wireshark) as that user, but as soon as you try prepending sudo you get: (wireshark:8881): Gtk-WARNING **: cannot open display: .

If you’ve been following me for long enough, you know I’ve been bitten already by a similar problem in the past. The only (minor) difference is that this time I don’t even have a DISPLAY variable set (as root).

So here’s another fix, this time using magic cookies.

Step 1, as normal user type echo $(xauth list ${DISPLAY#localhost}). You’ll get something like this back: machine/unix:25 MIT-MAGIC-COOKIE-1 41f6c7f04a706ca5e490b3edf8a26491

Step 2, as root, run xauth add followed by the line you got as output on the shell, that is: xauth add machine/unix:25 MIT-MAGIC-COOKIE-1 41f6c7f04a706ca5e490b3edf8a26491.

Exit the root shell, confidently type sudo DISPLAY="localhost:25.0"
and enjoy!

Cannot run a program as root because you “Cannot open display”

Say you’re trying a program as root. You sudo, you type the program name and then… bang.

(wireshark:2901): Gtk-WARNING **: cannot open display: localhost:30.0

Here’s the fix: remember the “localhost:30.0”, sudo into a root shell, run xauth to create/merge root’s Xauthority file and use the same display:

sudo -i
xauth merge ~your_username/.Xauthority
export DISPLAY=localhost:30.0

If you don’t get the display name (in the error message) when first running the program, you can retrieve it by echoing $DISPLAY.