Diagnóstico de Anomalias no Acesso RDP: Guia Prático para Sysadmins

Duarte Spínola  |  2026-07-12

O RDP (Remote Desktop Protocol) é a ferramenta de administração remota mais usada em ambientes Windows. Quando falha, o sysadmin perde acesso ao servidor e tem de recorrer à consola iLO/iDRAC ou deslocar-se fisicamente. As anomalias mais comuns são: impossibilidade de conectar (firewall, NLA, serviço parado), lentidão (rede, gráficos, bandwidth), desligamentos inesperados (licenças RDS, timeouts, GPO), e ecrã preto (perfis corrompidos, GPU, display driver). O diagnóstico começa sempre por isolar a camada afectada: rede, autenticação, serviço, ou cliente. Referência: Remote Desktop Services — Microsoft Learn.

O RDP usa a porta TCP 3389 por defeito. Em Windows Server 2022+ com RDP Shortpath, também usa UDP 3389 para streaming de gráficos. Se o UDP está bloqueado, o RDP funciona mas com pior experiência (sem ajuste adaptativo de bitrate).

1. Camadas de Diagnóstico RDP

Camada Sintoma Ferramenta de diagnóstico
Rede Não conecta, timeout Test-NetConnection, psping, ping
Firewall Conexão recusada (porta fechada) Windows Firewall, Get-NetFirewallRule
Serviço Serviço parado, não responde Get-Service TermService
Autenticação (NLA) Erro de autenticação antes de conectar GPO, SystemPropertiesRemote
Licenciamento RDS Aviso de licença, desligamento após X dias RD Licensing Diagnoser, lwdiag
Sessão Sessão presa, ecrã preto, sem resposta qwinsta, quser, Task Manager
Performance Lag, lentidão, gráficos lentos iperf3, PerfMon, Group Policy RDP settings
Perfil Ecrã preto após login, perfil temporário Event Viewer, net user, perfil corrompido
Cliente Cliente mstsc desactualizado, compatibilidade Windows Update, versão do cliente

2. Passo 1 — Conectividade de Rede

Antes de investigar o RDP, confirmar que a rede está funcional entre o cliente e o servidor.

2.1 Testar conectividade à porta 3389

<span style=”color:#6c7086;”># Testar TCP 3389 (PowerShell 5.1+)</span>
Test-NetConnection -ComputerName servidor01 -Port 3389

<span style=”color:#6c7086;”># Output esperado:</span>
<span style=”color:#6c7086;”># ComputerName : servidor01</span>
<span style=”color:#6c7086;”># RemoteAddress : 192.168.1.100</span>
<span style=”color:#6c7086;”># RemotePort : 3389</span>
<span style=”color:#6c7086;”># InterfaceAlias : Ethernet</span>
<span style=”color:#6c7086;”># SourceAddress : 192.168.1.50</span>
<span style=”color:#6c7086;”># TcpTestSucceeded : True</span>

<span style=”color:#6c7086;”># Alternativa com PSPing (mais detalhado — mede latência TCP)</span>
psping -t servidor01:3389

Se TcpTestSucceeded for False:

  1. Verificar se o servidor está online (ping servidor01)
  2. Verificar Windows Firewall no servidor (secção 3)
  3. Verificar firewalls intermédios (router, switch, VPN)
  4. Verificar se a porta 3389 não foi alterada (secção 2.2)

2.2 Verificar porta RDP

<span style=”color:#6c7086;”># No servidor — verificar a porta RDP configurada</span>
Get-ItemProperty -Path “HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” -Name “PortNumber”

<span style=”color:#6c7086;”># PortNumber = 3389 (padrão decimal)</span>
<span style=”color:#6c7086;”># Se for diferente, o cliente tem de usar servidor01:porta</span>

2.3 Testar com PSPing (latência TCP)

<span style=”color:#6c7086;”># PSPing mede latência TCP real à porta RDP (não apenas ICMP)</span>
psping -t servidor01:3389 -n 100

<span style=”color:#6c7086;”># Interpretar:</span>
<span style=”color:#6c7086;”># < 1 ms — excelente (LAN)</span>
<span style=”color:#6c7086;”># 1-10 ms — bom (LAN/WAN próxima)</span>
<span style=”color:#6c7086;”># 10-50 ms — aceitável (WAN)</span>
<span style=”color:#6c7086;”># > 50 ms — lag visível no RDP</span>
<span style=”color:#6c7086;”># > 150 ms — experiência degradada (considerar RDP Shortpath ou RDS Gateway)</span>

Referência: PSPing — Sysinternals.

3. Passo 2 — Firewall e Serviço

3.1 Verificar Windows Firewall no servidor

<span style=”color:#6c7086;”># Verificar regras de firewall para RDP</span>
Get-NetFirewallRule -DisplayGroup “Remote Desktop” | Select DisplayName, Enabled, Direction, Action

<span style=”color:#6c7086;”># Output esperado:</span>
<span style=”color:#6c7086;”># DisplayName Enabled Direction Action</span>
<span style=”color:#6c7086;”># ———– ——- ——— ——</span>
<span style=”color:#6c7086;”># Remote Desktop – User Mode… True Inbound Allow</span>
<span style=”color:#6c7086;”># Remote Desktop – Shadow Sess… True Inbound Allow</span>
<span style=”color:#6c7086;”># Remote Desktop – Remote Appl… True Inbound Allow</span>

<span style=”color:#6c7086;”># Se as regras estão desactivadas, activar:</span>
Enable-NetFirewallRule -DisplayGroup “Remote Desktop”

3.2 Verificar serviço TermService

<span style=”color:#6c7086;”># Verificar estado do serviço Remote Desktop Services</span>
Get-Service TermService

<span style=”color:#6c7086;”># Se estiver parado, iniciar:</span>
Start-Service TermService

<span style=”color:#6c7086;”># Verificar tipo de arranque (deve ser Automatic)</span>
Get-Service TermService | Select Name, Status, StartType

<span style=”color:#6c7086;”># Se estiver Disabled, activar:</span>
Set-Service TermService -StartupType Automatic
Start-Service TermService

3.3 Verificar se RDP está activado no servidor

<span style=”color:#6c7086;”># Verificar estado do RDP</span>
Get-ItemProperty -Path “HKLM:\System\CurrentControlSet\Control\Terminal Server” -Name “fDenyTSConnections”

<span style=”color:#6c7086;”># fDenyTSConnections = 0 → RDP activado</span>
<span style=”color:#6c7086;”># fDenyTSConnections = 1 → RDP desactivado</span>

<span style=”color:#6c7086;”># Activar RDP via PowerShell:</span>
Set-ItemProperty -Path “HKLM:\System\CurrentControlSet\Control\Terminal Server” -Name “fDenyTSConnections” -Value 0

<span style=”color:#6c7086;”># Ou via GUI: System Properties → Remote → Allow remote connections</span>

Referência: Allow access to RDP — Microsoft Learn.

4. Passo 3 — NLA e Autenticação

O Network Level Authentication (NLA) exige que o cliente autentique antes de estabelecer a sessão RDP. Se NLA está activado mas o cliente não suporta (cliente antigo, ou CredSSP desactivado), a conexão é recusada.

4.1 Verificar NLA no servidor

<span style=”color:#6c7086;”># Verificar NLA</span>
Get-ItemProperty -Path “HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” -Name “UserAuthentication”

<span style=”color:#6c7086;”># UserAuthentication = 0 → NLA desactivado</span>
<span style=”color:#6c7086;”># UserAuthentication = 1 → NLA activado (recomendado)</span>

<span style=”color:#6c7086;”># Desactivar NLA temporariamente para diagnóstico:</span>
Set-ItemProperty -Path “HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” -Name “UserAuthentication” -Value 0

Se desactivar NLA resolve o problema, a causa é CredSSP no cliente. Verificar se o cliente tem a actualização de segurança CredSSP instalada (KB patched para CVE-2018-0886) e se “Allow connections only from computers running Remote Desktop with Network Level Authentication” está compatível com o cliente.

4.2 Verificar utilizadores/grupos autorizados

<span style=”color:#6c7086;”># Verificar quem tem permissão de RDP</span>
Get-ItemProperty -Path “HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” -Name “SecurityDescriptor”

<span style=”color:#6c7086;”># Ou via GUI: System Properties → Remote → Select Users</span>

<span style=”color:#6c7086;”># Verificar membros do grupo Remote Desktop Users</span>
Get-LocalGroupMember -Group “Remote Desktop Users”

<span style=”color:#6c7086;”># Adicionar utilizador ao grupo RDP</span>
Add-LocalGroupMember -Group “Remote Desktop Users” -Member “utilizador”

4.3 Verificar GPO que afecta RDP

<span style=”color:#6c7086;”># Listar GPOs que afectam RDP</span>
gpresult /h C:\temp\gpresult.html

<span style=”color:#6c7086;”># Procurar no relatório por:</span>
<span style=”color:#6c7086;”># – Computer Configuration → Administrative Templates → Windows Components → Remote Desktop Services</span>
<span style=”color:#6c7086;”># – Set time limit for active/disconnected/idle sessions</span>
<span style=”color:#6c7086;”># – Require use of specific security layer for remote connections</span>

5. Passo 4 — Licenciamento RDS

Em ambientes com Remote Desktop Services (RDS) — não em administração remota (que permite 2 sessões por defeito) — o licenciamento é uma causa comum de desligamentos.

5.1 Diagnóstico de licenciamento

<span style=”color:#6c7086;”># Abrir RD Licensing Diagnoser (GUI)</span>
licmgr.exe

<span style=”color:#6c7086;”># Ou via PowerShell — verificar servidor de licenças</span>
Get-RDLicenseConfiguration

<span style=”color:#6c7086;”># Verificar modo de licenciamento</span>
Get-ItemProperty -Path “HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” -Name “LicensingMode”

<span style=”color:#6c7086;”># LicensingMode:</span>
<span style=”color:#6c7086;”># 1 = Per Device</span>
<span style=”color:#6c7086;”># 2 = Per User</span>
<span style=”color:#6c7086;”># 4 = Per Session (deprecated)</span>

5.2 Sintomas de problema de licenciamento

Sintoma Causa provável
“The remote session was disconnected because there are no Remote Desktop client access licenses available” Servidor de licenças não tem licenças disponíveis ou não é acessível
“Your Remote Desktop Services client access license is no longer valid” Licença expirada ou corrompida no cliente
Aviso “X days until licence expires” Período de tolerância após instalação de RDS
Desligamento imediato após login Modo de licenciamento incorrecto (Per Device vs Per User)

5.3 Corrigir licenças corrompidas no cliente

<span style=”color:#6c7086;”># No cliente — remover licenças RDS corrompidas</span>
<span style=”color:#6c7086;”># As licenças são guardadas em chaves de registry:</span>
<span style=”color:#6c7086;”># HKLM\SOFTWARE\Microsoft\MSLicensing\Store</span>

<span style=”color:#6c7086;”># Parar serviço TermService antes de alterar</span>
Stop-Service TermService -Force

<span style=”color:#6c7086;”># Remover chaves de licenciamento</span>
Remove-Item -Path “HKLM:\SOFTWARE\Microsoft\MSLicensing\Store” -Recurse -Force

<span style=”color:#6c7086;”># Reiniciar serviço</span>
Start-Service TermService

<span style=”color:#6c7086;”># Conectar via RDP — o cliente vai buscar nova licença ao servidor</span>

6. Passo 5 — Sessões Presas e Ecrã Preto

6.1 Listar sessões RDP activas

<span style=”color:#6c7086;”># Listar sessões no servidor</span>
qwinsta

<span style=”color:#6c7086;”># Output:</span>
<span style=”color:#6c7086;”># SESSIONNAME USERNAME ID STATE TYPE DEVICE</span>
<span style=”color:#6c7086;”># services 0 Disc</span>
<span style=”color:#6c7086;”># console Administrator 1 Active</span>
<span style=”color:#6c7086;”># rdp-tcp#0 user1 42 Active</span>
<span style=”color:#6c7086;”># rdp-tcp 65536 Listen</span>

<span style=”color:#6c7086;”># Ou com quser (mais detalhes)</span>
quser

<span style=”color:#6c7086;”># Output:</span>
<span style=”color:#6c7086;”># USERNAME SESSIONNAME ID STATE IDLE TIME LOGON</span>
<span style=”color:#6c7086;”># Administrator console 1 active . 14:00 12/07</span>
<span style=”color:#6c7086;”># user1 rdp-tcp#0 42 active 5 09:30 12/07</span>

Referência: qwinsta — Microsoft Learn, quser — Microsoft Learn.

6.2 Desligar/fazer logoff de sessão presa

<span style=”color:#6c7086;”># Desligar sessão por ID (usar ID do qwinsta/quser)</span>
Disconnect-RDSession -ID 42

<span style=”color:#6c7086;”># Ou via linha de comandos</span>
logoff 42

<span style=”color:#6c7086;”># Fazer logoff de todas as sessões excepto a consola</span>
query session | findstr “rdp” | for /f “tokens=3” %i in (‘more’) do logoff %i

6.3 Ecrã preto após login

O ecrã preto (black screen of death) é uma das anomalias mais frustrantes do RDP. O utilizador autentica-se, a janela mostra “Configuring remote session” e depois fica preta.

Causas mais comuns:

Causa Verificar Solução
Display driver (WDDM) Event Viewer → System Desactivar WDDM graphics para RDP via GPO
Perfil corrompido Event Viewer → Application (userenv errors) Criar perfil novo
Shell Explorer.exe crash Task Manager (Ctrl+Shift+Esc na sessão RDP) Reiniciar explorer.exe
GPO startup script bloqueante gpresult /h Remover script bloqueante
Antivirus a bloquear logon Logs do antivirus Excluir C:\Windows\System32\winlogon.exe
GPU parada (RDPDD) Device Manager → Display adapters Desactivar GPU virtual RDP

6.4 Desactivar WDDM para RDP (ecrã preto)

<span style=”color:#6c7086;”># Desactivar WDDM graphics driver para RDP (causa comum de ecrã preto)</span>
<span style=”color:#6c7086;”># Via GPO: Computer Configuration → Administrative Templates → Windows Components → Remote Desktop Services → Remote Desktop Session Host → Remote Session Environment → Use WDDM graphics display driver for Remote Desktop Connections → Disabled</span>

<span style=”color:#6c7086;”># Via registry:</span>
Set-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services” -Name “fEnableWddmDriver” -Value 0

<span style=”color:#6c7086;”># Reiniciar serviço TermService</span>
Restart-Service TermService

6.5 Perfil temporário / corrompido

<span style=”color:#6c7086;”># Verificar se o utilizador tem perfil temporário</span>
<span style=”color:#6c7086;”># Event Viewer → Application → procurar Event ID 1511 (Windows cannot load the user’s profile)</span>

<span style=”color:#6c7086;”># Listar perfis no servidor</span>
Get-ItemProperty -Path “HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*” | Select ProfileImagePath, Sid

<span style=”color:#6c7086;”># Procurar perfil com .bak (perfil corrompido)</span>
Get-ChildItem -Path “HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList” | Where-Object { $_.Name -match ‘\.bak’ }

<span style=”color:#6c7086;”># Solução: remover perfil corrompido</span>
<span style=”color:#6c7086;”># 1. Fazer logoff do utilizador</span>
<span style=”color:#6c7086;”># 2. System Properties → Advanced → User Profiles → Settings → Delete</span>
<span style=”color:#6c7086;”># 3. Ou via registry: remover a chave com .bak</span>
<span style=”color:#6c7086;”># 4. Utilizador volta a fazer login — perfil novo é criado</span>

7. Passo 6 — Performance e Lentidão

7.1 Medir latência e bandwidth

<span style=”color:#6c7086;”># No servidor (Linux/Windows) — iniciar iperf3</span>
iperf3 -s

<span style=”color:#6c7086;”># No cliente — testar throughput</span>
iperf3 -c servidor01 -t 30

<span style=”color:#6c7086;”># Se throughput < 10 Mbps, o RDP vai ter lag em gráficos</span>
<span style=”color:#6c7086;”># Se latência > 50 ms, considerar RDP Shortpath (UDP)</span>

7.2 Optimizar definições RDP no cliente

No cliente mstsc.exe (Remote Desktop Connection):

Definição Valor recomendado para WAN Valor para LAN
Colors 16-bit (High Color 16-bit) 32-bit
Display resolution 1280×720 Native
Experience → Visual effects Desactivar tudo Activar tudo
Experience → Persistent bitmap caching Activar Activar
Experience → Reconnect if connection dropped Activar Activar
Display → Full screen Sim Sim

7.3 Optimizar via GPO (servidor)

<span style=”color:#6c7086;”># Activar RDP Shortpath (UDP) — Windows Server 2022+</span>
<span style=”color:#6c7086;”># GPO: Computer Configuration → Administrative Templates → Windows Components → Remote Desktop Services → Remote Desktop Session Host → Remote Session Environment → Turn on UDP → Enabled</span>

<span style=”color:#6c7086;”># Via registry:</span>
Set-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services” -Name “SelectTransport” -Value 1
<span style=”color:#6c7086;”># 1 = Use both TCP and UDP (recomendado)</span>
<span style=”color:#6c7086;”># 0 = Use only TCP</span>
<span style=”color:#6c7086;”># 2 = Use only UDP</span>

<span style=”color:#6c7086;”># Activar compressão de gráficos</span>
Set-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services” -Name “TransportCompression” -Value 1
<span style=”color:#6c7086;”># 1 = Enabled, 0 = Disabled</span>

<span style=”color:#6c7086;”># Limitar cor a 16-bit (reduz bandwidth)</span>
Set-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services” -Name “ColorDepth” -Value 1
<span style=”color:#6c7086;”># 1 = 8-bit, 2 = 15-bit, 3 = 16-bit, 4 = 24-bit, 5 = 32-bit</span>

7.4 Timeouts de sessão

<span style=”color:#6c7086;”># Verificar timeouts configurados</span>
Get-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services” -ErrorAction SilentlyContinue | Select-Object *Timeout*, *Limit*

<span style=”color:#6c7086;”># Configurar timeout de sessão inactiva (30 minutos)</span>
Set-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services” -Name “MaxIdleTime” -Value 1800000
<span style=”color:#6c7086;”># 1800000 ms = 30 minutos</span>

<span style=”color:#6c7086;”># Configurar acção ao terminar sessão (1 = disconnect, 2 = logoff)</span>
Set-ItemProperty -Path “HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services” -Name “MaxIdleTimeAction” -Value 2

8. Passo 7 — Event Viewer: Erros RDP

8.1 Eventos a procurar

Event ID Source Significado
4625 Security Logon falhado — verificar credenciais
48 TermDD Conexão RDP desligada pelo cliente
40 TermDD Conexão RDP perdida (rede)
56 TermDD Erro de protocolo RDP
104 TermService Sessão desligada por timeout ou administrador
1511 Userenv Não foi possível carregar o perfil do utilizador
1512 Userenv Perfil temporário criado (perfil corrompido)
1530 Userenv Perfil bloqueado por outro processo
1074 User32 Sessão terminada por shutdown ou logoff programado

8.2 Consultar eventos RDP

<span style=”color:#6c7086;”># Eventos do serviço TermService nas últimas 24h</span>
Get-WinEvent -FilterHashtable @{LogName=’System’; ProviderName=’TermService’,’TermDD’; StartTime=(Get-Date).AddDays(-1)} | Select TimeCreated, Id, Message | Format-Table -AutoSize

<span style=”color:#6c7086;”># Eventos de logon falhado</span>
Get-WinEvent -FilterHashtable @{LogName=’Security’; Id=4625; StartTime=(Get-Date).AddDays(-1)} | Select TimeCreated, Message | Format-List

<span style=”color:#6c7086;”># Eventos de perfil (ecrã preto)</span>
Get-WinEvent -FilterHashtable @{LogName=’Application’; ProviderName=’Microsoft-Windows-User Profile Service’; StartTime=(Get-Date).AddDays(-1)} | Select TimeCreated, Id, Message | Format-List

9. Erros Comuns e Resolução

  • “Remote Desktop can’t connect to the remote computer” — verificar porta 3389, firewall, serviço TermService. Usar Test-NetConnection primeiro.
  • “Your computer could not connect to another console session” — alguém já está ligado na consola. Usar /admin no mstsc ou desligar a sessão consola com logoff 1.
  • “The remote session was disconnected because of an error in the licensing protocol” — licença RDS corrompida no cliente. Remover HKLM\SOFTWARE\Microsoft\MSLicensing\Store e reconectar.
  • “CredSSP encryption oracle remediation” — cliente sem patch CVE-2018-0886. Instalar actualização Windows Update ou desactivar NLA temporariamente.
  • “Because of a protocol error, this session will be disconnected” — conflito de protocolo entre cliente e servidor. Actualizar cliente mstsc ou desactivar UDP.
  • Ecrã preto após login — WDDM driver, perfil corrompido, ou explorer.exe crash. Verificar secção 6.3.
  • RDP lento em WAN — latência alta ou bandwidth baixo. Activar RDP Shortpath (UDP), reduzir cor para 16-bit, desactivar animações.
  • “The number of connections is limited” — em administração remota, apenas 2 sessões são permitidas por defeito. Desligar sessões inactivas ou instalar RDS CALs.
  • Sessão RDP desconecta após alguns minutos — GPO de timeout ou firewall a cortar conexões idle. Verificar MaxIdleTime e configurar keepalive.
  • RDP conecta mas não mostra desktop — explorer.exe não arranca. Na sessão RDP, Ctrl+Shift+Esc → File → Run → explorer.exe.
  • Não consegue copiar/colar entre cliente e servidor — serviço Clipboard no servidor parado. Reiniciar rdpclip.exe no servidor (Task Manager → kill → File → Run → rdpclip.exe).

10. Checklist de Diagnóstico

  1. RedeTest-NetConnection -ComputerName <IP> -Port 3389
  2. FirewallGet-NetFirewallRule -DisplayGroup "Remote Desktop" no servidor
  3. ServiçoGet-Service TermService — tem de estar a correr
  4. RDP activadofDenyTSConnections = 0 no registry
  5. NLA — verificar compatibilidade cliente/servidor
  6. Permissões — utilizador no grupo “Remote Desktop Users”
  7. Licenciamento — RD Licensing Diagnoser (se RDS, não admin remota)
  8. Sessões presasqwinsta / quser e logoff <ID>
  9. Ecrã preto — desactivar WDDM, verificar perfil, reiniciar explorer.exe
  10. Performanceiperf3 para bandwidth, activar RDP Shortpath (UDP)
  11. Event Viewer — procurar Event IDs 4625, 48, 40, 1511, 104
  12. Timeouts — verificar MaxIdleTime em GPO e registry
  13. Cliente — verificar versão do mstsc e actualizações Windows Update
  14. Keepalive — configurar keepalive no cliente mstsc para evitar desconexões

11. Artigos Relacionados

Este artigo foi útil?

Duarte Spínola

Deixe um Comentário