通过 TigerVNC 远程控制 Ubuntu 的完整步骤
一 环境准备与安装
- 更新索引并安装桌面环境(无图形界面的服务器才需要):
- Ubuntu 桌面版通常已自带桌面;服务器版建议安装轻量桌面(如 Xfce)或 ubuntu-desktop:
- 轻量方案:sudo apt install xfce4 xfce4-goodies
- 完整 GNOME:sudo apt install ubuntu-desktop
- 安装 TigerVNC 服务端:
- sudo apt install tigervnc-standalone-server tigervnc-common
- 为当前用户设置 VNC 登录密码(不要使用 sudo):
- 端口说明:显示编号 :1 对应端口 5901,:2 对应 5902,依此类推
二 配置桌面会话
三 启动与自启动
- 手动启动(首次或调试时)
- 启动桌面 :1:vncserver :1 -geometry 1600x900 -depth 24 -localhost no
- 查看实例:vncserver -list
- 关闭实例:vncserver -kill :1
- 开机自启动(systemd 模板,推荐)
- 新建:sudo nano /etc/systemd/system/vncserver@.service
- 内容(将 替换为你的用户名):
- [Unit]
- Description=Start TigerVNC server at startup
- After=syslog.target network.target
- [Service]
- Type=forking
- User=
- Group=
- WorkingDirectory=/home/
- PIDFile=/home//.vnc/%H:%i.pid
- ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
- ExecStart=/usr/bin/vncserver :%i -geometry 1600x900 -depth 24 -localhost no
- ExecStop=/usr/bin/vncserver -kill :%i
- [Install]
- WantedBy=multi-user.target
- 启用并启动:
- sudo systemctl daemon-reload
- sudo systemctl enable vncserver@1.service
- sudo systemctl start vncserver@1.service
- 防火墙放行(如启用 UFW)
- sudo ufw allow 5901/tcp && sudo ufw reload
四 客户端连接与安全加固
- 直连方式(仅在受信网络)
- 客户端输入:<服务器IP>:1(等价于端口 5901)
- 常见客户端:TigerVNC Viewer、RealVNC Viewer、Remmina
- SSH 隧道(更安全,推荐公网/不可信网络)
- 本地端口转发:ssh -L 5901:127.0.0.1:5901 @<SERVER_IP>
- 客户端连接:localhost:1
- 证书加密(可选,TigerVNC 支持 X.509)
- 生成证书(在服务器):
- *openssl req -x509 -newkey rsa -days 3650 -nodes -config /usr/lib/ssl/openssl.cnf *
- *-keyout ~/.vnc/vnc-server-private.pem -out ~/.vnc/vnc-server.pem *
- -subj ‘/CN=<服务器名称>’ -addext “subjectAltName=IP:x.x.x.x”
- 客户端配置:在 VNC Viewer 的 Security 选项中指定 CA 证书路径为 ~/.vnc/vnc-server.pem(Windows 可将证书与密码文件放到相应目录)
五 常见问题排查
- 连接超时/被拒绝
- 确认服务已启动:vncserver -list;检查端口:ss -tulnp | grep 5901
- 若只监听 127.0.0.1,启动时应加 -localhost no
- 防火墙/云安全组是否放行 5901/tcp
- 黑屏或无桌面
- 核对 ~/.vnc/xstartup 是否可执行且启动了正确桌面(如 exec startxfce4 或 GNOME 会话)
- 查看日志:cat ~/.vnc/*.log 定位报错
- 与物理显示器登录冲突
- 服务器场景可设为多用户目标:sudo systemctl set-default multi-user.target(释放 GPU/避免冲突)
- 剪贴板自动同步导致覆盖
- 在 ~/.vnc/config 增加:SendPrimary=0 与 SetPrimary=0,重启 VNC