萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

解決 Linux xhost "unable to open display" 錯誤的三種實戰方案

問題背景

在 Linux 文字介面或 SSH 連線中執行 xhost + 時,常遇到 unable to open display 錯誤。根本原因是 X Server 未啟動、DISPLAY 環境變數未正確設定、或 X11 Forwarding 未開啟。本文提供三種經驗證可行的解決方案。

方案一:使用 VNC Server 建立虛擬桌面 (最推薦)

適用於無實體螢幕的伺服器環境,透過 VNC 建立虛擬 X Server。

  1. 啟動 VNC Server:
    [root@localhost ~]# vncserver
    New 'localhost:1 (root)' desktop is localhost:1
    Starting applications specified in /root/.vnc/xstartup
    Log file is /root/.vnc/localhost:1.log
  2. 匯出 DISPLAY 變數:
    export DISPLAY=localhost:1
  3. 執行 xhost:
    [root@localhost ~]# xhost +
    access control disabled, clients can connect from any host
VNC 方案操作截圖

此法解決 90% 以上無圖形介面環境下的 xhost 需求 (如 Oracle 安裝前置作業)。

方案二:查詢現有 X Server 的 Display 編號並匯出

適用於已有圖形介面 (GNOME/KDE) 運行的本機或已開啟 X11 Forwarding 的 SSH 連線。

  1. 以 root 登入,查詢 Display 編號:
    xdpyinfo | grep "name of display"
    # 輸出範例:name of display: 127.0.0.1:1.0
  2. 匯出對應的 DISPLAY:
    export DISPLAY=:1.0   # 或 export DISPLAY=127.0.0.1:1.0
  3. 驗證:
    xhost +
    # 成功顯示:access control disabled, clients can connect from any host

若 xhost + 仍失敗,嘗試 export DISPLAY=:0 (第 0 號顯示器) 再試。

xdpyinfo 查詢示意

切換使用者情境 (如 root 切換至 oracle)

  1. root 環境下取得 name of display: 127.0.0.1:1.0
  2. 切換至 oracle:su - oracle
  3. 匯出:export DISPLAY=127.0.0.1:1.0 (或 :1.0)
  4. 驗證:xdpyinfo 能輸出資訊即成功

方案三:使用 Xshell + X11 Forwarding (Windows 客戶端)

適用於從 Windows 透過 SSH 連線 Linux,並需在遠端執行圖形化安裝程式 (如 Oracle Universal Installer)。

  1. 下載安裝 Xshell 5/6/7 及 Xmanager (或 VcXsrv、Xming 等 X Server)。
  2. Xshell 連線屬性 → SSH → Tunneling → 勾選 "Forward X11 connections"。
  3. 連線登入 Linux,系統自動設定 DISPLAY=localhost:10.0 等。
  4. 直接執行 xhost + 或圖形化安裝程式。
Xshell 選擇連線
Xshell 輸入帳號
Xshell 輸入密碼
Xshell 確認連線
Xshell 連線成功
Xshell 終端機畫面
startx 提示資訊

常見誤區與檢查清單

  • SSH 伺服端設定:/etc/ssh/sshd_config 需確認 X11Forwarding yes 且 X11UseLocalhost no (視情況),修改後 service sshd restart。
  • xauth 套件:遠端主機需安裝 xauth (yum install xauth),否則 X11 Forwarding 會失效。
  • 防火牆:確認 TCP 6000+n (X11 port) 未被封鎖,或走 SSH Tunnel 已自動繞過。
  • 不要混用:同一終端機勿同時匯出多個衝突的 DISPLAY,建議每次新增終端機重新匯出。

總結

場景推薦方案關鍵指令
無圖形介面伺服器 (Oracle 安裝等)VNC Servervncserver → export DISPLAY=localhost:1 → xhost +
本機有桌面 / SSH 已開 X11 Forwarding查詢現有 Displayxdpyinfo → export DISPLAY=:n.m → xhost +
Windows 客戶端需遠端圖形化操作Xshell + Xmanager/VcXsrv開啟 SSH X11 Forwarding → 直接執行圖形程式

依據實際環境選擇對應方案,即可徹底解決 xhost: unable to open display 問題。

copyright © 萬盛學電腦網 all rights reserved