Uso do PowerShell para obter a localização do dispositivo usando a API de geolocalização do Google

Principais conclusões

  • O script obtém a localização geográfica de um dispositivo usando a API GeoLocation do Google.
  • Ele foi projetado para atualizar os campos personalizados do NinjaOne com dados de localização.
  • O script requer uma conexão ativa com a Internet e é otimizado para dispositivos Windows 10.
  • A API de geolocalização do Google oferece precisão e cobertura mais ampla em comparação com outros métodos.
  • O uso do script para rastreamento de localização traz preocupações éticas e de privacidade.
  • Permissões explícitas são essenciais antes de implantar essa ferramenta para evitar violações de privacidade.
  • É fundamental entender os limites de taxa e os custos associados à API do Google.
  • O NinjaOne, combinado com esses scripts, oferece recursos robustos para operações de TI e gerenciamento de ativos.

No ecossistema de TI interconectado de hoje, uma das informações mais valiosas é a “localização”. A capacidade de rastrear a localização geográfica dos dispositivos pode ser crucial em muitas operações de TI, desde o gerenciamento de ativos até o monitoramento da segurança. Esta postagem do blog discute um script do PowerShell que permite que profissionais de TI e MSPs (Provedores de Serviços Gerenciados) obtenham a localização de um dispositivo Windows e a armazenem usando os campos personalizados do NinjaOne.

Histórico

O script em foco atualiza os campos personalizados com as coordenadas geográficas e o endereço de um dispositivo usando a API de geolocalização do Google. Para os profissionais de TI e MSPs, saber a localização física de um dispositivo é fundamental. Seja para rastrear equipamentos roubados, auditar dispositivos ou verificar a distribuição geográfica dos ativos de TI, a aplicação desse script pode ser diversa e profunda.

O roteiro

#Requires -Version 5.1

<#
.SYNOPSIS
    Updates Custom Fields with the location of a device based on the Google GeoLocation API.
.DESCRIPTION
    Updates Custom Fields with the location of a device based on the Google GeoLocation API.

    The CustomFieldName parameter can be used to specify which custom field to save the Latitude and Longitude coordinates to.
    The AddressCustomFieldName parameter can be used to specify which custom field to save the address to.

    This script requires a custom field to save location data in NinjaRMM.
    The default for CustomFieldName is "Location".
    The default for AddressCustomFieldName is "Address".
    You can use any text custom field that you wish.
.EXAMPLE
    -GoogleApiKey "<GeoLocation API key here>"
    Saves the Latitude and Longitude coordinates to the custom field named Location.
.EXAMPLE
    -GoogleApiKey "<GeoLocation API key here>" -CustomFieldName "Location" -AddressCustomFieldName "Address"
    Saves the Latitude and Longitude coordinates to the custom field named Location as well as the address to Address.
.INPUTS
    None
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10
    Release Notes:
    Updated to work with either Parameters or Script Variables
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]
    $GoogleApiKey,
    [Parameter()]
    [String]
    $CustomFieldName = "Location",
    [Parameter()]
    [String]
    $AddressCustomFieldName = "Address"
)

