> For the complete documentation index, see [llms.txt](https://docs.devolutions.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.devolutions.net/server/it/knowledge-base/how-to-articles/install-devolutions-server-for-linux.md).

# Installare Devolutions Server per Linux

Devolutions Server è disponibile per Linux con Microsoft Kestrel come server web integrato e Microsoft PowerShell 7 per l'installazione da riga di comando. Il presente argomento mostra come installare manualmente Devolutions Server for Linux utilizzando prompt Bash e script PowerShell, nonché come accedervi e rimuoverlo.

In alternativa, Devolutions Server può essere installato automaticamente utilizzando gli script disponibili nel [repository Devolutions GitHub ScriptLibrary](https://github.com/Devolutions/ScriptLibrary/tree/main/DVLSForLinux).

### Installazione dei prerequisiti <a href="#installing-prerequisites" id="installing-prerequisites"></a>

1. Se Microsoft SQL Server non è già installato, esegua il seguente prompt Bash modificando la variabile `MSSQL_SA_PASSWORD` con una password complessa:

   ```bash
   source /etc/os-release
   curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | sudo gpg --dearmor --batch --yes -o /usr/share/keyrings/microsoft-prod.gpg
   curl -fsSL https://packages.microsoft.com/config/ubuntu/$VERSION_ID/mssql-server-2022.list | sudo tee /etc/apt/sources.list.d/mssql-server-2022.list
   sudo apt-get update
   sudo apt-get install -y mssql-server
   sudo MSSQL_SA_PASSWORD="mystrongpassword" MSSQL_PID="evaluation" /opt/mssql/bin/mssql-conf -n setup accept-eula
   sudo /opt/mssql/bin/mssql-conf set sqlagent.enabled true
   sudo systemctl restart mssql-server
   ```

   In questo esempio `MSSQL_PID` è impostato su ***evaluation***, ma è possibile inserire qui una chiave prodotto.

{% hint style="warning" %}
Microsoft supporta solo [determinate versioni SQL](/server/it/readme/system-requirements.md#software-dependencies). Consulti la documentazione Microsoft per assicurarsi che la sua versione di SQL sia ufficialmente supportata per la sua distribuzione.
{% endhint %}

2. Esegua questo prompt Bash per installare PowerShell 7:

   ```bash
   sudo apt-get update
   sudo apt-get install -y wget apt-transport-https software-properties-common
   source /etc/os-release
   wget -q https://packages.microsoft.com/config/ubuntu/$VERSION_ID/packages-microsoft-prod.deb
   sudo dpkg -i packages-microsoft-prod.deb
   rm packages-microsoft-prod.deb
   sudo apt-get update
   sudo apt-get install -y powershell
   ```

Si assicuri che l'installazione avvenga in una directory accessibile all'utente corrente, poiché la riga di comando `wget` scarica un pacchetto `.deb` in tale directory.

3. Scelga se installare il [modulo Devolutions.PowerShell](https://www.powershellgallery.com/packages/Devolutions.PowerShell/) per l'utente corrente o per tutti gli utenti.

   * **Per l'utente corrente** (percorso: `/.local/share/powershell/Modules`), esegua:

     ```powershell
     Install-Module -Name 'Devolutions.PowerShell' -Confirm:$False
     ```
   * **Per tutti gli utenti** (percorso: `/opt/microsoft/powershell/7/Modules`), esegua:

     ```powershell
     & sudo pwsh -Command { Install-Module -Name 'Devolutions.PowerShell' -Confirm:$False -Scope 'AllUsers' -Force }
     ```

   È probabile che compaia un avviso indicante che l'installazione proviene da un repository non attendibile. Il modulo è ospitato su PowerShell Gallery, la posizione ufficiale per l'hosting dei moduli PowerShell gestita da Microsoft. Per evitare di visualizzare questo avviso in futuro, esegua:

   ```powershell
   Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
   ```

   Sebbene non sia obbligatorio, si consiglia vivamente di creare utenti e gruppi separati per Devolutions Server. Ecco un prompt Bash per creare un utente e un gruppo entrambi denominati ***dvls*** con la directory di installazione impostata su `/opt/devolutions/dvls`:

   ```bash
   sudo useradd -N dvls
   sudo groupadd dvls
   sudo usermod -a -G dvls dvls
   # optional, add current user to dvls group
   sudo usermod -a -G dvls $(id -un)
   sudo mkdir -p /opt/devolutions/dvls
   sudo chown -R dvls:dvls /opt/devolutions/dvls
   sudo chmod 550 /opt/devolutions/dvls
   ```

### Download e installazione di Devolutions Server for Linux <a href="#downloading-and-installing-dvls-for-linux" id="downloading-and-installing-dvls-for-linux"></a>

1. Esegua lo script PowerShell qui sotto per scaricare l'ultima versione di Devolutions Server for Linux ed estrarre il file `.tar.gz` nel percorso `/opt/devolutions/dvls`:

   ```powershell
   $DVLSPath = "/opt/devolutions/dvls"
   $DVLSProductURL = "https://devolutions.net/productinfo.htm"

   $Result = (Invoke-RestMethod -Method 'GET' -Uri $DVLSProductURL) -Split "`r"

   $DVLSLinux = [PSCustomObject]@{
       "Version" = (($Result | Select-String DPSLinuxX64bin.Version) -Split "=")[-1].Trim()
       "URL"     = (($Result | Select-String DPSLinuxX64bin.Url) -Split "=")[-1].Trim()
       "Hash"    = (($Result | Select-String DPSLinuxX64bin.hash) -Split "=")[-1].Trim()
   }

   $DVLSDownloadPath = Join-Path -Path "/tmp" -ChildPath (([URI]$DVLSLinux.URL).Segments)[-1]

   Invoke-RestMethod -Method 'GET' -Uri $DVLSLinux.URL -OutFile $DVLSDownloadPath

   & tar -xzf $DVLSDownloadPath -C $DVLSPath --strip-components=1

   Remove-Item -Path $DVLSDownloadPath

   & sudo pwsh -Command {
     Param(
         $DVLSPath
     )

     chown -R dvls:dvls $DVLSPath
     chmod -R o-rwx $DVLSPath
     chmod 660 (Join-Path -Path $DVLSPath -ChildPath 'appsettings.json')
     chmod 770 (Join-Path -Path $DVLSPath -ChildPath 'App_Data')
     chown -R dvls:dvls $DVLSPath
   } -Args $DVLSPath

   Set-Location -Path $DVLSPath
   ```

   È preferibile che Devolutions Server sia in grado di rispondere tramite TLS. Se non esiste già un certificato, è possibile generarne rapidamente uno utilizzando questo prompt Bash:

   ```bash
   cd /opt/devolutions/dvls

   openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes -keyout cert.key -out cert.crt -subj "/CN=MYHOST" -addext "subjectAltName=DNS:MYHOST"
   openssl pkcs12 -export -out cert.pfx -inkey cert.key -in cert.crt -passout pass:
   ```

   Nell'esempio qui sopra, `subjectAltName` utilizza `DNS:.` Per rispondere solo su un IP, utilizzi invece `IP:`.

Si noti che il certificato `.pfx` generato non ha una password.

2. Utilizzando il modulo Devolutions.PowerShell, esegua l'installazione di Devolutions Server tramite PowerShell. Si assicuri di personalizzare i valori elencati qui:

   * `MYHOST`
   * `MSSQLHOST`
   * `DBUSERNAME`
   * `YOURSTRONGPASSWORD`
   * `MYEMAIL`

   ```powershell
   Import-Module -Name 'Devolutions.PowerShell'

   $DVLSPath = "/opt/devolutions/dvls"
   # Modify the $DVLSURI to use 'https' if using SSL
   $DVLSURI  = "http://MYHOST:5000/"

   $DVLSAdminUsername = 'dvls-admin'
   $DVLSAdminPassword = 'dvls-admin'
   $DVLSAdminEmail    = 'MYEMAIL'

   $Params = @{
       "DatabaseHost"           = "MSSQLHOST"
       "DatabaseName"           = "DSERVER"
       "DatabaseUserName"       = "DBUSERNAME"
       "DatabasePassword"       = "YOURSTRONGPASSWORD"
       "ServerName"             = "DSERVER"
       "AccessUri"              = $DVLSURI
       "HttpListenerUri"        = $DVLSURI
       "DPSPath"                = $DVLSPath
       "UseEncryptedconnection" = $False # Modify as needed
       "TrustServerCertificate" = $False # Modify as needed
       "EnableTelemetry"        = $True # Modify as needed
       "DisableEncryptConfig"   = $True
   }

   $Configuration = New-DPSInstallConfiguration @Params
   New-DPSAppsettings -Configuration $Configuration

   $Settings = Get-DPSAppSettings -ApplicationPath $DVLSPath

   New-DPSDatabase -ConnectionString $Settings.ConnectionStrings.LocalSqlServer
   Update-DPSDatabase -ConnectionString $Settings.ConnectionStrings.LocalSqlServer -InstallationPath $DVLSPath
   New-DPSDataSourceSettings -ConnectionString $Settings.ConnectionStrings.LocalSqlServer

   New-DPSEncryptConfiguration -ApplicationPath $DVLSPath
   New-DPSDatabaseAppSettings -Configuration $Configuration

   New-DPSAdministrator -ConnectionString $Settings.ConnectionStrings.LocalSqlServer -Name $DVLSAdminUsername -Password $DVLSAdminPassword -Email $DVLSAdminEmail
   ```

   Se è già stato generato un certificato, proceda a modificare il file `appsettings.json` per consentire a Kestrel di rispondere tramite TLS utilizzando questo script PowerShell:

   ```powershell
   Import-Module -Name 'Devolutions.PowerShell'

   $DVLSPath = '/opt/devolutions/dvls'

   $JSON = Get-Content -Path (Join-Path -Path $DVLSPath -ChildPath 'appsettings.json') | ConvertFrom-JSON -Depth 100

   $JSON.Kestrel.Endpoints.Http | Add-Member -MemberType NoteProperty -Name 'Certificate' -Value @{
       'Path'     = (Join-Path -Path $DVLSPath -ChildPath 'cert.pfx')
       'Password' = ''
   }

   $JSON | ConvertTo-JSON -Depth 100 | Set-Content -Path (Join-Path -Path $DVLSPath -ChildPath 'appsettings.json')

   $Settings = Get-DPSAppSettings -ApplicationPath $DVLSPath

   $AccessUri = (Get-DPSAccessUri -ConnectionString $Settings.ConnectionStrings.LocalSqlServer).AccessUri
   Set-DPSAccessUri -ApplicationPath $DVLSPath -ConnectionString $Settings.ConnectionStrings.LocalSqlServer -AccessURI ($AccessUri -Replace "http","https")

   & sudo pwsh -Command {
     Param(
         $DVLSPath
     )

     & chown dvls:dvls (Join-Path -Path $DVLSPath -ChildPath 'cert.pfx')
   } -Args $DVLSPath
   ```

   Per consentire l'esecuzione in background di Devolutions Server for Linux, si consiglia di creare un unit file per systemd tramite questo prompt Bash:

   ```bash
   sudo tee /etc/systemd/system/dvls.service > /dev/null <<EOT
   [Unit]
   Description=DVLS

   [Service]
   Type=simple
   Restart=always
   RestartSec=10
   User=dvls
   ExecStart=/opt/devolutions/dvls/Devolutions.Server
   WorkingDirectory=/opt/devolutions/dvls
   KillSignal=SIGINT
   SyslogIdentifier=dvls
   Environment="SCHEDULER_EMBEDDED=true"

   [Install]
   WantedBy=multi-user.target
   Alias=dvls.service
   EOT

   sudo systemctl daemon-reload
   ```
3. Per avviare Devolutions Server, esegua:

   ```bash
   sudo systemctl start dvls

   # View status
   sudo systemctl status dvls
   ```

### Accedere a Devolutions Server for Linux <a href="#accessing-dvls-linux" id="accessing-dvls-linux"></a>

Per impostazione predefinita, Devolutions Server for Linux resta in ascolto sulla porta 5000 sull'IP o sul nome host del sistema di installazione, che nella maggior parte dei casi si presenta così: `http://MYHOST:5000`. Tenga presente che al primo avvio possono verificarsi errori OAuth quando si tenta di accedere a Devolutions Server da un URL non configurato. In tal caso, aggiunga ulteriori URI su cui restare in ascolto, oppure modifichi quello primario eseguendo il seguente script in PowerShell:

```powershell
Import-Module -Name 'Devolutions.PowerShell'

$DVLSPath = "/opt/devolutions/dvls"

$Settings = Get-DPSAppSettings -ApplicationPath $DVLSPath
$ConnectionString = $Settings.ConnectionStrings.LocalSqlServer

Get-DPSAccessUri -ConnectionString $ConnectionString

Set-DPSAccessUri -ConnectionString $ConnectionString -ApplicationPath $DVLSPath -AccessURI 'http://10.10.0.20:5000/' -AdditionalAccessURIs @('http://ubuntu-2204:5000/')
```

Se Devolutions Server rimane inaccessibile al di fuori del sistema installato, verifichi se le porte del firewall necessarie sono aperte, aggiungendo Uncomplicated Firewall al prompt, ad esempio: `sudo ufw allow 5000`.

### Importare la chiave di crittografia di Devolutions Server <a href="#importing-devolutions-server-encryption-key" id="importing-devolutions-server-encryption-key"></a>

**Esportazione da un'installazione Windows esistente**

```powershell
Import-Module -Name 'Devolutions.PowerShell
$existingDVLSInstance = 'C:\my\path\dvlsInstance\'
$destination = 'C:\other\path\encryption.config'
Export-DPSEncryptionKeys -ApplicationPath $existingDVLSInstance -Destination $destination
```

**Importazione in una nuova installazione Linux**

```powershell
Import-Module -Name 'Devolutions.PowerShell
$newDvlsInstance = '/home/user/linuxDlvsInstance'
$keysToImport = '/path/to/encryption.config'
Import-DPSEncryptionKeys -ApplicationPath $newDvlsInstance -Filename $keysToImport
```

### Aggiornare Devolutions Server for Linux <a href="#updating-devolutions-server-for-linux" id="updating-devolutions-server-for-linux"></a>

Non estragga il nuovo archivio `.tar.gz` direttamente sopra `/opt/devolutions/dvls.` In tal modo si sovrascrivono `appsettings.json` ed `encryption.config`, il che rende il servizio incapace di avviarsi e può rendere indecifrabili i dati esistenti. Segua sempre il metodo di aggiornamento descritto in questa pagina.

1. Esegua il backup del database. Ecco come farlo per Microsoft SQL Server (Linux o remoto):

   ```
   /opt/mssql-tools18/bin/sqlcmd -S <MSSQLHOST> -U <DBUSERNAME> -P '<PASSWORD>' -C \
     -Q "BACKUP DATABASE [DSERVER] TO DISK = N'/var/opt/mssql/data/DSERVER-$(date +%F-%H%M).bak' WITH INIT, COMPRESSION;"
   ```

   Il percorso completo di `sqlcmd` evita l'errore **"**&#x63;ommand not found" nelle shell non di login in cui `/etc/profile.d/mssql-tools.sh` non è stato caricato.

   `-C` considera attendibile il certificato del server (necessario per le installazioni locali di SQL Server che utilizzano un certificato autofirmato).

   Esegua il backup in una directory scrivibile dall'utente MSSQL. `/var/opt/mssql/data/` funziona da subito.
2. Si assicuri che il file `.bak` esista e non sia vuoto prima di procedere al passaggio successivo.
3. Arresti il servizio Devolutions Server utilizzando il seguente script:

   ```bash
   sudo systemctl stop dvls.service
   sudo systemctl status dvls.service   # confirm inactive (dead)
   ```
4. Esegua il backup dei file di installazione e di configurazione. Tenga presente che `/opt/devolutions/dvls` è in modalità 550 ed è di proprietà di `dvls:dvls`, pertanto i cmdlet di backup devono essere eseguiti come root. Avvii PowerShell con `sudo pwsh`, quindi incolli questo script:

   ```powershell
   Import-Module Devolutions.PowerShell
   $DVLSPath        = '/opt/devolutions/dvls'
   $BackupBase      = "/var/backups/dvls/$(Get-Date -Format 'yyyy-MM-dd-HHmm')"
   $BackupConfig    = Join-Path $BackupBase 'config'
   $BackupInstall   = Join-Path $BackupBase 'installation'
   mkdir -p $BackupConfig $BackupInstall
   Backup-DPSConfigurationFiles -ApplicationPath $DVLSPath -BackupConfigurationPath $BackupConfig
   Backup-DPSInstallationFiles  -ApplicationPath $DVLSPath -BackupPath              $BackupInstall
   ```

   * `Backup-DPSConfigurationFiles` conserva: `appsettings.json`, `web.config` ed `encryption.config`.
   * `Backup-DPSInstallationFiles` conserva le cartelle personalizzate, la cartella di rilevamento delle anomalie ed eventuali risorse aggiunte dall'utente.
5. Svuoti la directory di installazione tranne `App_data`, poiché contiene lo stato di runtime che sopravvive agli aggiornamenti. Utilizzi questo script per farlo:

   ```bash
   sudo find /opt/devolutions/dvls -mindepth 1 -maxdepth 1 ! -name 'App_Data' -exec rm -rf {} +
   sudo tar -xzf /tmp/DVLS.<version>.linux-x64.tar.gz -C /opt/devolutions/dvls --strip-components=1
   ```

   Utilizzi `--strip-components` solo se l'archivio ha una cartella di primo livello.
6. Ripristini la configurazione e i dati personalizzati. In questo passaggio, `appsettings.json` (stringa di connessione al DB) e `web.config` vengono reinseriti nella nuova installazione. Poiché `encryption.config` è già stato conservato all'interno di `App_Data/` dal passaggio n. 5, `Restore-DPSConfigurationFiles` non lo collocherà nella radice dell'installazione, perché non è lì che si trova su Linux. Ecco lo script di ripristino:

   ```
   Restore-DPSCustomFolders            -BackupPath              $BackupInstall -ApplicationPath $DVLSPath
   Restore-DPSAnomalyDetectionFolder   -BackupPath              $BackupInstall -ApplicationPath $DVLSPath
   Restore-DPSConfigurationFiles       -BackupConfigurationPath $BackupConfig  -ApplicationPath $DVLSPath
   ```
7. Estragga le stringhe di connessione dal file `appsettings.json` ripristinato:

   ```
   $ConnectionString = (Get-DPSAppSettings -ApplicationPath $DVLSPath).ConnectionStrings.LocalSqlServer
   Update-DPSDatabase -ConnectionString $ConnectionString -InstallationPath $DVLSPath
   ```

   `Update-DPSDatabase` non stampa alcun output in caso di successo. Verifichi che abbia funzionato controllando che il comando abbia restituito il codice di uscita 0 e che, dopo aver avviato il servizio al passaggio n. 9, il journal mostri voci ***Migration done with status Done*** senza righe `[ERR]`.
8. Riapplichi la proprietà e le autorizzazioni:

   ```
   sudo chown -R dvls:dvls /opt/devolutions/dvls
   sudo chmod 550 /opt/devolutions/dvls
   sudo chmod 660 /opt/devolutions/dvls/appsettings.json
   sudo chmod 770 /opt/devolutions/dvls/App_Data
   # If a certs/ directory is in use:
   [ -d /opt/devolutions/dvls/certs ] && sudo chmod 750 /opt/devolutions/dvls/certs
   ```
9. Avvii il servizio e verifichi che funzioni correttamente:

   ```
   sudo systemctl start dvls.service
   sudo systemctl status dvls.service
   sudo journalctl -u dvls.service -n 100 --no-pager
   ```

#### Risoluzione dei problemi <a href="#troubleshooting" id="troubleshooting"></a>

* **Il servizio non si avvia, `appsettings.json` mancante o vuoto:** ripristini da `$BackupConfig/appsettings.json`, ripeta i passaggi n. 8 e 9.
* **L'accesso funziona ma le voci non vengono decrittografate:** `encryption.config` non è stato ripristinato. Copi `$BackupConfig/encryption.config` in `$DVLSPath/App_Data/`, corregga le autorizzazioni (`chown dvls:dvls` e `chmod 660`), quindi riavvii.
* **Errori dello schema del DB in fase di esecuzione:** `Update-DPSDatabase` è stato saltato o non è riuscito. Ripeta il passaggio n. 7.
* **Rollback completo:** arresti il servizio (veda il passaggio n. 3), svuoti `/opt/devolutions/dvls` tranne `App_Data/` (passaggio n. 5), copi il contenuto di `$BackupInstall` nuovamente in `/opt/devolutions/dvls`, ripristini `appsettings.json` da `$BackupConfig`, riapplichi la proprietà e le autorizzazioni dal passaggio n. 8, ripristini il DB dal file `.bak` prodotto al passaggio n. 1, quindi riavvii.

### Rimuovere Devolutions Server <a href="#removing-dvls" id="removing-dvls"></a>

Per rimuovere Devolutions Server, esegua il prompt Bash qui sotto e lo personalizzi per il sistema. Questo script si basa sul [modulo PowerShell DbaTools](https://dbatools.io/) per facilitare la rimozione del database MSSQL. Presuppone che `localhost` sia l'installazione MSSQL e `dvls` il nome del database.

```
# Remove DVLS on Linux, adjust as necessary
& sudo systemctl stop dvls.service
& sudo rm /etc/systemd/system/dvls.service
& sudo rm -rf /opt/devolutions/dvls
& sudo userdel -r dvls
& sudo groupdel dvls

Import-Module dbatools
$Credential = Get-Credential

Set-DbaToolsInsecureConnection

Remove-DbaDatabase -SqlInstance localhost -SqlCredential $Credential -Database 'dvls' -Confirm:$False
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.devolutions.net/server/it/knowledge-base/how-to-articles/install-devolutions-server-for-linux.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
