Activar o desactivar el RDP (protocolo de escritorio remoto) en estaciones de trabajo mediante PowerShell

Activar o desactivar el RDP: puntos clave

  • El RDP es una herramienta crucial para los profesionales de TI, ya que permite el acceso remoto a los ordenadores.
  • El script PowerShell que veremos hoy ofrece un método simplificado para activar o desactivar el RDP en estaciones de trabajo.
  • Se realizan dos acciones principales: modificar la configuración del registro y ajustar las reglas del firewall.
  • El script requiere privilegios de administrador y comprueba si la máquina es una estación de trabajo.
  • Aunque el RDP ofrece comodidad, puede plantear riesgos de seguridad si está mal configurado.
  • Se recomienda supervisar y utilizar métodos de autenticación fuertes para un uso seguro del RDP.
  • Plataformas como NinjaOne complementan el script, ofreciendo una solución integral de gestión de TI.

El Protocolo de Escritorio Remoto (RDP) es una herramienta esencial en el arsenal de los profesionales de TI, que permite a los usuarios conectarse remotamente a otro ordenador a través de una conexión de red. Pero, como cualquier herramienta potente, el RDP requiere una gestión prudente, especialmente a medida que aumentan los problemas de seguridad. Este post profundiza en un script de PowerShell diseñado para gestionar y configurar los ajustes del Escritorio remoto (RDP) en estaciones de trabajo.

Antecedentes

PowerShell se ha convertido rápidamente en una herramienta fundamental para los administradores de TI debido a su flexibilidad y profundidad. El script proporcionado aprovecha este potencial ofreciendo un método conciso para activar o desactivar el RDP para estaciones de trabajo. A medida que los entornos informáticos se vuelven más complejos, las soluciones racionalizadas como este script son indispensables para los proveedores de servicios gestionados (MSP) y los profesionales de la TI. Asegurarse de que el RDP está correctamente configurado es crucial, ya que cualquier error de configuración podría exponer vulnerabilidades.

El script para activar o desactivar el RDP

<#
.SYNOPSIS
    Enables or Disables RDP for workstations only.
.DESCRIPTION
    Enables or Disables RDP for workstations only.
.EXAMPLE
    -Disable
    Disables RDP for a workstation.
.EXAMPLE
    -Enable
    Enables RDP for a workstation.
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
#>
[CmdletBinding(DefaultParameterSetName = "Disable")]
param (
    [Parameter(Mandatory = $true, ParameterSetName = "Enable")]
    [switch]
    $Enable,
    [Parameter(Mandatory = $true, ParameterSetName = "Disable")]
    [switch]
    $Disable
)

