A sincronização de tempo é um elemento fundamental na complexa máquina que é a TI. Garantir que os dispositivos em uma rede tenham tempos congruentes é vital para várias funcionalidades e protocolos de segurança. Este artigo se aprofunda em um script do PowerShell desenvolvido para comparar a hora do sistema local com um servidor NTP, sinalizando se a diferença ultrapassa um limite estipulado.
Histórico
À medida que as infraestruturas modernas de TI evoluem, a importância da precisão do tempo aumenta. As disparidades, mesmo que sejam mínimas, como alguns segundos, podem causar estragos, provocando anomalias nos aplicativos ou colocando em risco a segurança. Os profissionais de TI e os provedores de serviços gerenciados (MSPs) devem garantir sincronizações precisas de horário entre os dispositivos. Nosso script serve como uma ferramenta para sinalizar possíveis discrepâncias.
O roteiro
#Requires -Version 5.1
<#
.SYNOPSIS
Compares the local system time to an NTP server, returning an exit code of 0 if less than a 2 minute difference or 1 if more than 2 minute difference.
.DESCRIPTION
Compares the local system time to an NTP server, returning an exit code of 0 if less than a 2 minute difference or 1 if more than 2 minute difference.
.EXAMPLE
No parameters needed
The maximum acceptable time difference of 2 minute.
.EXAMPLE
-Max 5
The maximum acceptable time difference of 5 minute.
.EXAMPLE
-NtpServer "pool.ntp.org"
The maximum acceptable time difference of 2 minute, but uses the ntp.org's pool and use the time server pool "pool.ntp.org".
Alterative pools:
time.google.com
time.cloudflare.com
time.facebook.com
time.apple.com
time.nist.gov
.OUTPUTS
None
.NOTES
Minimum OS Architecture Supported: Windows 10, Windows Server 2016
Exit code 1: If the time is off more than Max
Exit code 0: If the time is off less than or equal to Max
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()]
[int]
$Max = 2,
[Parameter()]
[string]
$NtpServer = "time.windows.com"
)
begin {}
process {
Write-Host "Using NTP server($NtpServer) to get time."
$TimeSample = w32tm.exe /StripChart /Computer:"$NtpServer" /DataOnly /Samples:1
$Diff = $($($TimeSample | Select-Object -Last 1) -split ', ' | Select-Object -Last 1) -replace '+' -replace '-'
$TimeScale = $Diff -split '' | Select-Object -Last 1 -Skip 1
# Convert to minutes
$Diff = switch ($TimeScale) {
"s" { [double]$($Diff -replace 's') / 60 }
"m" { [double]$($Diff -replace 'm') }
"h" { [double]$($Diff -replace 'h') * 60 * 60 }
"d" { [double]$($Diff -replace 'd') * 60 * 60 * 24 }
Default {}
}
Write-Host "Time Difference between NTP server and local system: $($([Math]::Round($Diff,2))) minutes"
if ($Max -lt 0) {
# If Max is negative then flip the sign to positive
$Max = 0 - $Max
}
# Only output this if -Verbose is used
Write-Verbose "$($Diff) minutes > $Max minutes = $($Diff -gt $Max)"
# Assuming that $Max and $Diff are positive
if (
$Diff -gt $Max
) {
# If time difference > $Max then return exit code of 1
Write-Host "Time is over the maximum minutes of $Max."
exit 1
}
else {
# If time difference < $Max then return exit code of 0
Write-Host "Time is under the maximum minutes of $Max."
exit 0
}
}
end {}
Acesse mais de 300 scripts no NinjaOne Dojo
Detalhamento
- Cmdlet Binding & Parâmetros: O script usa o atributo CmdletBinding, o que permite que ele seja usado como um cmdlet e aproveite os recursos internos do PowerShell. Dois parâmetros são declarados: $Max, a diferença de tempo máxima aceitável (padrão: 2 minutos), e $NtpServer, o servidor a ser verificado (padrão: time.windows.com).
- Bloco de processo: A lógica principal é executada aqui.
- Ele obtém a diferença de horário usando o w32tm.exe, uma ferramenta de linha de comando do Windows.
- Analisa o tempo obtido, discernindo a diferença e sua escala (segundos, minutos, etc.).
- Converte a diferença de horário em minutos.
- Compara a diferença calculada com $Max, retornando o código de saída apropriado.
Casos de uso em potencial
Imagine um profissional de TI supervisionando uma vasta rede de dispositivos em uma empresa. Eles observaram anomalias em aplicativos que registram ações com registro de data e hora. Para diagnosticar, eles implementam esse script para identificar dispositivos com desvios de tempo substanciais. Com os resultados, eles podem fazer os ajustes necessários.
Comparações
Embora existam ferramentas baseadas em GUI e aplicativos de terceiros que oferecem recursos de sincronização de horário, esse script se destaca por sua simplicidade e adaptabilidade. Ele pode ser integrado aos fluxos de trabalho de TI ou às ferramentas de automação existentes, o que o torna uma opção versátil.
Implicações
As discrepâncias de tempo podem parecer inócuas, mas podem ter implicações profundas. Carimbos de data e hora diferentes podem prejudicar a integridade dos dados, afetar tarefas programadas e expor vulnerabilidades. Os invasores podem explorar lacunas de tempo, portanto, verificações regulares com ferramentas como esse script são cruciais para a segurança de TI.
Recomendações
- Execute o script em intervalos regulares para garantir o monitoramento contínuo.
- Sempre verifique a validade do servidor NTP que está sendo usado.
- Em caso de discrepâncias, investigue a causa principal, pois ela pode ser sintomática de problemas subjacentes maiores.
Considerações finais
Embora scripts como esses sejam de valor inestimável, uma plataforma abrangente como o NinjaOne pode elevar seu gerenciamento de TI. Integrando verificações, monitoramento e correção automatizados, o NinjaOne pode complementar ferramentas como nosso script do PowerShell, garantindo que sua infraestrutura permaneça funcional e segura.