> 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/es/knowledge-base/how-to-articles/install-devolutions-server-for-linux.md).

# Instalar Devolutions Server para Linux

Devolutions Server está disponible para Linux con Microsoft Kestrel como servidor web integrado y Microsoft PowerShell 7 para la instalación por línea de comandos. El presente tema muestra cómo instalar manualmente Devolutions Server for Linux mediante indicaciones de Bash y scripts de PowerShell, así como cómo acceder a él y eliminarlo.

Como alternativa, Devolutions Server se puede instalar automáticamente utilizando los scripts que se encuentran en el [repositorio ScriptLibrary de GitHub de Devolutions](https://github.com/Devolutions/ScriptLibrary/tree/main/DVLSForLinux).

### Instalación de los requisitos previos <a href="#installing-prerequisites" id="installing-prerequisites"></a>

1. Si Microsoft SQL Server no está ya instalado, ejecute la siguiente indicación de Bash con la variable `MSSQL_SA_PASSWORD` cambiada por una contraseña robusta:

   ```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
   ```

   `MSSQL_PID` está establecido en ***evaluation*** en este ejemplo, pero en su lugar se puede introducir aquí una clave de producto.

{% hint style="warning" %}
Microsoft solo admite [determinadas versiones de SQL](/server/es/readme/system-requirements.md#software-dependencies). Consulte la documentación de Microsoft para asegurarse de que su versión de SQL esté oficialmente admitida para su distribución.
{% endhint %}

2. Ejecute esta indicación de Bash para instalar 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
   ```

Asegúrese de que la instalación se realice en un directorio accesible para el usuario actual, ya que la línea de comandos `wget` descarga un paquete `.deb` en dicho directorio.

3. Elija si desea instalar el [módulo Devolutions.PowerShell](https://www.powershellgallery.com/packages/Devolutions.PowerShell/) para el usuario actual o para todos los usuarios.

   * **Para el usuario actual** (ubicación: `/.local/share/powershell/Modules`), ejecute:

     ```powershell
     Install-Module -Name 'Devolutions.PowerShell' -Confirm:$False
     ```
   * **Para todos los usuarios** (ubicación: `/opt/microsoft/powershell/7/Modules`), ejecute:

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

   Es probable que aparezca una advertencia indicando que la instalación proviene de un repositorio que no es de confianza. El módulo está alojado en PowerShell Gallery, la ubicación oficial para alojar módulos de PowerShell gestionada por Microsoft. Para evitar ver esta advertencia en el futuro, ejecute:

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

   Aunque no es obligatorio, se recomienda encarecidamente aprovisionar usuarios y grupos separados para Devolutions Server. Aquí tiene una indicación de Bash para crear un usuario y un grupo, ambos denominados ***dvls***, con el directorio de instalación establecido en `/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
   ```

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

1. Ejecute el script de PowerShell que figura a continuación para descargar la última versión de Devolutions Server for Linux y extraer el fichero `.tar.gz` en la ubicación `/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
   ```

   Lo mejor es que Devolutions Server pueda responder a través de TLS. Si aún no existe un certificado, se puede generar uno rápidamente utilizando esta indicación de 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:
   ```

   En el ejemplo anterior, `subjectAltName` utiliza `DNS:.` Para responder únicamente en una IP, utilice `IP:` en su lugar.

Tenga en cuenta que el certificado `.pfx` generado no tiene contraseña.

2. Utilizando el módulo Devolutions.PowerShell, ejecute la instalación de Devolutions Server a través de PowerShell. Asegúrese de personalizar los valores que se indican aquí:

   * `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
   ```

   Si ya se ha generado un certificado, proceda a modificar el fichero `appsettings.json` para permitir que Kestrel responda a través de TLS utilizando este script de 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
   ```

   Para ofrecer la ejecución en segundo plano de Devolutions Server for Linux, se recomienda crear un fichero de unidad para systemd mediante esta indicación de 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. Para iniciar Devolutions Server, ejecute:

   ```bash
   sudo systemctl start dvls

   # View status
   sudo systemctl status dvls
   ```

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

De forma predeterminada, Devolutions Server for Linux escucha en el puerto 5000 en la IP o el nombre de host del sistema de instalación, lo que habitualmente tiene este aspecto: `http://MYHOST:5000`. Tenga en cuenta que pueden producirse errores de OAuth en el primer inicio al intentar acceder a Devolutions Server desde una URL no configurada. Si es el caso, añada URI adicionales para escuchar, o modifique la principal ejecutando el siguiente script en 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/')
```

Si Devolutions Server sigue siendo inaccesible fuera del sistema instalado, compruebe si los puertos de cortafuegos necesarios están abiertos, añadiendo Uncomplicated Firewall a la indicación, por ejemplo: `sudo ufw allow 5000`.

### Importar la clave de cifrado de Devolutions Server <a href="#importing-devolutions-server-encryption-key" id="importing-devolutions-server-encryption-key"></a>

**Exportar desde una instalación de Windows existente**

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

**Importar a una nueva instalación de Linux**

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

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

No extraiga el nuevo archivo `.tar.gz` directamente sobre `/opt/devolutions/dvls.` Hacerlo sobrescribe `appsettings.json` y `encryption.config`, lo que deja el servicio sin poder iniciarse y puede hacer que los datos existentes no se puedan descifrar. Siga siempre el método de actualización detallado en esta página.

1. Haga una copia de seguridad de la base de datos. Así es como se hace en 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;"
   ```

   La ruta completa a `sqlcmd` evita el error **"**&#x63;ommand not found" en shells sin inicio de sesión donde no se ha cargado `/etc/profile.d/mssql-tools.sh`.

   `-C` confía en el certificado del servidor (necesario para instalaciones locales de SQL Server que utilizan un certificado autofirmado).

   Haga la copia de seguridad en un directorio en el que el usuario MSSQL pueda escribir. `/var/opt/mssql/data/` funciona de forma nativa.
2. Asegúrese de que el fichero `.bak` existe y no está vacío antes de continuar con el paso siguiente.
3. Detenga el servicio de Devolutions Server utilizando el siguiente script:

   ```bash
   sudo systemctl stop dvls.service
   sudo systemctl status dvls.service   # confirm inactive (dead)
   ```
4. Haga una copia de seguridad de los ficheros de instalación y de configuración. Tenga en cuenta que `/opt/devolutions/dvls` está en modo 550 y pertenece a `dvls:dvls`, por lo que los cmdlets de copia de seguridad deben ejecutarse como root. Inicie PowerShell con `sudo pwsh` y, a continuación, pegue este 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` y `encryption.config`.
   * `Backup-DPSInstallationFiles` conserva las carpetas personalizadas, la carpeta de detección de anomalías y cualquier recurso añadido por el usuario.
5. Vacíe el directorio de instalación excepto `App_data`, ya que contiene el estado de ejecución que se conserva entre actualizaciones. Utilice este script para hacerlo:

   ```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
   ```

   Utilice `--strip-components` solo si el archivo tiene una carpeta de nivel superior.
6. Restaure la configuración y los datos personalizados. En este paso, `appsettings.json` (cadena de conexión a la BD) y `web.config` se vuelven a colocar en la nueva instalación. Dado que `encryption.config` ya se conservó dentro de `App_Data/` en el paso n.º 5, `Restore-DPSConfigurationFiles` no lo colocará en la raíz de la instalación, porque no es ahí donde se encuentra en Linux. Este es el script de restauración:

   ```
   Restore-DPSCustomFolders            -BackupPath              $BackupInstall -ApplicationPath $DVLSPath
   Restore-DPSAnomalyDetectionFolder   -BackupPath              $BackupInstall -ApplicationPath $DVLSPath
   Restore-DPSConfigurationFiles       -BackupConfigurationPath $BackupConfig  -ApplicationPath $DVLSPath
   ```
7. Extraiga las cadenas de conexión del fichero `appsettings.json` restaurado:

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

   `Update-DPSDatabase` no imprime ningún resultado cuando se realiza correctamente. Verifique que ha funcionado comprobando que el comando devolvió el código de salida 0 y que, después de iniciar el servicio en el paso n.º 9, el diario muestra entradas ***Migration done with status Done*** sin líneas `[ERR]`.
8. Vuelva a aplicar la propiedad y los permisos:

   ```
   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. Inicie el servicio y compruebe si funciona correctamente:

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

#### Resolución de problemas <a href="#troubleshooting" id="troubleshooting"></a>

* **El servicio no se inicia, `appsettings.json` falta o está vacío:** restáurelo desde `$BackupConfig/appsettings.json` y repita los pasos n.º 8 y 9.
* **El inicio de sesión funciona, pero las entradas no se descifran:** `encryption.config` no se restauró. Copie `$BackupConfig/encryption.config` en `$DVLSPath/App_Data/`, corrija los permisos (`chown dvls:dvls` y `chmod 660`) y, a continuación, reinicie.
* **Errores de esquema de BD en tiempo de ejecución:** se omitió `Update-DPSDatabase` o falló. Repita el paso n.º 7.
* **Reversión completa:** detenga el servicio (véase el paso n.º 3), vacíe `/opt/devolutions/dvls` excepto `App_Data/` (paso n.º 5), copie el contenido de `$BackupInstall` de nuevo en `/opt/devolutions/dvls`, restaure `appsettings.json` desde `$BackupConfig`, vuelva a aplicar la propiedad y los permisos del paso n.º 8, restaure la BD desde el `.bak` generado en el paso n.º 1 y, a continuación, reinicie.

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

Para eliminar Devolutions Server, ejecute la indicación de Bash que figura a continuación y personalícela para el sistema. Este script se basa en el [módulo de PowerShell DbaTools](https://dbatools.io/) para facilitar la eliminación de la base de datos MSSQL. Supone que `localhost` es la instalación de MSSQL y `dvls` el nombre de la base de datos.

```
# 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/es/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.
