One place for hosting & domains

      How to Install and Configure VNC on Ubuntu 20.04


      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 with TightVNC on an Ubuntu 20.04 server and connect to it securely through an SSH tunnel. Then, you’ll use a VNC client program on your local machine to interact with your server through a graphical desktop environment.

      Prerequisites

      To complete this tutorial, you’ll need:

      • One Ubuntu 20.04 server with a non-root administrative user and a firewall configured with UFW. To set this up, follow our initial server setup guide for Ubuntu 20.04.
      • A local computer with a VNC client installed. The VNC client you use must support 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, an Ubuntu 20.04 server does not come with a graphical desktop environment or a VNC server installed, so you’ll begin by installing those.

      You have many options when it comes to which VNC server and desktop environment you choose. In this tutorial, you will install packages for the latest Xfce desktop environment and the TightVNC package available from the official Ubuntu repository. Both Xfce and TightVNC are known for being lightweight and fast, which will help ensure that the VNC connection will be smooth and stable even on slower internet connections.

      After connecting to your server with SSH, update your list of packages:

      Now install Xfce along with the xfce4-goodies package, which contains a few enhancements for the desktop environment:

      • sudo apt install xfce4 xfce4-goodies

      During installation, you may be prompted to choose a default display manager for Xfce. A display manager is a program that allows you to select and log in to a desktop environment through a graphical interface. You’ll only be using Xfce when you connect with a VNC client, and in these Xfce sessions you’ll already be logged in as your non-root Ubuntu user. So for the purposes of this tutorial, your choice of display manager isn’t pertinent. Select either one and press ENTER.

      Once that installation completes, install the TightVNC server:

      • sudo apt install tightvncserver

      Next, run the vncserver command to set a VNC access password, create the initial configuration files, and start a VNC server instance:

      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 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. Additionally, 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, with :2 referring to port 5902, :3 referring to 5903, and so on:

      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

      Note that if you ever want to change your password or add a view-only password, you can do so with the vncpasswd command:

      At this point, the VNC server is installed and running. Now let’s configure it to launch Xfce and give us access to the server through a graphical interface.

      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 environment it should connect to.

      The commands that the VNC server runs at startup 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 you’ll create your own to launch the Xfce desktop.

      Because you 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 will 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 a text editor, such as nano:

      Then add the following lines to the file:

      ~/.vnc/xstartup

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

      The first line is a shebang. In executable plain-text files on *nix platforms, a shebang tells the system what interpreter to pass that file to for execution. In this case, you’re passing the file to the Bash interpreter. This will allow each successive line to be executed as commands, in order.

      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. Whenever you start or restart the VNC server, these commands will execute automatically.

      Save and close the file after adding these lines. If you used nano, do so by pressing CTRL + X, Y, then ENTER.

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

      Then restart the VNC server:

      Notice that this time the command includes the -localhost option, which binds the VNC server to your server’s loopback interface. This will cause VNC to only allow connections that originate from the server on which it’s installed.

      In the next step, you’ll establish an SSH tunnel between your local machine and your server, essentially tricking VNC into thinking that the connection from your local machine originated on your server. This strategy will add an extra layer of security around VNC, as the only users who will be able to access it are those that already have SSH access to your 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, you’re ready to connect to the VNC server from your local machine.

      Step 3 — Connecting the VNC Desktop Securely

      VNC itself doesn’t use secure protocols when connecting. To securely connect to your server, you’ll establish an SSH tunnel and then tell your VNC client to connect using 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 ssh command:

      • ssh -L 59000:localhost:5901 -C -N -l sammy your_server_ip

      Here’s what this ssh command’s options mean:

      • -L 59000:localhost:5901: The -L switch specifies that the given port on the local computer (59000) is to be forwarded to the given host and port on the destination server (localhost:5901, meaning port 5901 on the destination server, defined as your_server_ip). Note that the local port you specify is somewhat arbitrary; as long as the port isn’t already bound to another service, you can use it as the forwarding port for your tunnel.
      • -C: This flag enables compression which can help minimize resource consumption and speed things up.
      • -N: This option tells ssh that you don’t want to execute any remote commands. This setting is useful when you just want to forward ports.
      • -l sammy your_server_ip: The -l switch let’s you specify the user you want to log in as once you connect to the server. Make sure to replace sammy and your_server_ip with the name of your non-root user and your server’s IP address.

      Note: This command establishes an SSH tunnel that forwards information from port 5901 on your VNC server to port 59000 on your local machine via port 22 on each machine, the default port for SSH. Assuming you followed the prerequisite Initial Server Setup guide for Ubuntu 20.04, you will have added a UFW rule to allow connections to your server over OpenSSH.

      This is more secure than simply opening up your server’s firewall to allow connections to port 5901, as that would allow anyone to access your server over VNC. By connecting over an SSH tunnel, you’re limiting VNC access to machines that already have SSH access to the server.

      If you are using PuTTY to connect to your server, you can create an SSH tunnel by right-clicking on the top bar of the terminal window, and then clicking the Change Settings… option:

      Right-click on top bar to reveal Change Settings option

      Find the Connection branch in the tree menu on the left-hand side of the PuTTY Reconfiguration window. Expand the SSH branch and click on Tunnels. On the Options controlling SSH port forwarding screen, enter 59000 as the Source Port and localhost:5901 as the Destination, like this:

      Example PuTTY SSH tunnel configuration

      Then click the Add button, and then the Apply button to implement the tunnel.

      Once the tunnel is running, use a VNC client to connect to localhost:59000. 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. It should look something like this:

      VNC connection to Ubuntu 20.04 server with the Xfce desktop environment

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

      File Manager via VNC connection to Ubuntu 20.04

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

      Now you can configure your VNC server to run as a systemd service.

      Step 4 — Running VNC as a System Service

      By setting up the VNC server to run as a systemd service you can start, stop, and restart it as needed, like any other service. You can also use systemd’s management commands to ensure that VNC starts when your server boots up.

      First, create a new unit file called /etc/systemd/system/[email protected]:

      The @ symbol at the end of the name will let us pass in an argument you can use in the service configuration. You’ll use this to specify the VNC display port you want to use when you 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/[email protected]

      [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 -localhost :%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 1280×800. You can modify these startup options as well to meet your needs. Also, note that the ExecStart command again includes the -localhost option.

      Save and close the file.

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

      • sudo systemctl daemon-reload

      Enable the unit file:

      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

      [email protected] - Start TightVNC server at startup Loaded: loaded (/etc/systemd/system/[email protected]; enabled; vendor preset: enabled) Active: active (running) since Thu 2020-05-07 17:23:50 UTC; 6s ago Process: 39768 ExecStartPre=/usr/bin/vncserver -kill :1 > /dev/null 2>&1 (code=exited, status=2) Process: 39772 ExecStart=/usr/bin/vncserver -depth 24 -geometry 1280x800 :1 (code=exited, status=0/SUCCESS) Main PID: 39795 (Xtightvnc) ...

      Your VNC server is now ready to use whenever your server boots up, and you can manage it with systemctl commands like any other systemd service.

      However, there won’t be any difference on the client side. To reconnect, start your SSH tunnel again:

      • ssh -L 59000:localhost:5901 -C -N -l sammy your_server_ip

      Then make a new connection using your VNC client software to localhost:59000 to connect to your server.

      Conclusion

      You now have a secured VNC server up and running on your Ubuntu 20.04 server. Now you’ll be able to manage your files, software, and settings with a user-friendly graphical interface, and you’ll be able to run graphical software like web browsers remotely.



      Source link

      Installation und Konfiguration von VNC auf Ubuntu 18.04


      Einführung

      Virtual Network Computing oder VNC ist ein Verbindungssystem, das es Ihnen ermöglicht, die Tastatur und die Maus zur Interaktion mit einer grafischen Desktop-Umgebung auf einem entfernten Server zu verwenden. Es vereinfacht die Verwaltung von Dateien, Software und Einstellungen auf einem entfernten Server für Benutzer, die mit der Befehlszeile noch nicht so versiert sind.

      In diesem Leitfaden erstellen Sie einen VNC-Server auf einem Ubuntu 18.04 Server und verbinden sich mit diesem über einen sicheren SSH-Tunnel. Dazu verwenden Sie TightVNC, ein schnelles, leichtes Fernsteuerungspaket. Mit dieser Auswahl stellen Sie sicher, dass unsere VNC-Verbindung auch bei langsameren Internet-Verbindungen reibungslos und stabil sein wird.

      Voraussetzungen

      Um dieses Tutorial zu absolvieren, benötigen Sie:

      • Einen Ubuntu 18.04-Server, der gemäß der Anleitung zum Setup des Ubuntu 18.04-Servers eingerichtet wurde, einschließlich eines Sudo-Benutzers ohne Rootberechtigung und einer Firewall.
      • Einen lokalen Computer mit einem installierten VNC Client, der VNC-Verbindungen über SSH-Tunnel unterstützt.

      Schritt 1 — Installation der Desktop-Umgebung und des VNC-Servers

      Standardmäßig wird ein Ubuntu 18.04 Server nicht mit einer grafischen Desktop-Umgebung oder einem installierten VNC-Server geliefert, daher beginnen wir mit deren Installation. Wir installieren vor allem Pakete für die aktuellste Xfce Desktop-Umgebung und das TightVNC-Paket, das im offiziellen Ubuntu Repository verfügbar ist.

      Aktualisieren Sie Ihre Liste der Pakete auf Ihrem Server.

      Installieren Sie jetzt die Xfce Desktop-Umgebung auf Ihrem Server:

      • sudo apt install xfce4 xfce4-goodies

      Wenn diese Installation abgeschlossen ist, installieren Sie den TightVNC Server:

      • sudo apt install tightvncserver

      Um die Erstkonfiguration des VNC-Servers nach der Installation abzuschließen, verwenden Sie den Befehl vncserver, um ein sicheres Passwort einzurichten und die Erstkonfigurationsdateien zu erstellen:

      Sie werden dazu aufgefordert, ein Passwort einzugeben und zu verifizieren, um ferngesteuert auf Ihren Rechner zuzugreifen.

      Output

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

      Das Passwort muss zwischen sechs und acht Zeichen lang sein. Passwörter mit mehr als 8 Zeichen werden automatisch verkürzt.

      Sobald Sie das Passwort verifiziert haben, können Sie ein schreibgeschütztes Passwort einrichten. Benutzer, die sich mit dem schreibgeschützten Passwort anmelden, können die VCN-Instanz nicht mit der Maus oder Tastatur steuern. Das ist eine hilfreiche Option, wenn Sie mit Ihrem VCN Server anderen etwas zeigen möchten, ist aber nicht erforderlich.

      Der Prozess erstellt dann die notwendigen Standard-Konfigurationsdateien und Verbindungsinformationen für den 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

      Jetzt wollen wir den VCN Server konfigurieren.

      Schritt 2 — Konfiguration des VCN Servers

      Der VCN Server muss wissen, welche Befehle er beim Start ausführen soll. VCN muss vor allem wissen, mit welchem grafischen Desktop er sich verbinden soll.

      Diese Befehle befinden sich in einer Konfigurationsdatei namens xstartup im Ordner .vnc in Ihrem Stammverzeichnis. Das Start-Skript wurde erstellt, als Sie den vncserver im vorherigen Schritt ausgeführt haben, aber wir erstellen unser eigenes, um den Xfce Desktop zu starten.

      Wenn VCN das erste Mal eingerichtet wird, startet er eine Standard-Server-Instanz auf Port 5901. Dieser Port wird als *Anzeige-Port *bezeichnet und wird vom VCN :1 genannt. VCN kann mehrere Instanzen auf anderen Anzeige-Ports, wie :2, :3 usw. starten.

      Da wir die Konfiguration des VCN Servers ändern werden, müssen wir zunächst die VCN Server-Instanz stoppen, die auf Port 5901 ausgeführt wird. Dazu verwenden wir den folgenden Befehl:

      Die Ausgabe sollte wie folgt aussehen, auch wenn Sie eine andere PID sehen werden:

      Output

      Killing Xtightvnc process ID 17648

      Bevor Sie die Datei xstartup ändern, sollten Sie ein Backup der Originaldatei vornehmen:

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

      Erstellen Sie jetzt eine neue xstartup-Datei und öffnen Sie sie im Texteditor:

      Die Befehle in dieser Datei werden automatisch ausgeführt, wenn Sie den VCN Server starten oder neu starten. VCN muss unsere Desktop-Umgebung starten, sofern diese noch nicht gestartet wurde. Fügen Sie der Datei diese Befehle hinzu:

      ~/.vnc/xstartup

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

      Der erste Befehl in der Datei, xrdb $HOME/. Xresources weist das GUI Framework des VNC mit, das des Serverbenutzers zu lesen. Xresources-Datei. . Xresources ist der Ort, an dem ein Benutzer bestimmte Einstellungen des grafischen Desktops ändern kann, wie die Terminal-Farben, Cursor-Gestaltung und das Font-Rendering. Der zweite Befehl weist den Server an, Xfce zu starten, wo Sie die grafische Software finden, die sie zur problemlosen Verwaltung Ihres Servers brauchen.

      Um sicherzustellen, dass der VCN Server diese neue Start-Datei ordnungsgemäß verwenden kann, müssen wir sie ausführbar machen.

      • sudo chmod +x ~/.vnc/xstartup

      Starten Sie jetzt den VCN Server.

      Sie werden eine Ausgabe sehen, die dieser ähnelt:

      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

      Sobald die Konfiguration vorgenommen wurde, wollen wir uns über unseren lokalen Rechner mit dem Server verbinden.

      Schritt 3 — Eine sichere Verbindung mit dem VCN Desktop

      VCN selbst verwendet keine sicheren Protokolle beim Verbinden. Wir verwenden einen SSH-Tunnel, um eine sichere Verbindung mit unserem Server herzustellen und weisen dann unseren VCN Client an, anstelle der Direktverbindung diesen Tunnel zu verwenden.

      Erstellen Sie auf Ihrem lokalen Computer eine SSH-Verbindung, die sicher an die localhost-Verbindung für VCN weiterleitet. Sie können dies mit folgendem Befehl über den Terminal auf Linux oder macOS durchführen:

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

      Der -L Switch gibt die Port-Bindung an. In diesem Fall verbinden wir Port 5901 der entfernten Verbindung mit Port 5901 auf Ihrem lokalen Rechner. Der -C Switch ermöglicht eine Kompression, während der -N Switch ssh mitteilt, dass wir keinen entfernten Befehl ausführen wollen. Der -l Switch gibt den entfernten Login-Namen an.

      Denken Sie daran, sammy und your_server_ip durch den Sudo-Benutzernamen ohne Rootberechtigung und die IP-Adresse Ihres Servers zu ersetzen.

      Wenn Sie einen grafischen SSH Client, wie PuTTY, verwenden, verwenden Sie your_server_ip als Verbindungs-IP und setzen localhost:5901 als einen neuen weitergeleiteten Port in der SSH-Tunnel-Einstellung des Programms ein.

      Sobald der Tunnel läuft, verwenden Sie einen VCN Client, um sich mit localhost:5901 zu verbinden. Sie werden aufgefordert, sich mit dem in Schritt 1 eingestellten Passwort zu authentifizieren.

      Sobald die Verbindung steht, sehen Sie den Xfce Standard-Desktop. Es sollte ungefähr so aussehen:

      VNC Verbindung mit dem Ubuntu 18.04 Server

      Sie können mit dem Dateimanager auf Dateien in Ihrem Stammverzeichnis zugreifen oder von der Befehlszeile aus, wie nachstehend zu sehen ist:

      Dateien über die VNC Verbindung mit Ubuntu 18.04

      Drücken Sie CTRL+C auf Ihrem Terminal, um den SSH-Tunnel zu stoppen und zu Ihrer Aufforderung zurückzukehren. Damit wird auch Ihre VNC Sitzung unterbrochen.

      Als nächstes richten wir unseren VNC Server als Dienst ein.

      Schritt 4 — VCN als Systemdienst ausführen

      Als nächstes stellen wir den VNC Server als Systemdienst ein, um ihn wie jeden anderen Dienst starten, stoppen und ggf. neu starten zu können. Damit wird auch sichergestellt, dass VCN beim Neustart Ihres Servers gestartet wird.

      Erstellen Sie zunächst in Ihrem bevorzugten Texteditor eine neue Unit-Datei mit dem Namen /etc/systemd/system/[email protected]:

      Das @ Symbol am Ende des Namens gestattet uns, ein Argument aufzunehmen, das wir in der Dienstkonfiguration verwenden können. Wir verwenden dies, um den VCN Anzeige-Port anzugeben, den wir bei der Dienstverwaltung einsetzen möchten.

      Fügen Sie der Datei folgende Zeilen hinzu. Vergewissern Sie sich, dass Sie den Wert von User, Group, WorkingDirectory und den Benutzernamen im Wert von *PIDFILE *ändern, damit er mit Ihrem Benutzernamen übereinstimmt:

      /etc/systemd/system/[email protected]

      [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

      Der ExecStartPre Befehl stoppt VCN, wenn er bereits läuft. Der ExecStart Befehl startet VCN und stellt die Farbtiefe auf 24-Bit-Farbe mit einer Auflösung von 1280 x 800. Sie können diese Startoptionen auch je nach Wunsch ändern.

      Speichern und schließen Sie die Datei.

      Als nächstes müssen Sie das System auf die neue Unit-Datei aufmerksam machen.

      • sudo systemctl daemon-reload

      Aktivieren Sie die Unit-Datei.

      Die 1 nach dem Zeichen @ gibt an, über welcher Anzeigenummer der Dienst angezeigt werden soll; in diesem Fall ist der Standard :1, wie wir bereits in Schritt 2 besprochen haben.

      Stoppen Sie die aktuelle Instanz des VCN Servers, wenn er noch läuft.

      Starten Sie ihn dann wie jeden anderen Systemdienst.

      • sudo systemctl start vncserver@1

      Sie können verifizieren, dass er mit diesem Befehl gestartet wurde:

      • sudo systemctl status vncserver@1

      Falls er richtig gestartet wurde, sollte die Ausgabe wie folgt aussehen:

      Output

      [email protected] - Start TightVNC server at startup Loaded: loaded (/etc/systemd/system/[email protected]; 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) ...

      Ihr VCN Server steht jetzt beim Neustart des Rechners zur Verfügung.

      Starten Sie Ihren SSH-Tunnel erneut:

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

      Stellen Sie dann mit Ihrer VCN Client Software eine neue Verbindung zum localhost:5901 her, um sich mit Ihrem Rechner zu verbinden.

      Zusammenfassung

      Jetzt läuft ein sicherer VCN Server auf Ihrem Ubuntu 18.04 Server. Jetzt können Sie Ihre Dateien, Software und Einstellungen in einer benutzerfreundlichen, vertrauten grafischen Oberfläche verwalten und grafische Software wie Web-Browser ferngesteuert ausführen.



      Source link

      Comment installer et configurer VNC sur Ubuntu 18.04


      Introduction

      Le* Virtual Network Computing*, ou VNC, est un système de connexion qui vous permet d’utiliser votre clavier et votre souris pour interagir avec un environnement de bureau graphique sur un serveur distant. Il facilite la gestion des fichiers, des logiciels et des paramètres sur un serveur distant pour les utilisateurs qui ne sont pas encore à l’aise avec la ligne de commande.

      Dans ce guide, vous allez configurer un serveur VNC sur un serveur Ubuntu 18.04 et vous y connecter en toute sécurité via un tunnel SSH. Vous utiliserez TightVNC, un logiciel de contrôle à distance rapide et léger. Ce choix garantira que notre connexion VNC sera fluide et stable, même sur des connexions Internet plus lentes.

      Conditions préalables

      Pour suivre ce tutoriel, vous aurez besoin des éléments suivants :

      • Un serveur Ubuntu 18.04 configuré en suivant le guide de configuration initiale de serveur Ubuntu 18.04, comprenant un utilisateur non root avec privilèges sudo et un pare-feu.
      • Un ordinateur local avec un client VNC installé qui prend en charge les connexions VNC sur les tunnels SSH.

      Étape 1 – Installation de l’environnement de bureau et du serveur VNC

      Par défaut, un serveur Ubuntu 18.04 n’a pas d’environnement de bureau graphique ou de serveur VNC installé, nous allons donc commencer par les installer. Plus précisément, nous installerons des packages pour le dernier environnement de bureau Xfce et le package TightVNC disponible dans le référentiel Ubuntu officiel.

      Sur votre serveur, mettez à jour votre liste de packages :

      Installez maintenant l'environnement de bureau Xfce sur votre serveur :

      • sudo apt install xfce4 xfce4-goodies

      Une fois cette installation terminée, installez le serveur TightVNC :

      • sudo apt install tightvncserver

      Pour terminer la configuration initiale du serveur VNC après l'installation, utilisez la commande vncserver pour définir un mot de passe sécurisé et créer les fichiers de configuration initiale :

      Vous serez invité à saisir et à vérifier un mot de passe pour accéder à votre machine à distance :

      Output

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

      Le mot de passe doit comporter entre six et huit caractères. Les mots de passe de plus de 8 caractères seront automatiquement tronqués.

      Une fois le mot de passe vérifié, vous aurez la possibilité de créer un mot de passe en lecture seule. Les utilisateurs qui se connectent avec le mot de passe en lecture seule ne pourront pas contrôler l'instance VNC avec leur souris ou leur clavier. Cette option est utile si vous souhaitez montrer quelque chose à d'autres personnes à l'aide de votre serveur VNC, mais elle n'est pas obligatoire.

      Le processus crée ensuite les fichiers de configuration par défaut et les informations de connexion nécessaires pour le serveur :

      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

      Configurons maintenant le serveur VNC.

      Étape 2 - Configuration du serveur VNC

      Le serveur VNC doit savoir quelles commandes exécuter lorsqu'il démarre. Plus précisément, VNC doit savoir à quel bureau graphique se connecter.

      Ces commandes se trouvent dans un fichier de configuration nommé xstartup dans le dossier .vnc de votre répertoire de base. Le script de démarrage a été créé lorsque vous avez exécuté vncserver à l'étape précédente, mais nous allons créer le nôtre pour lancer le bureau Xfce.

      Lors de la première configuration de VNC, celui-ci lance une instance de serveur par défaut sur le port 5901. Ce port est un port d'affichage et VNC le désigne par :1. VNC peut lancer plusieurs instances sur d'autres ports d'affichage, tels que :2, :3 et ainsi de suite.

      Comme nous allons modifier la configuration du serveur VNC, arrêtez tout d'abord l'instance du serveur VNC lancée sur le port 5901 grâce à la commande suivante :

      La sortie devrait ressembler à ceci, bien que vous verrez un PID différent :

      Output

      Killing Xtightvnc process ID 17648

      Avant de modifier le fichier xstartup, sauvegardez l'original :

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

      Créez maintenant un nouveau fichier xstartup et ouvrez-le dans votre éditeur de texte :

      Les commandes de ce fichier sont exécutées automatiquement chaque fois que vous démarrez ou redémarrez le serveur VNC. Nous avons besoin que VNC démarre notre environnement de bureau s'il n'est pas déjà lancé. Ajoutez ces commandes au fichier :

      ~/.vnc/xstartup

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

      La première commande du fichier, xrdb $HOME/.Xresources​​​, indique au framework de l'interface graphique de VNC de lire le fichier .Xresources. .Xresources permet à un utilisateur de modifier certains paramètres du bureau graphique, tels que les couleurs du terminal, les thèmes de curseur et le rendu des polices. La seconde commande indique au serveur de lancer Xfce, où vous trouverez tous les logiciels graphiques dont vous avez besoin pour gérer confortablement votre serveur.

      Pour que le serveur VNC puisse utiliser correctement ce nouveau fichier de démarrage, nous devons le rendre exécutable.

      • sudo chmod +x ~/.vnc/xstartup

      Redémarrez maintenant le serveur VNC.

      Vous verrez une sortie similaire à celle-ci :

      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

      Une fois la configuration en place, connectons-nous au serveur depuis notre machine locale.

      Étape 3 - Connexion sécurisée du bureau VNC

      VNC n'utilise pas lui-même de protocoles sécurisés lors de la connexion. Nous utiliserons un tunnel SSH pour nous connecter en toute sécurité à notre serveur, puis nous dirons à notre client VNC d'utiliser ce tunnel plutôt que d'établir une connexion directe.

      Créez une connexion SSH sur votre ordinateur local qui transfère en toute sécurité vers la connexion localhost pour VNC. Vous pouvez le faire via le terminal sous Linux ou macOS avec la commande suivante :

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

      Le commutateur -L définit les liaisons de port. Dans ce cas, nous relions le port 5901 de la connexion distante au port 5901 de votre machine locale. Le commutateur -C active la compression, tandis que le commutateur -N indique à ssh que nous ne voulons pas exécuter une commande à distance. Le commutateur -l définit le nom de connexion distant.

      N'oubliez pas de remplacer sammy et your_server_ip par le nom d'utilisateur non root avec privilèges sudo et l'adresse IP de votre serveur.

      Si vous utilisez un client SSH graphique, tel que PuTTY, utilisez your_server_ip comme IP de connexion et définissez localhost:5901 comme nouveau port transféré dans les paramètres du tunnel SSH du programme.

      Une fois le tunnel en cours d'exécution, utilisez un client VNC pour vous connecter à localhost:5901. Vous serez invité à vous authentifier à l'aide du mot de passe défini au cours de l'étape 1.

      Une fois connecté, vous verrez le bureau Xfce par défaut. Il devrait ressembler à cela :

      VNC connection to Ubuntu 18.04 server

      Vous pouvez accéder aux fichiers dans votre répertoire de base via le gestionnaire de fichiers ou depuis la ligne de commande, comme illustré ici :

      Files via VNC connection to Ubuntu 18.04

      Appuyez sur CTRL+C au sein de votre terminal pour arrêter le tunnel SSH et revenir à votre invite. Cela déconnectera également votre session VNC.

      Configurons ensuite notre serveur VNC en tant que service.

      Étape 4 - Exécution de VNC en tant que service système

      Ensuite, nous allons configurer le serveur VNC en tant que service systemd afin de pouvoir le démarrer, l'arrêter et le redémarrer au besoin, comme n'importe quel autre service. Cela garantira également que VNC se lance au redémarrage de votre serveur.

      Tout d'abord, créez un nouveau fichier d'unité appelé /etc/systemd/system/[email protected] à l'aide de l'éditeur de texte de votre choix :

      Le symbole @ à la fin du nom nous permettra de transmettre un argument que nous pourrons utiliser dans la configuration du service. Nous l'utiliserons pour spécifier le port d'affichage VNC que nous souhaitons utiliser lorsque nous gérons le service.

      Ajoutez les lignes suivantes au fichier. Veillez à modifier les valeurs de User, Group et WorkingDirectory, ainsi que le nom d'utilisateur dans la valeur de PIDFILE, en utilisant votre nom d'utilisateur :

      /etc/systemd/system/[email protected]

      [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

      La commande ExecStartPre arrête VNC s'il est déjà en cours d'exécution. La commande ExecStart lance VNC et définit une profondeur de couleur de 24 bits avec une résolution de 1280x800. Vous pouvez également modifier ces options de démarrage selon vos besoins.

      Enregistrez et fermez le fichier.

      Ensuite, informez le système du nouveau fichier d'unité.

      • sudo systemctl daemon-reload

      Activez le fichier d'unité.

      Le 1 suivant le signe @ indique le numéro d'affichage sur lequel le service doit apparaître, dans ce cas la valeur par défaut :1, comme mentionné à l'étape 2.

      Arrêtez l'instance actuelle du serveur VNC si elle est toujours en cours d'exécution.

      Puis, démarrez le serveur comme vous le feriez pour n'importe quel autre service systemd.

      • sudo systemctl start vncserver@1

      Vous pouvez vérifier qu'il a démarré avec cette commande :

      • sudo systemctl status vncserver@1

      S'il a démarré correctement, la sortie devrait ressembler à ceci :

      Output

      [email protected] - Start TightVNC server at startup Loaded: loaded (/etc/systemd/system/[email protected]; 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) ...

      Votre serveur VNC sera désormais disponible lorsque vous redémarrerez la machine.

      Relancez votre tunnel SSH :

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

      Puis, établissez une nouvelle connexion à localhost:5901 à l'aide de votre logiciel client VNC pour vous connecter à votre machine.

      Conclusion

      Vous disposez maintenant d'un serveur VNC sécurisé fonctionnant sur votre serveur Ubuntu 18.04. Vous pourrez désormais gérer vos fichiers, vos logiciels et vos paramètres grâce à une interface graphique intuitive et familière, et vous pourrez exécuter à distance des logiciels graphiques tels que des navigateurs Web.



      Source link