{"id":208103,"date":"2023-09-19T09:16:12","date_gmt":"2023-09-19T09:16:12","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/come-identificare-un-file-hosts-modificato-con-powershell\/"},"modified":"2024-03-26T16:18:41","modified_gmt":"2024-03-26T16:18:41","slug":"come-identificare-un-file-hosts-modificato-con-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/it\/script-hub\/come-identificare-un-file-hosts-modificato-con-powershell\/","title":{"rendered":"Come verificare la presenza di un file Hosts modificato con PowerShell"},"content":{"rendered":"<p>Nel vasto regno dell&#8217;IT, il filehosts \u00e8 una sentinella silenziosa, che assicura il corretto funzionamento delle comunicazioni di rete. Per chi non lo sapesse, il <a href=\"https:\/\/www.ninjaone.com\/blog\/what-is-a-hosts-file\/\">file hosts<\/a> \u00e8 un file di testo che mappa i nomi di host a indirizzi IP. \u00c8 utilizzato dal sistema operativo per risolvere i nomi di host in indirizzi IP quando un computer cerca di connettersi a una risorsa di rete. Ma cosa succede quando il <strong>file hosts viene manomesso o modificato<\/strong>? Come possono i professionisti IT e i Managed Service Provider (MSP) garantire l&#8217;integrit\u00e0 di questo file cruciale? Con lo script in cuistiamo per addentrarci.<\/p>\n<h2>Comprendere il file hosts<\/h2>\n<p>Il filehosts, nella sua essenza, \u00e8 la rubrica del sistema informatico. Svolge un ruolo fondamentale nell&#8217;indirizzare il traffico di rete, assicurando che gli utenti arrivino ai siti web e ai servizi corretti. Tuttavia, la sua importanza lo rende anche un obiettivo primario per i malintenzionati.<\/p>\n<h2>I potenziali rischi delle modifiche non autorizzate<\/h2>\n<p>Un aggressore, con cattive intenzioni, potrebbe modificare il file hosts per reindirizzare il traffico verso un sito web o un server dannoso. Tali alterazioni possono avere conseguenze disastrose:<\/p>\n<ul>\n<li><strong>Rubare informazioni personali<\/strong>: Reindirizzando gli utenti verso siti contraffatti, gli aggressori possono richiedere i dati personali, con conseguente furto di identit\u00e0.<\/li>\n<li><strong>Installazione di malware<\/strong>: Gli utenti possono essere indotti a scaricare software dannoso pensando di trovarsi su un sito legittimo.<\/li>\n<li><strong>Interruzione delle comunicazioni di rete<\/strong>: I servizi essenziali possono essere bloccati, causando interruzioni operative.<\/li>\n<\/ul>\n<p>Alla luce di questi rischi, \u00e8 fondamentale che i professionisti IT e gli MSP dispongano di strumenti in grado di rilevare rapidamente eventuali modifiche non autorizzate. \u00c8 qui che entra in gioco il nostro script.<\/p>\n<h2>Lo script<\/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>Accedi a oltre 700 script nel Dojo di NinjaOne<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/it\/prova-gratuita\/\">Ottieni l&#8217;accesso<\/a><\/p>\n<\/div>\n<h2>Un&#8217;immersione profonda nello script<\/h2>\n<p>Lo script PowerShell fornito \u00e8 progettato per verificare se il file hosts \u00e8 stato modificato dall&#8217;ultima esecuzione. Ecco una panoramica delle sue funzionalit\u00e0:<\/p>\n<ol>\n<li><strong>Controllo dell&#8217;elevazione dei permessi<\/strong>: Lo script controlla innanzitutto se \u00e8 in esecuzione con i privilegi di amministratore. Questo \u00e8 fondamentale perch\u00e9 qualsiasi tentativo di leggere o modificare i file di sistema richiede autorizzazioni elevate.<\/li>\n<li><strong>Verifica del file hosts<\/strong>: Quindi verifica l&#8217;esistenza del file hosts. Se il file manca, lo script segnala un errore.<\/li>\n<li><strong>Confronto degli hash<\/strong>: Lo script calcola un hash (SHA256) del file hosts corrente e lo confronta con la versione in cache dell&#8217;ultima esecuzione. Se c&#8217;\u00e8 una mancata corrispondenza, questo indica che il file \u00e8 stato modificato.<\/li>\n<li><strong>Confronto del contenuto<\/strong>: Oltre a verificare l&#8217;hash, lo script confronta anche il contenuto riga per riga, evidenziando eventuali aggiunte o rimozioni.<\/li>\n<\/ol>\n<h2>Vantaggi per i professionisti IT e gli MSP<\/h2>\n<ul>\n<li><strong>Monitoraggio proattivo<\/strong>: Questo script offre un approccio proattivo per monitorare il file hosts, assicurandone l&#8217;integrit\u00e0 e avvisando gli amministratori di eventuali modifiche non autorizzate.<\/li>\n<li><strong>Approfondimenti dettagliati<\/strong>: Confrontando le differenze di contenuto, i team IT possono identificare rapidamente ci\u00f2 che \u00e8 stato aggiunto o rimosso, e questo permette di intervenire per una rapida correzione.<\/li>\n<li><strong>Pronto per l\u2019automazione<\/strong>: Grazie alla sua struttura, lo script pu\u00f2 essere integrato in flussi di lavoro automatizzati, consentendo controlli regolari senza interventi manuali.<\/li>\n<\/ul>\n<h2>Il potere di NinjaOne<\/h2>\n<p>NinjaOne \u00e8 pi\u00f9 di una semplice soluzione di gestione IT. Si tratta di una piattaforma completa che consente ai professionisti IT e agli MSP di essere sempre all&#8217;avanguardia rispetto alle potenziali minacce. Integrando il nostro script di controllo del file hosts in NinjaOne otterrai:<\/p>\n<ul>\n<li><strong>Avvisi centralizzati<\/strong>: Ricevi avvisi direttamente sulla dashboard di NinjaOne ogni volta che il file hosts viene modificato. Questa notifica immediata assicura che tu possa agire rapidamente, e in questo modo protegge i tuoi sistemi da potenziali attacchi.<\/li>\n<li><strong>Controlli programmati<\/strong>: Automatizza l&#8217;esecuzione dello script a intervalli specificati, ottenendo un monitoraggio continuo.<\/li>\n<li><strong>Report dettagliati<\/strong>: Combina le informazioni ricevute dallo script con le funzionalit\u00e0 di reporting di NinjaOne per ottenere una visione completa del tuo ambiente IT.<\/li>\n<\/ul>\n<p>In conclusione, il file hosts, anche se spesso trascurato, \u00e8 una pietra angolare delle comunicazioni di rete. Garantire la sua integrit\u00e0 \u00e8 fondamentale. Il nostro script, soprattutto se combinato con la potenza di NinjaOne, fornisce ai team IT gli strumenti necessari per <a href=\"https:\/\/www.ninjaone.com\/it\/gestione-endpoint\/monitoraggio-e-avvisi\">monitorare, rilevare e intervenire nel caso in cui ci siano modifiche non autorizzate, ed \u00e8 una garazia di un ambiente IT sicuro e senza problemi.<\/a><\/p>\n","protected":false},"author":35,"featured_media":207021,"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":[4269],"class_list":["post-208103","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub\/208103","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/comments?post=208103"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media\/207021"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/media?parent=208103"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/operating_system?post=208103"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/it\/wp-json\/wp\/v2\/use_cases?post=208103"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}