begin {
    function Set-ItemProp {
        param (
            $Path,
            $Name,
            $Value,
            [ValidateSet("DWord", "QWord", "String", "ExpandedString", "Binary", "MultiString", "Unknown")]
            $PropertyType = "DWord"
        )
        # Do not output errors and continue
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
        if (-not $(Test-Path -Path $Path)) {
            # Check if path does not exist and create the path
            New-Item -Path $Path -Force | Out-Null
        }
        if ((Get-ItemProperty -Path $Path -Name $Name)) {
            # Update property and print out what it was changed from and changed to
            $CurrentValue = Get-ItemProperty -Path $Path -Name $Name
            try {
                Set-ItemProperty -Path $Path -Name $Name -Value $Value -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error $_
            }
            Write-Host "$Path$Name changed from $CurrentValue to $Value"
        }
        else {
            # Create property with value
            try {
                New-ItemProperty -Path $Path -Name $Name -Value $Value -PropertyType $PropertyType -Force -Confirm:$false -ErrorAction Stop | Out-Null
            }
            catch {
                Write-Error $_
            }
            Write-Host "Set $Path$Name to $Value"
        }
        $ErrorActionPreference = [System.Management.Automation.ActionPreference]::Continue
    }
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    }

    # Registry settings
    $Path = 'HKLM:\System\CurrentControlSet\Control\Terminal Server'
    $Name = "fDenyTSConnections"
    $RegEnable = 0
    $RegDisable = 1

    $osInfo = Get-CimInstance -ClassName Win32_OperatingSystem
    $IsWorkstation = if ($osInfo.ProductType -eq 1) {
        $true
    }
    else {
        $false
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    if (-not $IsWorkstation) {
        # System is a Domain Controller or Server
        Write-Error "System is a Domain Controller or Server. Skipping."
        exit 1
    }

    # Registry
    if ($Disable) {
        $RegCheck = $null
        $RegCheck = $(Get-ItemPropertyValue -Path $Path -Name $Name -ErrorAction SilentlyContinue)
        if ($null -eq $RegCheck) {
            $RegCheck = 0
        }
        if ($RegDisable -ne $RegCheck) {
            Set-ItemProp -Path $Path -Name $Name -Value $RegDisable
            Write-Host "Disabled $Path$Name"
        }
        else {
            Write-Host "$Path$Name already Disabled."
        }
    }
    elseif ($Enable) {
        $RegCheck = $null
        $RegCheck = $(Get-ItemPropertyValue -Path $Path -Name $Name -ErrorAction SilentlyContinue)
        if ($null -eq $RegCheck) {
            $RegCheck = 0
        }
        if ($RegEnable -ne $RegCheck) {
            Set-ItemProp -Path $Path -Name $Name -Value $RegEnable
            Write-Host "Enabled $Path$Name"
        }
        else {
            Write-Host "$Path$Name already Enabled."
        }
    }
    else {
        Write-Error "Enable or Disable was not specified."
        exit 1
    }

    # Firewall
    if ($Disable) {
        # Disable if was enabled and Disable was used
        try {
            Disable-NetFirewallRule -DisplayGroup "Remote Desktop" -ErrorAction Stop
        }
        catch {
            Write-Error $_
            Write-Host "Remote Desktop firewall group is missing?"
        }
        Write-Host "Disabled Remote Desktop firewall rule groups."
    }
    elseif ($Enable) {
        # Enable if was disabled and Enable was used
        try {
            Enable-NetFirewallRule -DisplayGroup "Remote Desktop" -ErrorAction Stop
        }
        catch {
            Write-Error $_
            Write-Host "Remote Desktop firewall group is missing?"
        }
        Write-Host "Enabled Remote Desktop firewall rule groups."
    }
    else {
        Write-Error "Enable or Disable was not specified."
        exit 1
    }
}
end {}

 

Accede a más de 300 scripts en el Dojo de NinjaOne

Obtén acceso

Análisis detallado

  • Parámetros: el script utiliza dos parámetros, Enable y Disable, que dictan si el RDP debe activarse o desactivarse. Son mutuamente excluyentes; sólo se puede utilizar uno a la vez.
  • Funciones de ayuda: dos funciones ayudan en la tarea principal:
  • Set-ItemProp: actualiza o crea propiedades del registro, gestionando los posibles errores y manteniendo informado al usuario.
  • Test-IsElevated: comprueba si el script se ejecuta con privilegios de administrador.
  • Proceso: este es el componente principal del script. Comienza comprobando si se dispone de derechos de administrador y si la máquina es una estación de trabajo. A continuación procede a:
  • Modificar la configuración del registro para activar o desactivar el RDP.
  • Ajustar la configuración del firewall para permitir o bloquear el tráfico RDP.

Posibles casos de uso

Imagina una empresa mediana con varias estaciones de trabajo para sus empleados. El departamento de TI, por motivos de seguridad, ha desactivado el RDP en todas las máquinas. Sin embargo, un consultor externo necesita tener acceso remoto a una estación de trabajo para realizar diagnósticos. Usando este script para activar o desactivar el RDP, el administrador de TI puede habilitar el RDP sin problemas en esa estación de trabajo específica y deshabilitarlo una vez que la tarea se haya realizado.

Comparaciones

Aunque existen herramientas basadas en GUI y otros métodos para gestionar el RDP, el script proporcionado para activar o desactivar el RDP ofrece las siguientes ventajas:

  • Escalabilidad: puede ejecutarse en varias estaciones de trabajo mediante un script o un programador de tareas.
  • Flexibilidad: se integra fácilmente en flujos de trabajo informáticos más amplios.
  • Transparencia: al ser de código abierto, el equipo de TI puede validar y ajustar el script para adaptarlo a necesidades específicas.

