温馨提示×

ubuntu tigervnc配置步骤

小樊
43
2025-12-18 22:00:32
栏目: 智能运维

Ubuntu 上 TigerVNC 配置步骤

一 准备与安装

  • 更新索引并安装组件(桌面环境需已安装,如未安装请先安装桌面):
    • sudo apt update
    • sudo apt install tigervnc-standalone-server tigervnc-common
  • 为当前用户设置 VNC 访问密码(不要使用 sudo 执行):
    • vncpasswd
  • 说明:VNC 会话编号与端口关系为“:1 → 5901”,“:2 → 5902”,以此类推。

二 配置桌面与会话启动脚本

  • 首次运行以生成 ~/.vnc 配置目录(如不存在可先执行一次 vncserver 再编辑):
    • vncserver
    • vncserver -kill :1
  • 编辑会话启动脚本 ~/.vnc/xstartup,按所用桌面选择其一:

Xfce(轻量稳定,推荐服务器场景)

#!/bin/sh
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
exec startxfce4

GNOME(Ubuntu 默认)

#!/bin/sh
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
export XKL_XMODMAP_DISABLE=1
[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &
gnome-session &
  • 赋予执行权限:chmod +x ~/.vnc/xstartup。

三 启动与验证

  • 启动会话(示例:显示号 :1,分辨率 1920x1080,颜色 32 位):
    • vncserver :1 -geometry 1920x1080 -depth 32
  • 常用管理命令:
    • 查看:vncserver -list
    • 停止:vncserver -kill :1
  • 若仅监听 127.0.0.1,外部无法直连,请改用:
    • vncserver :1 -localhost no -geometry 1920x1080 -depth 32
  • 防火墙放行(如使用 UFW):
    • sudo ufw allow 5901/tcp

四 安全连接与开机自启

  • SSH 隧道加密(推荐)
    • 本地端口转发:ssh -L 5901:localhost:5901 -C -N -l <用户名> <服务器IP>
    • 客户端连接:localhost:1(通过隧道后即为加密传输)
  • systemd 服务自启(以 :1 为例,按需修改用户与分辨率)
    • 新建服务文件:sudo nano /etc/systemd/system/vncserver@.service
    • 示例内容(适配 Ubuntu 22.04,使用 -localhost no 时请谨慎开放到公网):
[Unit]
Description=Start TigerVNC server at startup
After=syslog.target network.target

[Service]
Type=forking
User=<你的用户名>
Group=<你的用户名>
WorkingDirectory=/home/<你的用户名>
PIDFile=/home/<你的用户名>/.vnc/%H:590%i.pid
ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
ExecStart=/usr/bin/vncserver -depth 32 -geometry 1920x1080 -localhost no :%i
ExecStop=/usr/bin/vncserver -kill :%i

[Install]
WantedBy=multi-user.target
  • 启用与启动:
    • sudo systemctl daemon-reload
    • sudo systemctl enable --now vncserver@1.service
    • sudo systemctl status vncserver@1.service

五 常见问题与排查

  • 连接被拒绝或“connection refused”:检查端口监听是否为 0.0.0.0:5901 而非仅 127.0.0.1;必要时用 -localhost no 启动,并确认云服务器安全组/本机防火墙已放行 5901/tcp
  • 黑屏/灰屏:确认 ~/.vnc/xstartup 中启动了正确的桌面(exec startxfce4 或 gnome-session &),且文件具备可执行权限。
  • 客户端报“Failed to connect to RFB server”:核对显示号与端口映射(:1→5901),以及服务是否已运行(vncserver -list)。
  • 多用户/多实例:每个实例使用不同显示号(:1、:2…),对应不同端口(5901、5902…),并为每个用户分别配置 xstartup 与 systemd 服务。

0