begin {
    function Test-StringEmpty {
        param([string]$Text)
        # Returns true if string is empty, null, or whitespace
        process { [string]::IsNullOrEmpty($Text) -or [string]::IsNullOrWhiteSpace($Text) }
    }
    function Get-NearestCity {
        param (
            [double]$lat,
            [double]$lon,
            [string]$GoogleApi
        )
        try {
            $Response = Invoke-RestMethod -Uri "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lon&key=$GoogleApi"
        }
        catch {
            throw $Error[0]
        }
        return $Response.results[0].formatted_address
    }
    function Get-WifiNetwork {
        end {
            try {
                netsh.exe wlan sh net mode=bssid | ForEach-Object -Process {
                    if ($_ -match '^SSID (d+) : (.*)$') {
                        $current = @{}
                        $networks += $current
                        $current.Index = $matches[1].trim()
                        $current.SSID = $matches[2].trim()
                    }
                    else {
                        if ($_ -match '^s+(.*)s+:s+(.*)s*$') {
                            $current[$matches[1].trim()] = $matches[2].trim()
                        }
                    }
                } -Begin { $networks = @() } -End { $networks | ForEach-Object { New-Object -TypeName "PSObject" -Property $_ } }    
            }
            catch {
                # return nothing
            }
        }
    }

    # Check if Script Variables are being used
    if (-not $(Test-StringEmpty -Text $env:GoogleApiKey)) {
        $GoogleApiKey = $env:GoogleApiKey
    }
    if (-not $(Test-StringEmpty -Text $env:CustomFieldName)) {
        $CustomFieldName = $env:CustomFieldName
    }
    if (-not $(Test-StringEmpty -Text $env:AddressCustomFieldName)) {
        $AddressCustomFieldName = $env:AddressCustomFieldName
    }
    # Check if api key is set, error if not set
    if ($(Test-StringEmpty -Text $GoogleApiKey)) {
        # Both Parameter and Script Variable are empty
        # Can not combine Parameter "[Parameter(Mandatory)]" and Script Variable Required
        Write-Error "GoogleApiKey is required."
        exit 1
    }

    # Use the system's new line
    $NewLine = $([System.Environment]::NewLine)

    # Build URL with API key
    $Url = "https://www.googleapis.com/geolocation/v1/geolocate?key=$GoogleApiKey"
}
process {
    # Get WIFI network data nearby
    $WiFiData = Get-WifiNetwork |
        Select-Object @{name = 'age'; expression = { 0 } },
        @{name = 'macAddress'; expression = { $_.'BSSID 1' } },
        @{name = 'channel'; expression = { $_.Channel } },
        @{name = 'signalStrength'; expression = { (($_.Signal -replace "%") / 2) - 100 } }

    # Check if we got any number access points
    $Body = if ($WiFiData -and $WiFiData.Count -gt 0) {
        @{
            considerIp       = $true
            wifiAccessPoints = $WiFiData
        } | ConvertTo-Json
    }
    else {
        @{
            considerIp = $true
        } | ConvertTo-Json
    }

    # Get our lat,lng position
    try {
        $Response = Invoke-RestMethod -Method Post -Uri $Url -Body $Body -ContentType "application/json" -ErrorVariable Err
    }
    catch {
        Write-Error $_
        exit 1
    }

    # Save the relevant results to variable that have shorter names
    $Lat = $Response.location.lat
    $Lon = $Response.location.lng

    try {
        # Save Latitude, Longitude to the custom field from the CustomFieldName parameter
        Ninja-Property-Set -Name $CustomFieldName -Value "$Lat,$Lon"
    }
    catch {
        Write-Error "Failed to save to CustomFieldName($CustomFieldName)"
        exit 1
    }

    if ( $(Test-StringEmpty -Text $AddressCustomFieldName) -and $(Test-StringEmpty -Text $env:AddressCustomFieldName)) {
        # Both Parameter and Variable are empty
        Write-Output "$($NewLine)Location: $Lat,$Lon"
    }
    else {
        if ($(Test-StringEmpty -Text $AddressCustomFieldName)) {
            # Parameter was not used
            $AddressCustomFieldName = $env:AddressCustomFieldName
        }

        try {
            # Get City from Google API's
            # Google API: https://developers.google.com/maps/documentation/geocoding/requests-reverse-geocoding
            $Address = Get-NearestCity -lat $Lat -lon $Lon -GoogleApi $GoogleApiKey
        }
        catch {
            Write-Error "Failed to save to get nearest city."
            exit 1
        }

        try {
            # Save Lat and Lon to custom field
            Ninja-Property-Set -Name $AddressCustomFieldName -Value "$Address"
            Write-Output "$($NewLine)Location: $Address`: $Lat,$Lon"
        }
        catch {
            Write-Error "Failed to save to AddressCustomFieldName($AddressCustomFieldName)"
            exit 1
        }
    }
    exit 0
}
end {
    $ScriptVariables = @(
        [PSCustomObject]@{
            name           = "GoogleApiKey"
            calculatedName = "GoogleApiKey"
            required       = $true
            defaultValue   = $null
            valueType      = "TEXT"
            valueList      = $null
            description    = ""
        }
        [PSCustomObject]@{
            name           = "CustomFieldName"
            calculatedName = "CustomFieldName"
            required       = $false
            defaultValue   = [PSCustomObject]@{
                type  = "TEXT"
                value = "Location"
            }
            valueType      = "TEXT"
            valueList      = $null
            description    = ""
        }
    )
}

 

