One place for hosting & domains

      Cómo instalar y configurar VNC en Ubuntu 18.04


      Introducción

      Virtual Network Computing, o VNC, es un sistema de conexión que le permite usar su teclado y mouse para interactuar con un entorno de escritorio gráfico en un servidor remoto. Hace que administrar archivos, software y ajustes en un servidor remoto sea más fácil para los usuarios que aún no se sienten cómodos con la línea de comandos.

      En esta guía, configurará un servidor VNC en un servidor Ubuntu 18.04 y se conectará a él de forma segura a través de un túnel SSH. Usará TightVNC, un paquete de control remoto rápido y ligero. Esta opción garantizará que nuestra conexión VNC sea perfecta y estable, incluso en las conexiones a Internet más lentas.

      Requisitos previos

      Para completar este tutorial, necesitará lo siguiente:

      Paso 1: instalación del entorno de escritorio y el servidor VCN

      Por defecto, el servidor Ubuntu 18.04 no viene con un entorno de escritorio gráfico o un servidor VNC instalado, por lo que empezaremos por instalarlos. Específicamente, instalaremos paquetes para el entorno de escritorio Xfce más reciente y el paquete TightVNC disponible en el repositorio oficial de Ubuntu.

      En su servidor, actualice su lista de paquetes:

      Ahora, instale el entorno de escritorio Xfce en su servidor:

      • sudo apt install xfce4 xfce4-goodies

      Cuando finalice la instalación, instale el servidor TightVNC:

      • sudo apt install tightvncserver

      Para completar la configuración inicial del servidor VNC tras su instalación, utilice el comando vncserver para configurar una contraseña segura y crear los archivos de configuración iniciales:

      Se le indicará que introduzca y verifique una contraseña para acceder a su máquina de forma remota:

      Output

      You will require a password to access your desktops. Password: Verify:

      La contraseña debe tener entre seis y ocho caracteres de largo. Las contraseñas de más de 8 caracteres se reducirán automáticamente.

      Una vez que verifique la contraseña, tendrá la opción de crear una contraseña de solo vista. Los usuarios que inicien sesión con la contraseña de solo vista no podrán controlar la instancia de VNC con su mouse o teclado. Esta es una opción útil si desea demostrar algo a otras personas que utilizan su servidor VNC, pero no es un requisito necesario.

      Luego, el proceso crea los archivos de configuración predeterminados que se requieren y la información de conexión para el servidor:

      Output

      Would you like to enter a view-only password (y/n)? n xauth: file /home/sammy/.Xauthority does not exist New 'X' desktop is your_hostname:1 Creating default startup script /home/sammy/.vnc/xstartup Starting applications specified in /home/sammy/.vnc/xstartup Log file is /home/sammy/.vnc/your_hostname:1.log

      Ahora, vamos a configurar el servidor VNC.

      Paso 2: configuración del servidor VNC

      El servidor VNC debe saber qué comandos ejecutar cuando se inicia. Específicamente, VNC debe saber a qué escritorio gráfico deberá conectarse.

      Estos comandos se encuentran en un archivo de configuración llamado xstartup en la carpeta .vnc de su directorio principal. La secuencia de comandos de inicio se creó cuando ejecutó vncserver en el paso anterior, pero crearemos una propia para abrir el escritorio Xfce.

      Cuando VNC se configura por primera vez, se abre como una instancia del servidor predeterminada en el puerto 5901. Este puerto se llama puerto de visualización, y VNC se refiere a él como :1. VNC puede abrir múltiples instancias en otros puertos de visualización, como :2, :3, y así sucesivamente.

      Debido a que vamos a cambiar la configuración del servidor VNC, primero, detenga la instancia del servidor VNC que se está ejecutando en el puerto 5901 con el siguiente comando:

      El resultado debería tener este aspecto, pero verá un PID diferente:

      Output

      Killing Xtightvnc process ID 17648

      Antes de modificar el archivo xstartup, realice una copia de seguridad del original:

      • mv ~/.vnc/xstartup ~/.vnc/xstartup.bak

      Ahora, cree un nuevo archivo xstartup y ábralo en su editor de texto:

      Los comandos de este archivo se ejecutan automáticamente siempre que inicie o reinicie el servidor VNC. Necesitamos que VNC inicie nuestro entorno de escritorio, si aún no está iniciado. Añada estos comandos al archivo:

      ~/.vnc/xstartup

      #!/bin/bash xrdb $HOME/.Xresources startxfce4 &

      El primer comando del archivo, xrdb $HOME/. Xresources, le indica al marco de trabajo de la GUI de VNC que lea el archivo .Xresources del usuario del servidor. El archivo .Xresources es donde un usuario puede realizar cambios a ajustes concretos del escritorio gráfico, como los colores de la terminal, los temas del cursor y la renderización de fuentes. El segundo comando le indica al servidor que inicie Xfce, que es donde encontrará todo el software gráfico que necesita para administrar cómodamente su servidor.

      Para garantizar que el servidor VNC pueda usar este nuevo archivo de inicio correctamente, deberá hacerlo ejecutable.

      • sudo chmod +x ~/.vnc/xstartup

      Ahora, reinicie el servidor VNC.

      Visualizará un resultado similar al siguiente:

      Output

      New 'X' desktop is your_hostname:1 Starting applications specified in /home/sammy/.vnc/xstartup Log file is /home/sammy/.vnc/your_hostname:1.log

      Con la configuración establecida, vamos a conectar con el servidor desde nuestra máquina local.

      Paso 3: conexión segura del escritorio de VNC

      VNC no utiliza protocolos seguros cuando se conecta. Usaremos un túnel SSH para establecer una conexión segura con nuestro servidor y, luego, le indicaremos a nuestro cliente VNC que utilice ese túnel en vez de realizar una conexión directa.

      Cree una conexión SSH en su equipo local que se reenvíe de forma segura a la conexión localhost para VNC. Puede hacerlo a través de la terminal en Linux o macOS con el siguiente comando:

      • ssh -L 5901:127.0.0.1:5901 -C -N -l sammy your_server_ip

      El conmutador -L especifica las vinculaciones del puerto. En este caso, estamos vinculando el puerto 5901 de la conexión remota con el puerto 5901 de su máquina local. El conmutador -C permite la compresión, mientras que el conmutador -N le indica a ssh que no queremos ejecutar el comando remoto. El conmutador -l especifica el nombre de inicio de sesión remoto.

      Recuerde sustituir sammy y your_server_ipcon el nombre de usuario sudo no root y la dirección IP de su servidor.

      Si está usando un cliente SSH gráfico, como PuTTY, utilice your_server_ip para la conexión IP y establezca localhost:5901 como un nuevo puerto reenviado en los ajustes del túnel SSH del programa.

      Una vez que el túnel se esté ejecutando, utilice un cliente VNC para conectar a localhost:5901. Se le pedirá que autentique usando la contraseña que configuró en el Paso 1.

      Una vez conectado, verá el escritorio Xfce predeterminado. Debería tener un aspecto similar a esto:

      Conexión de VNC al servidor Ubuntu 18.04

      Puede acceder a los archivos en su directorio principal con el administrador de archivos o desde la línea de comandos, como se indica aquí:

      Archivos a través de la conexión de VNC a Ubuntu 18.04

      Pulse CTRL+C en su terminal para detener el túnel SSH y regresar a su instrucción. Esto también desconectará su sesión de VNC.

      A continuación, vamos a configurar nuestro servidor VNC como servicio.

      Paso 4: ejecución de VNC como servicio del sistema

      A continuación, configuraremos el servidor VNC como un servicio de systemd para poder iniciarlo, detenerlo y reiniciarlo según lo necesitemos, como cualquier otro servicio. Esto también garantizará que VNC se inicie al reiniciar su servidor.

      Primero, cree un nuevo archivo de unidad llamado /etc/systemd/system/vncserver@.service con el editor de texto de su preferencia:

      • sudo nano /etc/systemd/system/vncserver@.service

      El símbolo @ al final del nombre nos dejará pasar un argumento que podemos usar en la configuración del servicio. Lo usaremos para especificar el puerto de visualización de VNC que queremos usar cuando administremos el servicio.

      Añada las siguientes líneas al archivo. Asegúrese de cambiar el valor de User, Group, WorkingDirectory y el nombre de usuario en el valor de PIDFILE para que coincidan con su nombre de usuario:

      /etc/systemd/system/vncserver@.service

      [Unit] Description=Start TightVNC server at startup After=syslog.target network.target [Service] Type=forking User=sammy Group=sammy WorkingDirectory=/home/sammy PIDFile=/home/sammy/.vnc/%H:%i.pid ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1 ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :%i ExecStop=/usr/bin/vncserver -kill :%i [Install] WantedBy=multi-user.target

      El comando ExecStartPre detiene VNC si ya se está ejecutando. El comando ExecStart inicia VNC y establece la profundidad del color a color de 24 bits con una resolución de 1280 x 800. También puede modificar estas opciones de inicio según sus necesidades.

      Guarde y cierre el archivo.

      A continuación, informe al sistema la existencia de un nuevo archivo de unidad.

      • sudo systemctl daemon-reload

      Habilite el archivo de unidad.

      • sudo systemctl enable vncserver@1.service

      El 1 tras el signo @ indica en qué número de pantalla debe aparecer el servicio, en este caso, el valor predeterminado es :1,como se explicó en el paso 2.

      Detenga la instancia actual del servidor VNC si aún se está ejecutando.

      Luego, inícielo como iniciaría cualquier otro servicio de systemd.

      • sudo systemctl start vncserver@1

      Puede verificar si ha comenzado con este comando:

      • sudo systemctl status vncserver@1

      Si se inició correctamente, el resultado debería verse así:

      Output

      ● vncserver@1.service - Start TightVNC server at startup Loaded: loaded (/etc/systemd/system/vncserver@.service; indirect; vendor preset: enabled) Active: active (running) since Mon 2018-07-09 18:13:53 UTC; 2min 14s ago Process: 22322 ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :1 (code=exited, status=0/SUCCESS) Process: 22316 ExecStartPre=/usr/bin/vncserver -kill :1 > /dev/null 2>&1 (code=exited, status=0/SUCCESS) Main PID: 22330 (Xtightvnc) ...

      Ahora, su servidor VNC estará disponible cuando reinicie la máquina.

      Inicie su túnel SSH de nuevo:

      • ssh -L 5901:127.0.0.1:5901 -C -N -l sammy your_server_ip

      Luego, realice una nueva conexión usando el software de su cliente VNC con localhost:5901 para conectarse con su máquina.

      Conclusión

      Ahora, tiene un servidor VNC seguro funcionando en su servidor Ubuntu 18.04. Ya puede administrar sus archivos, software y ajustes con una interfaz gráfica familiar y fácil de usar, y puede ejecutar software gráfico, como navegadores web, de forma remota.



      Source link

      How to Install and Configure VNC on Debian 10


      Introduction

      Virtual Network Computing, or VNC, is a connection system that allows you to use your keyboard and mouse to interact with a graphical desktop environment on a remote server. It makes managing files, software, and settings on a remote server easier for users who are not yet comfortable with the command line.

      In this guide, you’ll set up a VNC server on a Debian 10 server and connect to it securely through an SSH tunnel. You’ll use TightVNC, a fast and lightweight remote control package. This choice will ensure that our VNC connection will be smooth and stable even on slower internet connections.

      Prerequisites

      To complete this tutorial, you’ll need:

      • One Debian 10 server set up by following the Debian 10 initial server setup guide, including a non-root user with sudo access and a firewall.
      • A local computer with a VNC client installed that supports VNC connections over SSH tunnels.
        • On Windows, you can use TightVNC, RealVNC, or UltraVNC.
        • On macOS, you can use the built-in Screen Sharing program, or can use a cross-platform app like RealVNC.
        • On Linux, you can choose from many options, including vinagre, krdc, RealVNC, or TightVNC.

      Step 1 — Installing the Desktop Environment and VNC Server

      By default, a Debian 10 server does not come with a graphical desktop environment or a VNC server installed, so we’ll begin by installing those. Specifically, we will install packages for the latest Xfce desktop environment and the TightVNC package available in the official Debian repository.

      On your server, update your list of packages:

      Now install the Xfce desktop environment on your server:

      • sudo apt install xfce4 xfce4-goodies

      During the installation, you’ll be prompted to select your keyboard layout from a list of possible options. Choose the one that’s appropriate for your language and press Enter. The installation will continue.

      Once the installation completes, install the TightVNC server:

      • sudo apt install tightvncserver

      To complete the VNC server’s initial configuration after installation, use the vncserver command to set up a secure password and create the initial configuration files:

      You’ll be prompted to enter and verify a password to access your machine remotely:

      Output

      You will require a password to access your desktops. Password: Verify:

      The password must be between six and eight characters long. Passwords more than 8 characters will be truncated automatically.

      Once you verify the password, you’ll have the option to create a a view-only password. Users who log in with the view-only password will not be able to control the VNC instance with their mouse or keyboard. This is a helpful option if you want to demonstrate something to other people using your VNC server, but this isn’t required.

      The process then creates the necessary default configuration files and connection information for the server:

      Output

      Would you like to enter a view-only password (y/n)? n xauth: file /home/sammy/.Xauthority does not exist New 'X' desktop is your_hostname:1 Creating default startup script /home/sammy/.vnc/xstartup Starting applications specified in /home/sammy/.vnc/xstartup Log file is /home/sammy/.vnc/your_hostname:1.log

      Now let’s configure the VNC server.

      Step 2 — Configuring the VNC Server

      The VNC server needs to know which commands to execute when it starts up. Specifically, VNC needs to know which graphical desktop it should connect to.

      These commands are located in a configuration file called xstartup in the .vnc folder under your home directory. The startup script was created when you ran the vncserver command in the previous step, but we’ll create our own to launch the Xfce desktop.

      When VNC is first set up, it launches a default server instance on port 5901. This port is called a display port, and is referred to by VNC as :1. VNC can launch multiple instances on other display ports, like :2, :3, and so on.

      Because we are going to be changing how the VNC server is configured, first stop the VNC server instance that is running on port 5901 with the following command:

      The output should look like this, although you’ll see a different PID:

      Output

      Killing Xtightvnc process ID 17648

      Before you modify the xstartup file, back up the original:

      • mv ~/.vnc/xstartup ~/.vnc/xstartup.bak

      Now create a new xstartup file and open it in your text editor:

      Commands in this file are executed automatically whenever you start or restart the VNC server. We need VNC to start our desktop environment if it’s not already started. Add these commands to the file:

      ~/.vnc/xstartup

      #!/bin/bash
      xrdb $HOME/.Xresources
      startxfce4 &
      

      The first command in the file, xrdb $HOME/.Xresources, tells VNC’s GUI framework to read the user’s .Xresources file. .Xresources is where a user can make changes to certain settings for the graphical desktop, like terminal colors, cursor themes, and font rendering. The second command tells the server to launch Xfce, which is where you will find all of the graphical software that you need to comfortably manage your server.

      To ensure that the VNC server will be able to use this new startup file properly, we’ll need to make it executable.

      • sudo chmod +x ~/.vnc/xstartup

      Now, restart the VNC server.

      You’ll see output similar to this:

      Output

      New 'X' desktop is your_hostname:1 Starting applications specified in /home/sammy/.vnc/xstartup Log file is /home/sammy/.vnc/your_hostname:1.log

      With the configuration in place, let’s connect to the server from our local machine.

      Step 3 — Connecting the VNC Desktop Securely

      VNC itself doesn’t use secure protocols when connecting. We’ll use an SSH tunnel to connect securely to our server, and then tell our VNC client to use that tunnel rather than making a direct connection.

      Create an SSH connection on your local computer that securely forwards to the localhost connection for VNC. You can do this via the terminal on Linux or macOS with the following command:

      • ssh -L 5901:127.0.0.1:5901 -C -N -l sammy your_server_ip

      The -L switch specifies the port bindings. In this case we’re binding port 5901 of the remote connection to port 5901 on your local machine. The -C switch enables compression, while the -N switch tells ssh that we don’t want to execute a remote command. The -l switch specifies the remote login name.

      Remember to replace sammy and your_server_ip with your non-root username and the IP address of your server.

      If you are using a graphical SSH client, like PuTTY, use your_server_ip as the connection IP, and set localhost:5901 as a new forwarded port in the program’s SSH tunnel settings.

      Once the tunnel is running, use a VNC client to connect to localhost:5901. You’ll be prompted to authenticate using the password you set in Step 1.

      Once you are connected, you’ll see the default Xfce desktop.

      VNC connection to Debian 10 server

      Select Use default config to configure your desktop quickly.

      You can access files in your home directory with the file manager or from the command line, as seen here:

      Files via VNC connection to Debian 10

      On your local machine, press CTRL+C in your terminal to stop the SSH tunnel and return to your prompt. This will disconnect your VNC session as well.

      Next let’s set up the VNC server as a service.

      Step 4 — Running VNC as a System Service

      Next, we’ll set up the VNC server as a systemd service so we can start, stop, and restart it as needed, like any other service. This will also ensure that VNC starts up when your server reboots.

      First, create a new unit file called /etc/systemd/system/vncserver@.service using your favorite text editor:

      • sudo nano /etc/systemd/system/vncserver@.service

      The @ symbol at the end of the name will let us pass in an argument we can use in the service configuration. We’ll use this to specify the VNC display port we want to use when we manage the service.

      Add the following lines to the file. Be sure to change the value of User, Group, WorkingDirectory, and the username in the value of PIDFILE to match your username:

      /etc/systemd/system/vncserver@.service

      [Unit]
      Description=Start TightVNC server at startup
      After=syslog.target network.target
      
      [Service]
      Type=forking
      User=sammy
      Group=sammy
      WorkingDirectory=/home/sammy
      
      PIDFile=/home/sammy/.vnc/%H:%i.pid
      ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1
      ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :%i
      ExecStop=/usr/bin/vncserver -kill :%i
      
      [Install]
      WantedBy=multi-user.target
      

      The ExecStartPre command stops VNC if it’s already running. The ExecStart command starts VNC and sets the color depth to 24-bit color with a resolution of 1280x800. You can modify these startup options as well to meet your needs.

      Save and close the file.

      Next, make the system aware of the new unit file.

      • sudo systemctl daemon-reload

      Enable the unit file.

      • sudo systemctl enable vncserver@1.service

      The 1 following the @ sign signifies which display number the service should appear over, in this case the default :1 as was discussed in Step 2..

      Stop the current instance of the VNC server if it’s still running.

      Then start it as you would start any other systemd service.

      • sudo systemctl start vncserver@1

      You can verify that it started with this command:

      • sudo systemctl status vncserver@1

      If it started correctly, the output should look like this:

      Output

      ● vncserver@1.service - Start TightVNC server at startup Loaded: loaded (/etc/systemd/system/vncserver@.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2019-10-10 17:56:17 UTC; 5s ago Process: 935 ExecStartPre=/usr/bin/vncserver -kill :1 > /dev/null 2>&1 (code=exited, status=2) Process: 940 ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :1 (code=exited, status=0/SUCCESS) Main PID: 948 (Xtightvnc) . . .

      Your VNC server will now be available when you reboot the machine.

      Start your SSH tunnel again:

      • ssh -L 5901:127.0.0.1:5901 -C -N -l sammy your_server_ip

      Then make a new connection using your VNC client software to localhost:5901 to connect to your machine.

      Conclusion

      You now have a secured VNC server up and running on your Debian 10 server. Now you’ll be able to manage your files, software, and settings with an easy-to-use and familiar graphical interface, and you’ll be able to run graphical software like web browsers remotely.



      Source link

      How to Install and Configure VNC on Debian 9


      Introduction

      Virtual Network Computing, or VNC, is a connection system that allows you to use your keyboard and mouse to interact with a graphical desktop environment on a remote server. It makes managing files, software, and settings on a remote server easier for users who are not yet comfortable with the command line.

      In this guide, you’ll set up a VNC server on a Debian 9 server and connect to it securely through an SSH tunnel. You’ll use TightVNC, a fast and lightweight remote control package. This choice will ensure that our VNC connection will be smooth and stable even on slower internet connections.

      Prerequisites

      To complete this tutorial, you’ll need:

      • One Debian 9 server set up by following the Debian 9 initial server setup guide, including a non-root user with sudo access and a firewall.
      • A local computer with a VNC client installed that supports VNC connections over SSH tunnels.
        • On Winows, you can use TightVNC, RealVNC, or UltraVNC.
        • On macOS, you can use the built-in Screen Sharing program, or can use a cross-platform app like RealVNC.
        • On Linux, you can choose from many options, including vinagre, krdc, RealVNC, or TightVNC.

      Step 1 — Installing the Desktop Environment and VNC Server

      By default, a Debian 9 server does not come with a graphical desktop environment or a VNC server installed, so we’ll begin by installing those. Specifically, we will install packages for the latest Xfce desktop environment and the TightVNC package available in the official Debian repository.

      On your server, update your list of packages:

      Now install the Xfce desktop environment on your server:

      • sudo apt install xfce4 xfce4-goodies

      During the installation, you'll be prompted to select your keyboard layout from a list of possible options. Choose the one that's appropriate for your language and press Enter. The installation will continue.

      Once that installation completes, install the TightVNC server:

      • sudo apt install tightvncserver

      To complete the VNC server's initial configuration after installation, use the vncserver command to set up a secure password and create the initial configuration files:

      You'll be prompted to enter and verify a password to access your machine remotely:

      Output

      You will require a password to access your desktops. Password: Verify:

      The password must be between six and eight characters long. Passwords more than 8 characters will be truncated automatically.

      Once you verify the password, you'll have the option to create a a view-only password. Users who log in with the view-only password will not be able to control the VNC instance with their mouse or keyboard. This is a helpful option if you want to demonstrate something to other people using your VNC server, but this isn't required.

      The process then creates the necessary default configuration files and connection information for the server:

      Output

      Would you like to enter a view-only password (y/n)? n xauth: file /home/sammy/.Xauthority does not exist New 'X' desktop is your_hostname:1 Creating default startup script /home/sammy/.vnc/xstartup Starting applications specified in /home/sammy/.vnc/xstartup Log file is /home/sammy/.vnc/your_hostname:1.log

      Now let's configure the VNC server.

      Step 2 — Configuring the VNC Server

      The VNC server needs to know which commands to execute when it starts up. Specifically, VNC needs to know which graphical desktop it should connect to.

      These commands are located in a configuration file called xstartup in the .vnc folder under your home directory. The startup script was created when you ran the vncserver in the previous step, but we'll create our own to launch the Xfce desktop.

      When VNC is first set up, it launches a default server instance on port 5901. This port is called a display port, and is referred to by VNC as :1. VNC can launch multiple instances on other display ports, like :2, :3, and so on.

      Because we are going to be changing how the VNC server is configured, first stop the VNC server instance that is running on port 5901 with the following command:

      The output should look like this, although you'll see a different PID:

      Output

      Killing Xtightvnc process ID 17648

      Before you modify the xstartup file, back up the original:

      • mv ~/.vnc/xstartup ~/.vnc/xstartup.bak

      Now create a new xstartup file and open it in your text editor:

      Commands in this file are executed automatically whenever you start or restart the VNC server. We need VNC to start our desktop environment if it's not already started. Add these commands to the file:

      ~/.vnc/xstartup

      #!/bin/bash xrdb $HOME/.Xresources startxfce4 &

      The first command in the file, xrdb $HOME/.Xresources, tells VNC's GUI framework to read the server user's .Xresources file. .Xresources is where a user can make changes to certain settings of the graphical desktop, like terminal colors, cursor themes, and font rendering. The second command tells the server to launch Xfce, which is where you will find all of the graphical software that you need to comfortably manage your server.

      To ensure that the VNC server will be able to use this new startup file properly, we'll need to make it executable.

      • sudo chmod +x ~/.vnc/xstartup

      Now, restart the VNC server.

      You'll see output similar to this:

      Output

      New 'X' desktop is your_hostname:1 Starting applications specified in /home/sammy/.vnc/xstartup Log file is /home/sammy/.vnc/your_hostname:1.log

      With the configuration in place, let's connect to the server from our local machine.

      Step 3 — Connecting the VNC Desktop Securely

      VNC itself doesn't use secure protocols when connecting. We'll use an SSH tunnel to connect securely to our server, and then tell our VNC client to use that tunnel rather than making a direct connection.

      Create an SSH connection on your local computer that securely forwards to the localhost connection for VNC. You can do this via the terminal on Linux or macOS with the following command:

      • ssh -L 5901:127.0.0.1:5901 -C -N -l sammy your_server_ip

      The -L switch specifies the port bindings. In this case we're binding port 5901 of the remote connection to port 5901 on your local machine. The -C switch enables compression, while the -N switch tells ssh that we don't want to execute a remote command. The -l switch specifies the remote login name.

      Remember to replace sammy and your_server_ip with the sudo non-root username and IP address of your server.

      If you are using a graphical SSH client, like PuTTY, use your_server_ip as the connection IP, and set localhost:5901 as a new forwarded port in the program's SSH tunnel settings.

      Once the tunnel is running, use a VNC client to connect to localhost:5901. You'll be prompted to authenticate using the password you set in Step 1.

      Once you are connected, you'll see the default Xfce desktop.

      VNC connection to Debian 9 serverSelect Use default config to configure your desktop quickly.

      You can access files in your home directory with the file manager or from the command line, as seen here:

      Files via VNC connection to Debian 9

      On your local machine, press CTRL+C in your terminal to stop the SSH tunnel and return to your prompt. This will disconnect your VNC session as well.

      Next let's set up the VNC server as a service.

      Step 4 — Running VNC as a System Service

      Next, we'll set up the VNC server as a systemd service so we can start, stop, and restart it as needed, like any other service. This will also ensure that VNC starts up when your server reboots.

      First, create a new unit file called /etc/systemd/system/vncserver@.service using your favorite text editor:

      • sudo nano /etc/systemd/system/vncserver@.service

      The @ symbol at the end of the name will let us pass in an argument we can use in the service configuration. We'll use this to specify the VNC display port we want to use when we manage the service.

      Add the following lines to the file. Be sure to change the value of User, Group, WorkingDirectory, and the username in the value of PIDFILE to match your username:

      /etc/systemd/system/vncserver@.service

      [Unit] Description=Start TightVNC server at startup After=syslog.target network.target [Service] Type=forking User=sammy Group=sammy WorkingDirectory=/home/sammy PIDFile=/home/sammy/.vnc/%H:%i.pid ExecStartPre=-/usr/bin/vncserver -kill :%i > /dev/null 2>&1 ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :%i ExecStop=/usr/bin/vncserver -kill :%i [Install] WantedBy=multi-user.target

      The ExecStartPre command stops VNC if it's already running. The ExecStart command starts VNC and sets the color depth to 24-bit color with a resolution of 1280x800. You can modify these startup options as well to meet your needs.

      Save and close the file.

      Next, make the system aware of the new unit file.

      • sudo systemctl daemon-reload

      Enable the unit file.

      • sudo systemctl enable vncserver@1.service

      The 1 following the @ sign signifies which display number the service should appear over, in this case the default :1 as was discussed in Step 2..

      Stop the current instance of the VNC server if it's still running.

      Then start it as you would start any other systemd service.

      • sudo systemctl start vncserver@1

      You can verify that it started with this command:

      • sudo systemctl status vncserver@1

      If it started correctly, the output should look like this:

      Output

      ● vncserver@1.service - Start TightVNC server at startup Loaded: loaded (/etc/systemd/system/vncserver@.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2018-09-05 16:47:40 UTC; 3s ago Process: 4977 ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :1 (code=exited, status=0/SUCCESS) Process: 4971 ExecStartPre=/usr/bin/vncserver -kill :1 > /dev/null 2>&1 (code=exited, status=0/SUCCESS) Main PID: 4987 (Xtightvnc) ...

      Your VNC server will now be available when you reboot the machine.

      Start your SSH tunnel again:

      • ssh -L 5901:127.0.0.1:5901 -C -N -l sammy your_server_ip

      Then make a new connection using your VNC client software to localhost:5901 to connect to your machine.

      Conclusion

      You now have a secured VNC server up and running on your Debian 9 server. Now you'll be able to manage your files, software, and settings with an easy-to-use and familiar graphical interface, and you'll be able to run graphical software like web browsers remotely.



      Source link