X Window 设计之初即支持跨网络:X Client 是需图形显示的应用程序,X Server 负责显示与用户交互,二者通信协议称为 X Protocol。本文详述基于主机验证与用户验证的两种配置方式,并解决常见 Error: can't open display! 问题。
$ xhost +192.168.0.1 # 允许该 IP 发送 X Request
$ xhost -192.168.0.1 # 取消授权
$ xhost + # 允许所有主机
$ xhost - # 取消允许所有
也可在 /etc/X*.hosts 永久添加授权主机(* 为显示编号,如 X0.hosts)。
ssh 或 telnet 到 X Client 机器,运行 X 程序并指定显示:
$ xeyes -display 192.168.0.254:0
# 或导出 DISPLAY 环境变量
$ export DISPLAY=192.168.0.254:0
一台机器可启动多个显示屏幕(默认 :0),可修改 /etc/X11/gdm/gdm.conf 或用 startx -- :1 指定。
核心步骤:在 X Server 端生成用户 cookie,再将 cookie 传给 X Client。
$ xauth
Using authority file /home/yingyuan/.Xauthority
xauth> list
xauth> add 192.168.0.199:0 MIT-MAGIC-COOKIE-1 8432567fa3ae2341
xauth> exit
~/.Xauthority 从 Server 到 Client。xauth extract 导出,merge 导入。xauth add 添加。DISPLAY 环境变量格式: hostname:displaynumber.screennumber。本地 Unix socket 连接时 hostname 为空,displaynumber 对应 /tmp/.X11-unix/X0。
su 切换用户后运行图形程序报错: 需在原用户下执行 xhost + 允许其他用户显示。
SSH X11 转发: 服务端 /etc/ssh/sshd_config 设 X11Forwarding yes,客户端 /etc/ssh/ssh_config 设 ForwardX11 yes,ssh 后自动设置 DISPLAY(如 localhost:10.0)。
开启 X Server TCP 端口监听: 修改 /etc/X11/xinit/xserverrc 移除 -nolisten tcp;KDM 修改 ServerArgsLocal;GDM 在 [Security] 加 DisallowTCP=false。