{"id":808350,"date":"2026-05-14T07:31:47","date_gmt":"2026-05-14T07:31:47","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=808350"},"modified":"2026-05-14T07:31:47","modified_gmt":"2026-05-14T07:31:47","slug":"how-to-check-for-modified-hosts-file-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/pt-br\/script-hub\/how-to-check-for-modified-hosts-file-powershell\/","title":{"rendered":"Como verificar se h\u00e1 um arquivo de hosts modificado com o PowerShell"},"content":{"rendered":"<p>No vasto dom\u00ednio da TI, o arquivo hosts funciona como uma sentinela silenciosa, garantindo comunica\u00e7\u00f5es de rede sem problemas. Para quem n\u00e3o conhece, o <a href=\"https:\/\/www.ninjaone.com\/blog\/what-is-a-hosts-file\/\">arquivo hosts<\/a> \u00e9 um arquivo de texto que mapeia nomes de host para endere\u00e7os IP. \u00c9 usado pelo sistema operacional para resolver nomes de host para endere\u00e7os IP quando um computador tenta se conectar a um recurso de rede. Mas o que acontece quando o <strong><a href=\"https:\/\/www.ninjaone.com\/blog\/how-to-edit-hosts-file\/\">arquivo hosts \u00e9<\/a> modificado ou adulterado<\/strong>? Como os profissionais de TI e os provedores de servi\u00e7os gerenciados (MSPs) podem garantir a integridade desse arquivo crucial? Entre no script que estamos prestes a analisar.<\/p>\n<h2>Entendendo o arquivo Hosts<\/h2>\n<p>O arquivo hosts, em sua ess\u00eancia, \u00e9 o cat\u00e1logo de endere\u00e7os do sistema do computador. Ele desempenha um papel fundamental no direcionamento do tr\u00e1fego de rede, garantindo que os usu\u00e1rios acessem os sites e servi\u00e7os corretos. No entanto, sua import\u00e2ncia tamb\u00e9m o torna um alvo principal para agentes mal-intencionados.<\/p>\n<h2>Os poss\u00edveis riscos de modifica\u00e7\u00f5es n\u00e3o autorizadas<\/h2>\n<p>Um invasor, com inten\u00e7\u00f5es nefastas, pode modificar o arquivo hosts para redirecionar o tr\u00e1fego para um site ou servidor malicioso. Essas altera\u00e7\u00f5es podem ter consequ\u00eancias terr\u00edveis:<\/p>\n<ul>\n<li><strong>Roubo de informa\u00e7\u00f5es pessoais<\/strong>: Ao redirecionar os usu\u00e1rios para sites falsos, os invasores podem fazer phishing para obter detalhes pessoais, levando ao roubo de identidade.<\/li>\n<li><strong>Instala\u00e7\u00e3o de malware<\/strong>: Os usu\u00e1rios podem ser induzidos a fazer download de software malicioso, pensando que est\u00e3o em um site leg\u00edtimo.<\/li>\n<li><strong>Interrup\u00e7\u00e3o das comunica\u00e7\u00f5es de rede<\/strong>: Servi\u00e7os essenciais podem ser bloqueados, causando interrup\u00e7\u00f5es operacionais.<\/li>\n<\/ul>\n<p>Devido a esses riscos, \u00e9 fundamental que os profissionais de TI e os MSPs tenham ferramentas que possam detectar rapidamente qualquer altera\u00e7\u00e3o n\u00e3o autorizada. \u00c9 aqui que nosso script entra em a\u00e7\u00e3o.<\/p>\n<h2>O roteiro<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Checks if the hosts file was modified from last run.\r\n.DESCRIPTION\r\n    Checks if the hosts file was modified from last run.\r\n    On first run this will not produce an error, but will create a cache file for later comparison.\r\n.EXAMPLE\r\n    No parameters needed.\r\n.OUTPUTS\r\n    None\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2016\r\n    Release Notes:\r\n    Initial Release\r\nBy 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.\r\n    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. \r\n    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. \r\n    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. \r\n    Warranty Disclaimer: The script is provided \u201cas is\u201d and \u201cas available\u201d, 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. \r\n    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. \r\n    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. \r\n    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).\r\n#&gt;\r\n\r\n[CmdletBinding()]\r\nparam (\r\n    # Path and file of the hosts file\r\n    [string]\r\n    $HostsPath = \"C:WindowsSystem32driversetchosts\",\r\n    # Path and file where the cache file will be saved for comparison\r\n    [string]\r\n    $CachePath = \"C:ProgramDataNinjaRMMAgentscriptingTest-HostsFile.clixml\"\r\n)\r\n\r\nbegin {\r\n    function Test-IsElevated {\r\n        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()\r\n        $p = New-Object System.Security.Principal.WindowsPrincipal($id)\r\n        $p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)\r\n    }\r\n}\r\nprocess {\r\n    if (-not (Test-IsElevated)) {\r\n        Write-Error -Message \"Access Denied. Please run with Administrator privileges.\"\r\n        exit 1\r\n    }\r\n\r\n    # Check if hosts file exists\r\n    if ($(Test-Path -Path $HostsPath)) {\r\n        # Get content and create hash of hosts file\r\n        $HostsContent = Get-Content -Path $HostsPath\r\n        $HostsHash = Get-FileHash -Path $HostsPath -Algorithm SHA256\r\n\r\n        $Current = [PSCustomObject]@{\r\n            Content = $HostsContent\r\n            Hash    = $HostsHash\r\n        }\r\n\r\n        # Check if this is first run or not\r\n        if ($(Test-Path -Path $CachePath)) {\r\n            # Compare last content and hash\r\n            $Cache = Import-Clixml -Path $CachePath\r\n            $ContentDifference = Compare-Object -ReferenceObject $Cache.Content -DifferenceObject $Current.Content -CaseSensitive\r\n            $HashDifference = $Cache.Hash -like $Current.Hash\r\n            $Current | Export-Clixml -Path $CachePath -Force -Confirm:$false\r\n            if (-not $HashDifference) {\r\n                Write-Host \"Hosts file has changed since last run!\"\r\n                Write-Host \"\"\r\n                $ContentDifference | ForEach-Object {\r\n                    if ($_.SideIndicator -like '=&gt;') {\r\n                        Write-Host \"Added: $($_.InputObject)\"\r\n                    }\r\n                    elseif ($_.SideIndicator -like '&lt;=') {\r\n                        Write-Host \"Removed: $($_.InputObject)\"\r\n                    }\r\n                }\r\n                exit 1\r\n            }\r\n        }\r\n        else {\r\n            Write-Host \"First run, saving comparison cache file.\"\r\n            $Current | Export-Clixml -Path $CachePath -Force -Confirm:$false\r\n        }\r\n    }\r\n    else {\r\n        Write-Error \"Hosts file is missing!\"\r\n        exit 1\r\n    }\r\n    exit 0\r\n}\r\nend {}<\/pre>\n<p>&nbsp;<\/p>\n\n<div class=\"in-context-cta\"><p>Acesse mais de 300 scripts no NinjaOne Dojo<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/freetrialform\/\">Obter acesso<\/a><\/p>\n<\/div>\n<h2>Um mergulho profundo no roteiro<\/h2>\n<p>O script do PowerShell fornecido foi projetado para verificar se o arquivo hosts foi modificado desde sua \u00faltima execu\u00e7\u00e3o. Veja a seguir um detalhamento de sua funcionalidade:<\/p>\n<ol>\n<li><strong>Verifica\u00e7\u00e3o da eleva\u00e7\u00e3o<\/strong>: O script primeiro verifica se est\u00e1 sendo executado com privil\u00e9gios de administrador. Isso \u00e9 fundamental porque qualquer tentativa de ler ou modificar arquivos do sistema requer permiss\u00f5es elevadas.<\/li>\n<li><strong>Verifica\u00e7\u00e3o de arquivos de hosts<\/strong>: Em seguida, ele verifica a exist\u00eancia do arquivo hosts. Se o arquivo estiver faltando, o script sinalizar\u00e1 um erro.<\/li>\n<li><strong>Compara\u00e7\u00e3o de hash<\/strong>: O script calcula um hash (SHA256) do arquivo de hosts atual e o compara com uma vers\u00e3o em cache da \u00faltima execu\u00e7\u00e3o. Se houver uma incompatibilidade, isso indica que o arquivo foi modificado.<\/li>\n<li><strong>Compara\u00e7\u00e3o de conte\u00fado<\/strong>: Al\u00e9m de verificar apenas o hash, o script tamb\u00e9m compara o conte\u00fado linha por linha, destacando quaisquer adi\u00e7\u00f5es ou remo\u00e7\u00f5es.<\/li>\n<\/ol>\n<h2>Benef\u00edcios para profissionais de TI e MSPs<\/h2>\n<ul>\n<li><strong>Monitoramento proativo<\/strong>: Esse script oferece uma abordagem proativa para monitorar o arquivo hosts, garantindo sua integridade e alertando os administradores sobre quaisquer altera\u00e7\u00f5es n\u00e3o autorizadas.<\/li>\n<li><strong>Insights detalhados<\/strong>: Ao comparar as diferen\u00e7as de conte\u00fado, as equipes de TI podem identificar rapidamente o que foi adicionado ou removido, ajudando na r\u00e1pida corre\u00e7\u00e3o.<\/li>\n<li><strong>Pronto para automa\u00e7\u00e3o<\/strong>: Devido ao seu design, o script pode ser integrado a fluxos de trabalho automatizados, permitindo verifica\u00e7\u00f5es regulares sem interven\u00e7\u00e3o manual.<\/li>\n<\/ul>\n<h2>O poder do NinjaOne<\/h2>\n<p>O NinjaOne \u00e9 mais do que apenas uma solu\u00e7\u00e3o de gerenciamento de TI. \u00c9 uma plataforma abrangente que capacita os profissionais de TI e MSPs a se manterem \u00e0 frente das poss\u00edveis amea\u00e7as. Ao integrar nosso script de verifica\u00e7\u00e3o de arquivos hosts ao NinjaOne:<\/p>\n<ul>\n<li><strong>Alertas centralizados<\/strong>: Receba alertas diretamente no painel do NinjaOne sempre que o arquivo hosts for modificado. Essa notifica\u00e7\u00e3o imediata garante que voc\u00ea possa agir rapidamente, protegendo seus sistemas contra poss\u00edveis ataques.<\/li>\n<li><strong>Verifica\u00e7\u00f5es programadas<\/strong>: Automatize o script para ser executado em intervalos espec\u00edficos, garantindo o monitoramento cont\u00ednuo.<\/li>\n<li><strong>Relat\u00f3rios detalhados<\/strong>: Combine as percep\u00e7\u00f5es do script com os recursos de relat\u00f3rio do NinjaOne para obter uma vis\u00e3o hol\u00edstica de seu ambiente de TI.<\/li>\n<\/ul>\n<p>Concluindo, o arquivo hosts, embora muitas vezes ignorado, \u00e9 a pedra angular das comunica\u00e7\u00f5es de rede. Garantir sua integridade \u00e9 fundamental. Nosso script, especialmente quando combinado com o poder do NinjaOne, fornece \u00e0s equipes de TI as ferramentas necess\u00e1rias para <a href=\"https:\/\/www.ninjaone.com\/pt-br\/endpoint-management\/monitoramento-remoto-e-alertas\/\">monitorar, detectar e agir contra modifica\u00e7\u00f5es n\u00e3o autorizadas, garantindo um ambiente de TI seguro e tranquilo.<\/a><\/p>\n","protected":false},"author":35,"featured_media":142195,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_acf_changed":false,"_relevanssi_hide_post":"","_relevanssi_hide_content":"","_relevanssi_pin_for_all":"","_relevanssi_pin_keywords":"","_relevanssi_unpin_keywords":"","_relevanssi_related_keywords":"","_relevanssi_related_include_ids":"","_relevanssi_related_exclude_ids":"","_relevanssi_related_no_append":"","_relevanssi_related_not_related":"","_relevanssi_related_posts":"","_relevanssi_noindex_reason":"","_lmt_disableupdate":"no","_lmt_disable":""},"operating_system":[4212],"use_cases":[12460],"class_list":["post-808350","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/script_hub\/808350","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/comments?post=808350"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media\/142195"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media?parent=808350"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/operating_system?post=808350"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/use_cases?post=808350"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}