阿男的小窝

View the Project on GitHub

关于VNC和ssh tunnel的一些使用经验

在Fedora Linux下安装下面的vnc客户端与服务端:

$ sudo dnf install tigervnc*

XFce作为VNC的远程桌面环境是不错的选择,在Fedora Linux下可以使用下面的命令安装:

$ sudo dnf install @xfce-desktop-environment

第一次启动vnc server:

$ vncserver :1

注意不需要sudo。第一次运行vncserver,会产生一些初始的配置文件,我们要配置vnc server使用xfce。此时先把server停掉:

$ vncserver -kill :1

然后编辑~/.vnc/xstartup这个文件:

$ cat ~/.vnc/xstartup
#!/bin/sh

unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
#exec /etc/X11/xinit/xinitrc
exec /bin/sh /etc/xdg/xfce4/xinitrc

注意我们把vncserver默认的/etc/X11/xinit/xinitrc换成了/etc/xdg/xfce4/xinitrc。更改完配置以后,重新启动服务器,可以看到此时远程砖面环境变成了Xfce:

使用vnc server,最好通过ssh tunnel来访问,这样比较安全。在Linux/MacOS下面建立ssh tunnel的命令如下:

$ ssh -v -C -L 590N:localhost:590M remote_host

注意端口号和启动vnc server的参数相关,如果是:1,那么端口号就是5901,依此类推。remote_host就是运行了vnc server的远程主机的ip地址(或者是域名)。

如果在Windows下,可以使用PuTTY来配置SSH Tunnel:

最后,我们可以看一下Fedora Linux当中,VNC Service的定义:

$ cat /usr/lib/systemd/system/vncserver@.service
# The vncserver service unit file
#
# Quick HowTo:
# 1. Copy this file to /etc/systemd/system/vncserver@.service
# 2. Replace <USER> with the actual user name and edit vncserver
#    parameters appropriately
#    (ExecStart=/usr/sbin/runuser -l <USER> -c "/usr/bin/vncserver %i"
#     PIDFile=/home/<USER>/.vnc/%H%i.pid)
# 3. Run `systemctl daemon-reload`
# 4. Run `systemctl enable vncserver@:<display>.service`
#
# DO NOT RUN THIS SERVICE if your local area network is
# untrusted!  For a secure way of using VNC, you should
# limit connections to the local host and then tunnel from
# the machine you want to view VNC on (host A) to the machine
# whose VNC output you want to view (host B)
#
# [user@hostA ~]$ ssh -v -C -L 590N:localhost:590M hostB
#
# this will open a connection on port 590N of your hostA to hostB's port 590M
# (in fact, it ssh-connects to hostB and then connects to localhost (on hostB).
# See the ssh man page for details on port forwarding)
#
# You can then point a VNC client on hostA at vncdisplay N of localhost and with
# the help of ssh, you end up seeing what hostB makes available on port 590M
#
# Use "-nolisten tcp" to prevent X connections to your VNC server via TCP.
#
# Use "-localhost" to prevent remote VNC clients connecting except when
# doing so through a secure tunnel.  See the "-via" option in the
# `man vncviewer' manual page.


[Unit]
Description=Remote desktop service (VNC)
After=syslog.target network.target

[Service]
Type=forking

# Clean any existing files in /tmp/.X11-unix environment
ExecStartPre=/bin/sh -c '/usr/bin/vncserver -kill %i > /dev/null 2>&1 || :'
ExecStart=/usr/sbin/runuser -l <USER> -c "/usr/bin/vncserver %i"
PIDFile=/home/<USER>/.vnc/%H%i.pid
ExecStop=/bin/sh -c '/usr/bin/vncserver -kill %i > /dev/null 2>&1 || :'

[Install]
WantedBy=multi-user.target

上面的service文件里面,文档说明很清晰,建议阅读。

以上就是VNC Server的一些使用心得。