X11-Forwarding allows you to execute graphical programs remotely and forward the display to your local machine. This can be done via SSH and requires specific permission and configuration.
You could be switching your user to other users such as root if you're doing system administration work, and X11-Forwarding will fail with Can't open display, or X11 connection rejected because of wrong authentication errors.
$ sudo xclock [sudo] password for user: X11 connection rejected because of wrong authentication. Error: Can't open display: localhost:10.0
This is because X11-Forwarding using SSH requires the correct value for ~/.Xauthority file and DISPLAY environment variable, which is only automatically set for the users directly connecting to the remote host, and not for the user that the initial user switches to.
Steps to use SSH X11-Forwarding for sudo or su:
- Make sure you're already able to run graphical program via SSH X tunneling as normal user.
- Connect to SSH server with X11-Forwarding enabled.
$ ssh -X remote-host user@remote-host's password: Welcome to Ubuntu 20.10 (GNU/Linux 5.8.0-26-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage 0 updates can be installed immediately. 0 of these updates are security updates. Last login: Sun Nov 1 21:17:13 2020 from 192.168.111.27
- Get X authorization entry for current display.
$ xauth list $DISPLAY host/unix:10 MIT-MAGIC-COOKIE-1 742d024faeb3d29a15ff06f1b8c3b21e
This info is stored in ~/.Xauthority file.
$ cat ~/.Xauthority host10MIT-MAGIC-COOKIE-1t-O��Қ��ò
- Get DISPLAY environment variable value.
$ echo $DISPLAY localhost:10.0
- Switch to root or other user using sudo and/or su.
$ sudo su - [sudo] password for user: root@host:~#
- Generate ~/.Xauthority file using xauth command.
# xauth add host/unix:10 MIT-MAGIC-COOKIE-1 742d024faeb3d29a15ff06f1b8c3b21e
- Check .Xauthority file to confirm.
# cat ~/.Xauthority host10MIT-MAGIC-COOKIE-1t-O��Қ��ò
- Export DISPLAY environment variable value for current user.
# export DISPLAY=localhost:10.0
- Run X program.
# xclock
Mohd Shakir Zakaria is an experienced cloud architect with a strong development and open-source advocacy background. He boasts multiple certifications in AWS, Red Hat, VMware, ITIL, and Linux, underscoring his expertise in cloud architecture and system administration.
Comment anonymously. Login not required.