FAQ

  • ¿Este script para activar o desactivar el RDP puede ejecutarse en servidores?
    No, el script comprueba específicamente si la máquina es una estación de trabajo antes de ejecutarse.
  • ¿Qué ocurre si el script se ejecuta sin privilegios de administrador?
    Aparecerá un mensaje de error solicitando al usuario que se ejecute con privilegios de administrador.

Implicaciones

Aunque habilitar el RDP es conveniente, un RDP expuesto puede ser un riesgo de seguridad significativo. Los ciberdelincuentes suelen aprovecharse de los RDP mal configurados. Por tanto, es imperativo equilibrar la comodidad con la seguridad.

Recomendaciones

  • Desactiva siempre el RDP cuando no esté en uso.
  • Supervisa los registros RDP en busca de actividades sospechosas.
  • Emplea métodos de autenticación fuertes cuando el RDP esté habilitado.

Reflexiones finales

Herramientas como NinjaOne mejoran las operaciones de TI, ofreciendo una plataforma centralizada para gestionar y supervisar redes, dispositivos y mucho más. A la hora de integrar soluciones como el script PowerShell que hemos visto en marcos de TI más amplios, plataformas como NinjaOne proporcionan una supervisión y una eficacia inestimables.

Al comprender e implementar scripts de PowerShell como el que hemos visto anteriormente, los profesionales de TI pueden reforzar su eficacia y la seguridad de sus entornos de trabajo. Combinar esto con potentes herramientas como NinjaOne hace que la gestión de TI sea aún más sólida.

Próximos pasos

La creación de un equipo de TI próspero y eficaz requiere contar con una solución centralizada que se convierta en tu principal herramienta de prestación de servicios. NinjaOne permite a los equipos de TI supervisar, gestionar, proteger y dar soporte a todos sus dispositivos, estén donde estén, sin necesidad de complejas infraestructuras locales.

Obtén más información sobre NinjaOne Endpoint Management, echa un vistazo a un tour en vivoo tu prueba gratuita de la plataforma NinjaOne.

Categorías:

Quizá también te interese…

Ver demo×
×

¡Vean a NinjaOne en acción!

Al enviar este formulario, acepto la política de privacidad de NinjaOne.

Términos y condiciones de NinjaOne

Al hacer clic en el botón «Acepto» que aparece a continuación, estás aceptando los siguientes términos legales, así como nuestras Condiciones de uso:

  • Derechos de propiedad: NinjaOne posee y seguirá poseyendo todos los derechos, títulos e intereses sobre el script (incluidos los derechos de autor). NinjaOne concede al usuario una licencia limitada para utilizar el script de acuerdo con estos términos legales.
  • Limitación de uso: solo podrás utilizar el script para tus legítimos fines personales o comerciales internos, y no podrás compartirlo con terceros.
  • Prohibición de republicación: bajo ninguna circunstancia está permitido volver a publicar el script en ninguna biblioteca de scripts que pertenezca o esté bajo el control de cualquier otro proveedor de software.
  • Exclusión de garantía: el script se proporciona «tal cual» y «según disponibilidad», sin garantía de ningún tipo. NinjaOne no promete ni garantiza que el script esté libre de defectos o que satisfaga las necesidades o expectativas específicas del usuario.
  • Asunción de riesgos: el uso que el usuario haga del script corre por su cuenta y riesgo. El usuario reconoce que existen ciertos riesgos inherentes al uso del script, y entiende y asume cada uno de esos riesgos.
  • Renuncia y exención: el usuario no hará responsable a NinjaOne de cualquier consecuencia adversa o no deseada que resulte del uso del script y renuncia a cualquier derecho o recurso legal o equitativo que pueda tener contra NinjaOne en relación con su uso del script.
  • CLUF: si el usuario es cliente de NinjaOne, su uso del script está sujeto al Contrato de Licencia para el Usuario Final (CLUF).