Cannot connect to X Server when running app with sudo

267,530

Solution 1

You need to allow the root user access to the X server:

xhost local:root

And point the command to the right DISPLAY:

sudo DISPLAY=$DISPLAY gedit /etc/profile

Solution 2

Finally the problem is solved. I have just added the line:

Defaults env_keep="DISPLAY XAUTHORITY"

at the end of visudo.

To do that you have to run

sudo visudo

it will open the file then add the above line at the end.

Thanks to all, specially @Thor for kind help

Solution 3

Supplementing @Thor's answer:

Run xhost local:root before sudo gedit. To make this permanent, add the line

xhost local:root

to the file ~/.xinitrc 1. Create the file if it doesn't exist.


[1] https://askubuntu.com/a/720120/452398

Share:
267,530

Related videos on Youtube

noobcoder
Author by

noobcoder

PhD student at Department of Physics, IISc.

Updated on September 18, 2022

Comments

  • noobcoder
    noobcoder over 1 year

    When I am running some software using sudo command it showing error like

    cannot connect to X server
    

    For example if I run the following command:

    $ sudo gedit /etc/profile
    

    I am getting following command

    (gedit:6758): WARNING **: Command line `dbus-launch --autolaunch=84b871d735f31ffe014dc9ba00000009 --binary-syntax --close-stderr' 
    exited with non-zero exit status 1: 
    Autolaunch error: X11 initialization failed. 
    Cannot open display:
    Run 'gedit --help' to see a full list of available command line options.
    

    Or if I am running super-boot-manager I am getting following error

    buc: cannot connect to X server
    

    Please help.

  • noobcoder
    noobcoder over 11 years
    That solved the problem with opening gedit as sudo, but still can't lunch super-boot-manager. It is showing same error
  • sugab
    sugab about 9 years
    Defaults env_keep="DISPLAY" works for me.
  • Ev-
    Ev- over 7 years
    I have been searching high and low for this answer forever. I wish I could upvote both of you multiple times for your answers. Thank you so very much! :)
  • user1927105
    user1927105 over 5 years
    Thank you for providing an answer that provides a non-permanent solution.
  • jpaugh
    jpaugh almost 4 years
    I've just learned that sudo -H should be used when starting graphical applications, to avoid file corruption of X-related files.
  • Joerg S
    Joerg S over 3 years
    setting the DISPLAY in sudo was not even required for me - Debian Buster.
  • user508402
    user508402 over 2 years
    How can I make this permanent?
  • Thor
    Thor over 2 years
    @user508402: that depends on many things. You should probably post this as a new question, where you detail your current setup, i.e. shell, window manager etc.