Acesse mais de 300 scripts no NinjaOne Dojo

Obter acesso

Detalhamento

O script pode ser dividido em três partes principais:

  • Inicialização: O script começa com a definição de parâmetros como GoogleApiKey, CustomFieldName e AddressCustomFieldName. Esses parâmetros funcionam como entradas para personalizar o comportamento do script.
  • Operações principais: A parte principal do script envolve:
  • Verificação das redes WiFi disponíveis ao redor do dispositivo.
  • Construir uma carga útil com dados de WiFi e enviá-la ao serviço de geolocalização do Google para obter a latitude e a longitude.
  • Busca da cidade ou do endereço mais próximo usando as coordenadas obtidas.
  • Atualização dos campos personalizados no NinjaOne com os dados de localização.
  • Operações de conclusão: ScriptVariables são inicializadas para armazenar dados e ajudar em outras operações.

Casos de uso em potencial

Considere um profissional de TI, Alex, que trabalha em uma empresa. Eles foram designados para auditar todos os laptops em várias filiais do escritório. Usando esse script, Alex pode obter rapidamente a localização geográfica de cada laptop, garantindo que eles estejam de fato nos locais de escritório declarados.

Comparações

A abordagem do script aproveita a API de geolocalização do Google, que oferece detalhes precisos de localização. As alternativas podem envolver o uso de serviços de localização nativos do Windows ou outras APIs de terceiros. No entanto, os vastos dados e a infraestrutura robusta do Google fazem dele a escolha preferida para esses aplicativos, oferecendo melhor precisão e cobertura mais ampla.

Implicações

Embora a capacidade de rastrear a localização de um dispositivo seja uma ótima ferramenta para o gerenciamento e a segurança de ativos, ela também apresenta preocupações com a privacidade. É fundamental que as equipes de TI garantam que essa ferramenta seja usada de forma ética, com as devidas permissões e divulgações. O rastreamento não autorizado pode levar a violações de leis e regulamentos de privacidade.

Recomendações

  • Sempre obtenha permissão explícita antes de executar esse script em qualquer dispositivo.
  • Certifique-se de que você entenda os limites de taxa e os custos associados à API de geolocalização do Google.
  • Analise e audite regularmente os registros para evitar qualquer uso indevido.

Considerações finais

Para MSPs e profissionais de TI, o NinjaOne oferece uma plataforma inestimável para centralizar e otimizar as operações de TI. A integração de tais scripts para obter a localização dos dispositivos amplia ainda mais os recursos do NinjaOne, tornando-o uma ferramenta indispensável para os cenários modernos de TI. Os scripts do PowerShell, especialmente como o que foi dissecado acima, oferecem uma camada adicional de flexibilidade e poder aos usuários do NinjaOne, ajudando-os a manter o ritmo em um mundo de TI dinâmico.

FAQs

O script requer uma conexão ativa com a Internet para se comunicar com os serviços do Google.

A API de geolocalização do Google tem limites com base no tipo de sua conta e no status de faturamento.

O requisito mínimo de sistema operacional do script é o Windows 10.

Próximas etapas

Montar uma equipe de TI eficaz requer uma solução centralizada que seja a principal ferramenta de entrega de serviços. Com NinjaOne, a TI monitora, gerencia, protege e oferece suporte a todos os dispositivos, onde quer que estejam, dispensando infraestrutura complexa no local.

Saiba mais sobre a solução NinjaOne Remote Script Deployment, agende uma demonstração, ou inicie sua avaliação gratuita da plataforma NinjaOne.

Categories:

You might also like

Uso do PowerShell para obter a localização do dispositivo usando a API de geolocalização do Google

Como configurar o Windows Defender SmartScreen usando o PowerShell

Exigir senha após a suspensão em máquinas Windows: Script do PowerShell

Ativar ou desativar o protocolo de área de trabalho remota (RDP) em estações de trabalho usando o PowerShell

Como atualizar as políticas de senha do Windows usando o PowerShell

Gerenciando & Configurando o NETBIOS no Windows usando o PowerShell

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our 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 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).