Principais conclusões
- Eficiência automatizada: Automatiza a geração de URLs do ConnectWise ScreenConnect, aumentando a eficiência operacional.
- Flexibilidade de parâmetros: Oferece suporte a configurações dinâmicas por meio de parâmetros como domínio, grupo de sessões e ID de instância.
- Requisito administrativo: Requer privilégios administrativos para modificar campos personalizados e acesso ao registro.
- Verificação de instalação: Verifica a instalação do ScreenConnect usando o registro do sistema, garantindo a execução de scripts direcionados.
- Construção direta de URL: Gera URLs de inicialização direta para cada instância do ScreenConnect, minimizando a entrada manual.
- Potencial de integração: Integra-se facilmente a fluxos de trabalho maiores de automação de TI, oferecendo escalabilidade.
- Considerações sobre segurança: Enfatiza a necessidade do uso seguro de scripts para evitar o acesso não autorizado.
- NinjaOne Synergy: Demonstra a integração potencial e os ganhos de eficiência com o NinjaOne para o gerenciamento remoto do sistema.
No campo dinâmico da tecnologia da informação, a capacidade de gerenciar e dar suporte a sistemas remotos com eficiência é fundamental. Um participante importante nesse domínio é o ConnectWise ScreenConnect, uma solução robusta de suporte remoto, acesso e reunião. Automatizar sua implementação e integração por meio de scripts do PowerShell aumenta a eficiência e a confiabilidade, uma necessidade dos profissionais de TI e dos provedores de serviços gerenciados (MSPs).
Histórico
O script em foco foi projetado para automatizar a recuperação dos URLs de inicialização do ConnectWise ScreenConnect e salvá-los em um campo personalizado. Essa automação é crucial para ambientes de TI em que o acesso remoto rápido e contínuo a várias máquinas é uma exigência diária. A capacidade do script de identificar instâncias específicas do ScreenConnect e gerar URLs de conexão direta economiza um tempo inestimável e reduz os erros manuais, tornando-o uma ferramenta vital para o suporte e o gerenciamento de TI.
O roteiro:
<#
.SYNOPSIS
Get ConnectWise ScreenConnect Launch URL and save to custom field (defaults to screenconnectUrl). Requires the domain used for ScreenConnect and a Session Group the machine is a part of to successfully build URL.
.DESCRIPTION
Get ConnectWise ScreenConnect Launch URL and save to custom field (defaults to screenconnectUrl).
Requires the domain used for ScreenConnect and a Session Group the machine is a part of to successfully build URL.
.EXAMPLE
-ScreenConnectDomain "replace.me" -InstanceID "1111111111"
Building Launch URL(s)...
Launch URL(s) Created
Instance : 1111111111
LaunchURL : https://replace.me/Host#Access/All%20Machines//555555-555-555-5555-55555/Join
SessionId : 555555-555-555-5555-55555
PARAMETER: -ScreenConnectDomain "ExampleInput"
The domain used for your Connectwise ScreenConnect Instance.
PARAMETER: -SessionGroup "ExampleInput"
The Session Group in which the machine would normally be found. Defaults to "All Machines".
PARAMETER: -InstanceID "ExampleInput"
The Instance ID for your instance of ScreenConnect. Used to differentiate between multiple installed ScreenConnect Instances.
To get the instance id you can see it in the program's name in Control Panel e.g. ScreenConnect Client (yourinstanceidishere)
or in ScreenConnect itself (Admin > Advanced > Server Information > Instance Identifier Fingerprint).
PARAMETER: -CustomField "ReplaceWithAnyMultilineCustomField"
The custom field you would like to write the results to. Defaults to screenconnectUrl
.OUTPUTS
None
.NOTES
Minimum OS Architecture Supported: Windows 7+, Server 2008+
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()]
param (
[Parameter()]
[String]$ScreenConnectDomain,
[Parameter()]
[String]$SessionGroup = "All Machines",
[Parameter()]
[String]$InstanceID,
[Parameter()]
[String]$CustomField = "screenconnectUrl"
)
begin {
if ($env:screenconnectDomain -and $env:screenconnectDomain -notlike "null") { $ScreenConnectDomain = $env:screenconnectDomain }
if ($env:sessionGroup -and $env:sessionGroup -notlike "null") { $SessionGroup = $env:sessionGroup }
if ($env:instanceId -and $env:instanceId -notlike "null") { $InstanceID = $env:instanceId }
if ($env:customFieldName -and $env:customFieldName -notlike "null") { $CustomField = $env:customFieldName }
# Warn end-user if we're not provided an instance id
if (-not ($InstanceID)) {
Write-Warning "Without the instance id we will be unable to tell which ScreenConnect instance is yours if multiple are installed resulting in the wrong URL being displayed."
Write-Warning "To get the instance id you can see it in the programs name in Control Panel ex. ScreenConnect Client (yourinstanceidishere) or in Control itself (Admin > Advanced > Server Information > Instance Identifier Fingerprint)"
}
# These two are actually necessary to build the URL
if (-not ($ScreenConnectDomain) -or -not ($SessionGroup)) {
Write-Error "Unable to build URL without the domain or Session Group."
exit 1
}
# Test for elevation
function Test-IsElevated {
$id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$p = New-Object System.Security.Principal.WindowsPrincipal($id)
$p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}
# Checks the two Uninstall registry keys to see if the app is installed. Needs the name as it would appear in Control Panel.
function Find-UninstallKey {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $True)]
[String]$DisplayName,
[Parameter()]
[Switch]$UninstallString
)
process {
$UninstallList = New-Object System.Collections.Generic.List[Object]
$Result = Get-ChildItem HKLM:SoftwareWow6432NodeMicrosoftWindowsCurrentVersionUninstall* | Get-ItemProperty | Where-Object { $_.DisplayName -like "*$DisplayName*" }
if ($Result) { $UninstallList.Add($Result) }
$Result = Get-ChildItem HKLM:SoftwareMicrosoftWindowsCurrentVersionUninstall* | Get-ItemProperty | Where-Object { $_.DisplayName -like "*$DisplayName*" }
if ($Result) { $UninstallList.Add($Result) }
# Programs don't always have an uninstall string listed here so to account for that I made this optional.
if ($UninstallString) {
$UninstallList | Select-Object -ExpandProperty UninstallString -ErrorAction SilentlyContinue
}
else {
$UninstallList
}
}
}
# Define the name of the software we are searching for and look for it in both the 64 bit and 32 bit registry nodes.
if (-not $InstanceID) { $SoftwareName = "ScreenConnect Client" }else { $SoftwareName = "ScreenConnect Client ($InstanceID)" }
$ControlInstallation = Find-UninstallKey -DisplayName $SoftwareName
# If its not installed lets error out.
if (-not ($ControlInstallation)) {
Write-Error "Connectwise ScreenConnect is not installed!"
exit 1
}
# Elevation is required to write to custom fields.
if (-not (Test-IsElevated)) {
Write-Error -Message "Access Denied. Please run with Administrator privileges."
exit 1
}
}
process {
# The Image Path Registry Key contains the unique session id needed to generate the URL
Write-Host "Building Launch URL(s)..."
$ControlInstances = $ControlInstallation.DisplayName | ForEach-Object {
$ImagePath = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServices$_" | Select-Object -Property ImagePath -ExpandProperty ImagePath
$Id = ($ImagePath -split '&' | Where-Object { $_ -match 's=(.*-){4}' }) -replace "s="
$Instance = ($_ -replace "ScreenConnect Client (" -replace ")").trim()
New-Object psobject -Property @{
Instance = $Instance
LaunchURL = [URI]::EscapeUriString("https://$ScreenConnectDomain/Host#Access/$SessionGroup//$Id/Join")
SessionId = $Id
}
}
# Create a Table/List of our results
Write-Host "Launch URL(s) Created"
$ControlInstances | Format-List -Property Instance, LaunchURL, SessionId | Out-String | Write-Host
# PowerShell 2.0 does not support ninjarmm-cli
if ($PSVersionTable.PSVersion.Major -gt 2) {
if ($ControlInstances.LaunchURL.Count -gt 1) {
Ninja-Property-Set -Name $CustomField -Value ($ControlInstances | Format-List -Property Instance, LaunchURL | Out-String)
}
else {
Ninja-Property-Set -Name $CustomField -Value ($ControlInstances.LaunchURL | Out-String)
}
}
else {
Write-Host "ninjarmm-cli does not support PowerShell 1 & 2. Refer to https://ninjarmm.zendesk.com/hc/en-us/articles/4405408656013 ."
}
}
end {
}
Acesse mais de 300 scripts no NinjaOne Dojo
Detalhamento
- Inicialização de parâmetros: O script começa definindo parâmetros como ScreenConnectDomain, SessionGroup, InstanceID e CustomField. Esses parâmetros são essenciais para identificar a instância específica do ScreenConnect e o grupo de máquinas dentro dela.
- Verificações de variáveis de ambiente: Ele verifica e usa variáveis de ambiente se elas estiverem definidas. Essa flexibilidade permite a adaptação dinâmica a diferentes configurações do sistema.
- Verificações pré-execução: O script garante que os parâmetros necessários sejam fornecidos e verifica se há privilégios administrativos, pois a modificação de campos personalizados exige permissões elevadas.
- Verificação da instalação do software: Ele pesquisa o registro do sistema para verificar se o ScreenConnect está instalado, identificando a instância correta usando o InstanceID fornecido.
- Geração de URL: A funcionalidade principal em que ele constrói o URL de inicialização do ScreenConnect usando o domínio, o grupo de sessões e um ID de sessão exclusivo extraído do registro do sistema.
- Formatação de saída: Os URLs gerados são formatados em uma lista legível, fornecendo informações claras e acionáveis para o usuário.
Casos de uso em potencial
Imagine um profissional de TI gerenciando uma frota de máquinas em vários locais. Eles precisam se conectar rapidamente a qualquer máquina para solucionar problemas. Usando esse script, eles podem gerar URLs diretos do ScreenConnect para cada máquina e armazená-los em um campo personalizado, permitindo o acesso remoto instantâneo sem a construção manual de URLs.
Comparações
Tradicionalmente, a geração de URLs do ScreenConnect envolve a identificação manual do ID de sessão de cada máquina e a construção do URL. Esse script automatiza esse processo, reduzindo significativamente o tempo e a possibilidade de erro. Em comparação com os métodos baseados em GUI, o script oferece recursos de escalabilidade e integração com outros fluxos de trabalho de automação.
Implicações
A automação da geração de URLs aumenta a eficiência operacional, mas também representa um risco se for mal utilizada. Se ocorrer um acesso não autorizado ao script, isso pode levar a possíveis violações de segurança. Portanto, é fundamental proteger o script e o ambiente em que ele é usado.
Recomendações
- Proteger o meio ambiente: Execute o script em um ambiente seguro e controlado.
- Atualizações regulares: Mantenha o ambiente do ConnectWise ScreenConnect e do PowerShell atualizado.
- Controle de acesso: Restringir o acesso ao script somente ao pessoal autorizado.
Considerações finais
A incorporação desses scripts na plataforma NinjaOne pode simplificar as tarefas de gerenciamento remoto, oferecendo uma experiência de gerenciamento mais coesa e eficiente. A capacidade do NinjaOne de se integrar a ferramentas como o ConnectWise ScreenConnect, ampliada com o poder da automação, é uma prova de sua utilidade no cenário de TI em constante evolução.