{"id":208615,"date":"2024-01-22T12:07:11","date_gmt":"2024-01-22T12:07:11","guid":{"rendered":"https:\/\/www.ninjaone.com\/script-hub\/detectar-un-archivo-hosts-modificado\/"},"modified":"2024-03-26T16:19:00","modified_gmt":"2024-03-26T16:19:00","slug":"detectar-archivo-hosts-modificado-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/detectar-archivo-hosts-modificado-powershell\/","title":{"rendered":"C\u00f3mo detectar con Powershell un archivo Hosts modificado"},"content":{"rendered":"<p>En el vasto sector de las TI, el archivo hosts es como un centinela silencioso que garantiza la fluidez de las comunicaciones de red. Para los que no est\u00e9n familiarizados, el <a href=\"https:\/\/www.ninjaone.com\/blog\/what-is-a-hosts-file\/\">archivo hosts<\/a> es un archivo de texto que asigna nombres de host a direcciones IP. Lo utiliza el sistema operativo para resolver los nombres de host en direcciones IP cuando un ordenador intenta conectarse a un recurso de red. Pero, \u00bfqu\u00e9 ocurre cuando <strong>se manipula o se modifica el archivo hosts<\/strong>? \u00bfC\u00f3mo pueden los profesionales de TI y los proveedores de servicios gestionados (MSP) garantizar la integridad de este archivo crucial? Con el script en el que vamos a profundizar en unos instantes.<\/p>\n<h2>Entender el archivo Hosts<\/h2>\n<p>El archivo hosts, en su esencia, es la libreta de direcciones del sistema inform\u00e1tico. Desempe\u00f1a un papel fundamental a la hora de dirigir el tr\u00e1fico de la red, garantizando que los usuarios aterricen en los sitios web y servicios correctos. Sin embargo, su importancia tambi\u00e9n la convierte en un objetivo prioritario para los actores maliciosos.<\/p>\n<h2>Los riesgos potenciales de las modificaciones no autorizadas<\/h2>\n<p>Un atacante con malas intenciones podr\u00eda modificar el archivo hosts para redirigir el tr\u00e1fico a un sitio web o servidor malicioso. Tales alteraciones pueden tener consecuencias nefastas:<\/p>\n<ul>\n<li><strong>Robo de informaci\u00f3n personal<\/strong>: al redirigir a los usuarios a sitios falsos, los atacantes pueden suplantar sus datos personales y robar su identidad.<\/li>\n<li><strong>Instalaci\u00f3n de malware<\/strong>: se puede enga\u00f1ar a los usuarios para que descarguen programas maliciosos, pensando que est\u00e1n en un sitio leg\u00edtimo.<\/li>\n<li><strong>Interrupci\u00f3n de las comunicaciones de red<\/strong>: los servicios esenciales pueden bloquearse, causando interrupciones operativas.<\/li>\n<\/ul>\n<p>Ante estos riesgos, es primordial que los profesionales de TI y los MSP dispongan de herramientas capaces de detectar r\u00e1pidamente cualquier cambio no autorizado. Aqu\u00ed es donde entra en juego nuestro script.<\/p>\n<h2>El 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>Accede a m\u00e1s de 300 scripts en el Dojo de NinjaOne<\/p>\n<p><a href=\"https:\/\/www.ninjaone.com\/es\/prueba-gratuita-formulario\/\">Obt\u00e9n acceso<\/a><\/p>\n<\/div>\n<h2>Una inmersi\u00f3n profunda en el script<\/h2>\n<p>El script PowerShell proporcionado est\u00e1 dise\u00f1ado para comprobar si el archivo hosts ha sido modificado desde su \u00faltima ejecuci\u00f3n. Aqu\u00ed tienes un an\u00e1lisis global de su funcionalidad:<\/p>\n<ol>\n<li><strong>Control de la elevaci\u00f3n de los permisos<\/strong>: el script comprueba primero si se est\u00e1 ejecutando con privilegios de administrador. Esto es crucial porque cualquier intento de leer o modificar archivos del sistema requiere permisos elevados.<\/li>\n<li><strong>Verificaci\u00f3n del archivo hosts<\/strong>: a continuaci\u00f3n, verifica la existencia del archivo hosts. Si falta el archivo, el script indica un error.<\/li>\n<li><strong>Comparaci\u00f3n entre hash<\/strong>: el script calcula un hash (SHA256) del archivo hosts actual y lo compara con una versi\u00f3n en cach\u00e9 de la \u00faltima ejecuci\u00f3n. Si no coincide, indica que el archivo ha sido modificado.<\/li>\n<li><strong>Comparaci\u00f3n de contenidos<\/strong>: adem\u00e1s de comprobar el hash, el script tambi\u00e9n compara el contenido l\u00ednea por l\u00ednea, resaltando cualquier adici\u00f3n o eliminaci\u00f3n.<\/li>\n<\/ol>\n<h2>Ventajas para los profesionales de TI y los MSP<\/h2>\n<ul>\n<li><strong>Supervisi\u00f3n proactiva<\/strong>: este script ofrece un enfoque proactivo para monitorizar el archivo hosts, asegurando su integridad y alertando a los administradores de cualquier cambio no autorizado.<\/li>\n<li><strong>Informaci\u00f3n detallada<\/strong>: al comparar las diferencias de contenido, los equipos de TI pueden identificar r\u00e1pidamente lo que se ha a\u00f1adido o eliminado, lo que ayuda a una r\u00e1pida correcci\u00f3n.<\/li>\n<li><strong>Listo para la automatizaci\u00f3n<\/strong>: gracias a su estructura, el script puede integrarse en flujos de trabajo automatizados, lo que permite realizar comprobaciones peri\u00f3dicas sin intervenci\u00f3n manual.<\/li>\n<\/ul>\n<h2>El poder de NinjaOne<\/h2>\n<p>NinjaOne es m\u00e1s que una soluci\u00f3n de gesti\u00f3n de TI. Se trata de una plataforma integral que permite a los profesionales de TI y a los MSP adelantarse a las posibles amenazas. Integrando nuestro script de comprobaci\u00f3n de archivos hosts en NinjaOne obtendr\u00e1s<\/p>\n<ul>\n<li><strong>Alertas centralizadas<\/strong>: recibe alertas directamente en el panel de control de NinjaOne cada vez que se modifique el archivo hosts. Esta notificaci\u00f3n inmediata garantiza que puedas actuar con rapidez, protegiendo tus sistemas de posibles ataques.<\/li>\n<li><strong>Controles programados<\/strong>: automatiza el script para que se ejecute a intervalos especificados, garantizando as\u00ed una supervisi\u00f3n continua.<\/li>\n<li><strong>Generaci\u00f3n de informes pormenorizada<\/strong>: combina la informaci\u00f3n del script con las funciones de generaci\u00f3n de informes de NinjaOne para obtener una visi\u00f3n global de tu entorno de TI.<\/li>\n<\/ul>\n<p>En conclusi\u00f3n, el archivo hosts, aunque a menudo se pasa por alto, es una piedra angular de las comunicaciones en red. Garantizar su integridad es primordial. Nuestro script, especialmente cuando se combina con la potencia de NinjaOne, proporciona a los equipos de TI las herramientas que necesitan para <a href=\"https:\/\/www.ninjaone.com\/es\/supervision-gestion-de-endpoints\/supervision-remota-aviso-de-alertas\">supervisar, detectar y actuar contra modificaciones no autorizadas, garantizando un entorno de TI seguro y sin problemas.<\/a><\/p>\n","protected":false},"author":35,"featured_media":207026,"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":[4259],"class_list":["post-208615","script_hub","type-script_hub","status-publish","has-post-thumbnail","hentry","script_hub_category-windows","use_cases-configuracion-general"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/208615","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub"}],"about":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/types\/script_hub"}],"author":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/users\/35"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/comments?post=208615"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media\/207026"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=208615"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=208615"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=208615"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}