Cannot connect to X Server when running app with sudo

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.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

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

Solution 4

Actually the code you are running has cv2.imshow() or any other display commands, for remote running of code you have to comment them, and better save for visualization.

Solution 5

set DISPLAY and XAUTHORITY variable environment before running your scrip.
for example in systemctl service file:

[Unit]
Description=Start Clock

[Service]
Environment=DISPLAY=:0
Environment=XAUTHORITY=/home/pi/.Xauthority
ExecStart=/usr/bin/python3 /home/pi/clock.py
Restart=always
RestartSec=10s
KillMode=process
TimeoutSec=infinity

[Install]
WantedBy=graphical.target

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply