In a complex Active Directory (AD) environment with multiple server types such as domain controllers and file servers, managing and verifying access permissions is crucial. Automating the process of testing Remote Desktop Protocol (RDP) connectivity using different AD accounts, like Tier 1 and Tier 2, can significantly enhance efficiency and accuracy. This guide provides a comprehensive approach to automating RDP connection testing using PowerShell and PsExec, ensuring both effectiveness and adherence to security best practices.
servers.txt
) containing the IP addresses or hostnames of the target servers, one per line.Create a text file named servers.txt
that includes all the server IP addresses or hostnames you wish to test. Ensure each entry is on a separate line. For example:
192.168.1.10
192.168.1.20
file-server01
domain-controller02
PsExec is a powerful tool from Microsoft Sysinternals that allows you to execute processes on remote systems. Follow these steps to install PsExec:
PsExec.exe
in a directory that's included in your system’s PATH environment variable, or note its full path for use in scripts.It's critical to handle credentials securely to prevent unauthorized access. Avoid hardcoding credentials in scripts. Instead, use PowerShell's Get-Credential
cmdlet or store credentials in a secure encrypted file or a credential vault.
Example using Get-Credential
:
$credential = Get-Credential -Message "Enter your Tier 1 account credentials"
Create a PowerShell script (e.g., Test-RDPConnection.ps1
) that automates the process of testing RDP connections using PsExec. Below is a comprehensive script with detailed explanations:
# Define the path to PsExec
$psexecPath = "C:\Path\To\PsExec.exe"
# Import the list of servers
$servers = Get-Content -Path "C:\Path\To\servers.txt"
# Prompt for Tier 1 credentials securely
$credential = Get-Credential -Message "Enter your Tier 1 account credentials"
# Define the log file path
$logFile = "C:\Path\To\RDP_Test_Results.csv"
# Initialize the log file with headers
"Server,ConnectionStatus,Timestamp" | Out-File -FilePath $logFile -Encoding UTF8
# Function to test RDP connection using PsExec
function Test-RDPConnection {
param (
[string]$ComputerName,
[System.Management.Automation.PSCredential]$Credential
)
$username = $Credential.UserName
$password = $Credential.GetNetworkCredential().Password
try {
# Construct the PsExec command
$command = "& `"$psexecPath`" \\$ComputerName -u $username -p $password cmd /c echo RDP connection successful"
# Execute the command
$result = Invoke-Expression $command
# Determine the connection status based on the output
if ($result -like "*RDP connection successful*") {
$status = "Success"
} else {
$status = "Failed"
}
}
catch {
$status = "Error: $_"
}
# Log the result with a timestamp
"$ComputerName,$status,$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Out-File -FilePath $logFile -Append -Encoding UTF8
# Output to console
Write-Host "$ComputerName - $status" -ForegroundColor ($status -eq "Success" ? "Green" : "Red")
}
# Iterate through each server and test RDP connection
foreach ($server in $servers) {
Test-RDPConnection -ComputerName $server -Credential $credential
}
Write-Host "RDP connection tests completed. Results are saved in $logFile" -ForegroundColor Cyan
PsExec.exe
file.servers.txt
.Get-Credential
.Test-RDPConnection
that uses PsExec to attempt an RDP connection and logs the outcome.Follow these steps to execute the script:
Test-RDPConnection.ps1
.
.\Test-RDPConnection.ps1
When prompted, enter the Tier 1 account credentials. The script will then attempt to connect to each server and log the results.
The script generates a CSV file (RDP_Test_Results.csv
) containing the following columns:
You can open this CSV file using Microsoft Excel or any other spreadsheet application to analyze the results.
To speed up the testing process, especially in environments with a large number of servers, you can leverage PowerShell's parallel processing capabilities using ForEach-Object -Parallel
or the Start-Job
cmdlet.
Example using parallel processing:
$servers = Get-Content -Path "C:\Path\To\servers.txt"
$credential = Get-Credential -Message "Enter your Tier 1 account credentials"
$logFile = "C:\Path\To\RDP_Test_Results.csv"
"Server,ConnectionStatus,Timestamp" | Out-File -FilePath $logFile -Encoding UTF8
$servers | ForEach-Object -Parallel {
param ($server, $psexecPath, $credential, $logFile)
$username = $credential.UserName
$password = $credential.GetNetworkCredential().Password
try {
$command = "& `"$psexecPath`" \\$server -u $username -p $password cmd /c echo RDP connection successful"
$result = Invoke-Expression $command
if ($result -like "*RDP connection successful*") {
$status = "Success"
} else {
$status = "Failed"
}
}
catch {
$status = "Error: $_"
}
"$server,$status,$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" | Out-File -FilePath $logFile -Append -Encoding UTF8
Write-Host "$server - $status" -ForegroundColor ($status -eq "Success" ? "Green" : "Red")
} -ArgumentList $_, $psexecPath, $credential, $logFile
To regularly perform RDP connection tests without manual intervention, you can schedule the PowerShell script using Windows Task Scheduler.
powershell.exe
-File "C:\Path\To\Test-RDPConnection.ps1"
For enhanced visibility and alerting, integrate the RDP connection test results with your organization's monitoring and alerting systems. This can be achieved by:
Modify the script to send an email if any RDP connection fails:
# Define SMTP server details
$smtpServer = "smtp.yourdomain.com"
$from = "admin@yourdomain.com"
$to = "security@yourdomain.com"
$subject = "RDP Connection Test Alert"
# After testing all servers
$failedConnections = Import-Csv -Path $logFile | Where-Object { $_.ConnectionStatus -ne "Success" }
if ($failedConnections) {
$body = "The following servers failed the RDP connection test:`n"
foreach ($entry in $failedConnections) {
$body += "$($entry.Server) - Status: $($entry.ConnectionStatus) - Time: $($entry.Timestamp)`n"
}
Send-MailMessage -SmtpServer $smtpServer -From $from -To $to -Subject $subject -Body $body
Write-Host "Alert email sent for failed connections." -ForegroundColor Yellow
}
When automating RDP connection tests, it's essential to adhere to security best practices to protect sensitive information and maintain compliance:
Encountering issues during automation is common. Here are some troubleshooting steps to resolve common problems:
Set-ExecutionPolicy
cmdlet.Set-ExecutionPolicy RemoteSigned
Test-NetConnection
to verify connectivity on port 3389 for RDP.Automating RDP connection testing using PowerShell and PsExec offers a robust solution for verifying access permissions across multiple servers in an AD environment. By following the steps outlined in this guide, you can enhance operational efficiency, maintain security compliance, and ensure that your Tier 1 accounts function as intended. Remember to continuously monitor and refine your scripts to adapt to evolving security landscapes and organizational needs.