{"id":374049,"date":"2024-10-23T11:56:25","date_gmt":"2024-10-23T11:56:25","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=374049"},"modified":"2024-10-23T11:56:25","modified_gmt":"2024-10-23T11:56:25","slug":"buscar-en-la-cache-dns","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/es\/script-hub\/buscar-en-la-cache-dns\/","title":{"rendered":"C\u00f3mo buscar en la cach\u00e9 DNS de forma eficaz con PowerShell: una gu\u00eda completa"},"content":{"rendered":"<p>En el mundo interconectado de hoy en d\u00eda, los profesionales de TI a menudo tienen que investigar y gestionar diversos problemas relacionados con la red. Uno de los aspectos cr\u00edticos de la soluci\u00f3n de problemas de red consiste en comprender las consultas <a href=\"https:\/\/www.ninjaone.com\/blog\/what-is-dns\/\" target=\"_blank\" rel=\"noopener\">DNS (Sistema de Nombres de Dominio)<\/a> y resolver los problemas relacionados con estas.<\/p>\n<p>El DNS es el protocolo responsable de traducir los nombres de dominio en direcciones IP que los ordenadores utilizan para comunicarse entre s\u00ed. En este contexto, buscar registros espec\u00edficos en la cach\u00e9 DNS puede ser una tarea esencial para los administradores de red y los <a href=\"https:\/\/www.ninjaone.com\/es\/que-es-un-msp\" target=\"_blank\" rel=\"noopener\">proveedores de servicios gestionados (MSP)<\/a>.<\/p>\n<p>Este post profundizar\u00e1 en un script PowerShell dise\u00f1ado para buscar en la cach\u00e9 DNS nombres de registros que coincidan con palabras clave especificadas. Exploraremos su contexto, c\u00f3mo funciona, sus aplicaciones en el mundo real y por qu\u00e9 es una herramienta inestimable para los profesionales de TI.<\/p>\n<h2>La importancia de la gesti\u00f3n de la cach\u00e9 DNS<\/h2>\n<p>Antes de centrarnos en el script, es crucial comprender la importancia de la gesti\u00f3n de la cach\u00e9 DNS. La cach\u00e9 DNS es una base de datos temporal mantenida por el sistema operativo que almacena registros de todas las visitas recientes e intentos de visita a sitios web y otros dominios de Internet. Esta cach\u00e9 permite un acceso m\u00e1s r\u00e1pido a los sitios visitados con frecuencia al reducir la necesidad de b\u00fasquedas DNS repetidas, lo que aumenta la eficacia de la navegaci\u00f3n.<\/p>\n<p>Sin embargo, a veces esta cach\u00e9 puede contener registros obsoletos o incorrectos, lo que puede provocar problemas de acceso al sitio web o vulnerabilidades de seguridad. Aqu\u00ed es donde la capacidad de buscar y gestionar la cach\u00e9 DNS se vuelve vital. El script del que hablaremos hoy proporciona una forma simplificada de buscar y analizar registros de cach\u00e9 DNS, lo que lo convierte en una herramienta indispensable para los profesionales de TI.<\/p>\n<h2>El script para buscar en la cach\u00e9 DNS<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Search for DNS cache record names that match the specified keywords.\r\n.DESCRIPTION\r\n    Search for DNS cache record names that match the specified keywords.\r\n    The DNS cache is a temporary database maintained by the operating system that contains records of all the recent visits and attempted visits to websites and other internet domains.\r\n    This script searches the DNS cache for record names that match the specified keywords and outputs the results to the Activity Feed.\r\n    Optionally, the results can be saved to a multiline custom field.\r\n\r\nPARAMETER: -Keywords \"ExampleInput\"\r\n    Comma separated list of keywords to search for in the DNS cache.\r\n.EXAMPLE\r\n    -Keywords \"arpa\"\r\n    ## EXAMPLE OUTPUT WITH Keywords ##\r\n    Entry: 1.80.19.172.in-addr.arpa, Record Name: 1.80.19.172.in-addr.arpa., Record Type: 12, Data: test.mshome.net, TTL: 598963\r\n\r\nPARAMETER: -Keywords \"arpa,mshome\" -MultilineCustomField \"ReplaceMeWithAnyMultilineCustomField\"\r\n    The name of the multiline custom field to save the results to.\r\n.EXAMPLE\r\n    -Keywords \"arpa,mshome\" -MultilineCustomField \"ReplaceMeWithAnyMultilineCustomField\"\r\n    ## EXAMPLE OUTPUT WITH MultilineCustomField ##\r\n    Entry: 1.80.19.172.in-addr.arpa, Record Name: 1.80.19.172.in-addr.arpa., Record Type: 12, Data: test.mshome.net, TTL: 598963\r\n    Entry: test.mshome.net, Record Name: test.mshome.net., Record Type: 1, Data: 172.19.80.1, TTL: 598963\r\n\r\n.NOTES\r\n    Minimum OS Architecture Supported: Windows 10, Windows Server 2016\r\n    Release Notes: 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    [Parameter()]\r\n    [String[]]$Keywords,\r\n    [Parameter()]\r\n    [String]$MultilineCustomField\r\n)\r\n\r\nbegin {\r\n    $ExitCode = 0\r\n    function Set-NinjaProperty {\r\n        [CmdletBinding()]\r\n        Param(\r\n            [Parameter(Mandatory = $True)]\r\n            [String]$Name,\r\n            [Parameter()]\r\n            [String]$Type,\r\n            [Parameter(Mandatory = $True, ValueFromPipeline = $True)]\r\n            $Value,\r\n            [Parameter()]\r\n            [String]$DocumentName\r\n        )\r\n    \r\n        $Characters = $Value | Measure-Object -Character | Select-Object -ExpandProperty Characters\r\n        if ($Characters -ge 10000) {\r\n            throw [System.ArgumentOutOfRangeException]::New(\"Character limit exceeded, value is greater than 10,000 characters.\")\r\n        }\r\n        \r\n        # If we're requested to set the field value for a Ninja document we'll specify it here.\r\n        $DocumentationParams = @{}\r\n        if ($DocumentName) { $DocumentationParams[\"DocumentName\"] = $DocumentName }\r\n        \r\n        # This is a list of valid fields that can be set. If no type is given, it will be assumed that the input doesn't need to be changed.\r\n        $ValidFields = \"Attachment\", \"Checkbox\", \"Date\", \"Date or Date Time\", \"Decimal\", \"Dropdown\", \"Email\", \"Integer\", \"IP Address\", \"MultiLine\", \"MultiSelect\", \"Phone\", \"Secure\", \"Text\", \"Time\", \"URL\", \"WYSIWYG\"\r\n        if ($Type -and $ValidFields -notcontains $Type) { Write-Warning \"$Type is an invalid type! Please check here for valid types. https:\/\/ninjarmm.zendesk.com\/hc\/en-us\/articles\/16973443979789-Command-Line-Interface-CLI-Supported-Fields-and-Functionality\" }\r\n        \r\n        # The field below requires additional information to be set\r\n        $NeedsOptions = \"Dropdown\"\r\n        if ($DocumentName) {\r\n            if ($NeedsOptions -contains $Type) {\r\n                # We'll redirect the error output to the success stream to make it easier to error out if nothing was found or something else went wrong.\r\n                $NinjaPropertyOptions = Ninja-Property-Docs-Options -AttributeName $Name @DocumentationParams 2&gt;&amp;1\r\n            }\r\n        }\r\n        else {\r\n            if ($NeedsOptions -contains $Type) {\r\n                $NinjaPropertyOptions = Ninja-Property-Options -Name $Name 2&gt;&amp;1\r\n            }\r\n        }\r\n        \r\n        # If an error is received it will have an exception property, the function will exit with that error information.\r\n        if ($NinjaPropertyOptions.Exception) { throw $NinjaPropertyOptions }\r\n        \r\n        # The below type's require values not typically given in order to be set. The below code will convert whatever we're given into a format ninjarmm-cli supports.\r\n        switch ($Type) {\r\n            \"Checkbox\" {\r\n                # While it's highly likely we were given a value like \"True\" or a boolean datatype it's better to be safe than sorry.\r\n                $NinjaValue = [System.Convert]::ToBoolean($Value)\r\n            }\r\n            \"Date or Date Time\" {\r\n                # Ninjarmm-cli expects the GUID of the option to be selected. Therefore, the given value will be matched with a GUID.\r\n                $Date = (Get-Date $Value).ToUniversalTime()\r\n                $TimeSpan = New-TimeSpan (Get-Date \"1970-01-01 00:00:00\") $Date\r\n                $NinjaValue = $TimeSpan.TotalSeconds\r\n            }\r\n            \"Dropdown\" {\r\n                # Ninjarmm-cli is expecting the guid of the option we're trying to select. So we'll match up the value we were given with a guid.\r\n                $Options = $NinjaPropertyOptions -replace '=', ',' | ConvertFrom-Csv -Header \"GUID\", \"Name\"\r\n                $Selection = $Options | Where-Object { $_.Name -eq $Value } | Select-Object -ExpandProperty GUID\r\n        \r\n                if (-not $Selection) {\r\n                    throw [System.ArgumentOutOfRangeException]::New(\"Value is not present in dropdown\")\r\n                }\r\n        \r\n                $NinjaValue = $Selection\r\n            }\r\n            default {\r\n                # All the other types shouldn't require additional work on the input.\r\n                $NinjaValue = $Value\r\n            }\r\n        }\r\n        \r\n        # We'll need to set the field differently depending on if its a field in a Ninja Document or not.\r\n        if ($DocumentName) {\r\n            $CustomField = Ninja-Property-Docs-Set -AttributeName $Name -AttributeValue $NinjaValue @DocumentationParams 2&gt;&amp;1\r\n        }\r\n        else {\r\n            $CustomField = Ninja-Property-Set -Name $Name -Value $NinjaValue 2&gt;&amp;1\r\n        }\r\n        \r\n        if ($CustomField.Exception) {\r\n            throw $CustomField\r\n        }\r\n    }\r\n}\r\nprocess {\r\n    # Get the keywords to search for in the DNS cache\r\n    $Keywords = if ($env:keywordsToSearch -and $env:keywordsToSearch -ne \"null\") {\r\n        $env:keywordsToSearch -split \",\" | ForEach-Object { $_.Trim() }\r\n    }\r\n    else {\r\n        $Keywords -split \",\" | ForEach-Object { $_.Trim() }\r\n    }\r\n    $Keywords = if ($Keywords -and $Keywords -ne \"null\") {\r\n        $Keywords | ForEach-Object {\r\n            Write-Host \"[Info] Searching for DNS Cache Records Matching: $_\"\r\n            Write-Output \"*$_*\"\r\n        }\r\n    }\r\n    else {\r\n        # Exit if Keywords is empty\r\n        Write-Host \"[Error] No Keywords Provided\"\r\n        $ExitCode = 1\r\n        exit $ExitCode\r\n    }\r\n    # Get the multiline custom field to save the results to\r\n    $MultilineCustomField = if ($env:multilineCustomField -and $env:multilineCustomField -ne \"null\") {\r\n        $env:multilineCustomField -split \",\" | ForEach-Object { $_.Trim() }\r\n    }\r\n    else {\r\n        $MultilineCustomField -split \",\" | ForEach-Object { $_.Trim() }\r\n    }\r\n\r\n    Write-Host \"\"\r\n\r\n    # Get the DNS cache entries that match the keywords\r\n    $DnsCache = Get-DnsClientCache -Name $Keywords | Select-Object -Property Entry, Name, Type, Data, TimeToLive\r\n\r\n    if ($null -eq $DnsCache) {\r\n        Write-Host \"[Warn] No DNS Cache Entries Found\"\r\n    }\r\n    else {\r\n        # Format the DNS cache entries\r\n        $Results = $DnsCache | ForEach-Object {\r\n            \"Entry: $($_.Entry), Record Name: $($_.Name), Record Type: $($_.Type), Data: $($_.Data), TTL: $($_.TimeToLive)\"\r\n        }\r\n        Write-Host \"[Info] DNS Cache Entries Found\"\r\n        # Save the results to a multiline custom field if specified\r\n        if ($MultilineCustomField -and $MultilineCustomField -ne \"null\") {\r\n            Write-Host \"[Info] Attempting to set Custom Field '$MultilineCustomField'.\"\r\n            try {\r\n                Set-NinjaProperty -Name $MultilineCustomField -Value $($Results | Out-String)\r\n                Write-Host \"[Info] Successfully set Custom Field '$MultilineCustomField'!\"\r\n            }\r\n            catch {\r\n                Write-Host \"[Warn] Failed to set Custom Field '$MultilineCustomField'.\"\r\n                $Results | Out-String | Write-Host\r\n            }\r\n        }\r\n        else {\r\n            # Output the results to the Activity Feed\r\n            $Results | Out-String | Write-Host\r\n        }\r\n    }\r\n    exit $ExitCode\r\n}\r\nend {\r\n    \r\n    \r\n    \r\n}<\/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>Desglose detallado del script<\/h2>\n<p>Vamos a desglosar el script para entender c\u00f3mo funciona y la funcionalidad que ofrece.<\/p>\n<h3>1. Inicializaci\u00f3n del script:<\/h3>\n<ul>\n<li>El script comienza configurando par\u00e1metros que permiten a los usuarios especificar palabras clave para buscar en la cach\u00e9 DNS. Estas palabras clave se introducen como una lista separada por comas.<\/li>\n<li>Un par\u00e1metro opcional permite a los usuarios guardar los resultados en un campo personalizado multil\u00ednea. Esto es especialmente \u00fatil para fines de registro y documentaci\u00f3n.<\/li>\n<\/ul>\n<h3>2. Tratamiento de palabras clave:<\/h3>\n<ul>\n<li>El script procesa las palabras clave proporcionadas, asegur\u00e1ndose de que est\u00e1n formateadas correctamente para la operaci\u00f3n de b\u00fasqueda. Si no se proporcionan palabras clave, el script saldr\u00e1 con un error, asegur\u00e1ndose de que los usuarios son conscientes de la entrada que falta.<\/li>\n<\/ul>\n<h3>3. Recuperaci\u00f3n de cach\u00e9 DNS:<\/h3>\n<ul>\n<li>El n\u00facleo del script consiste en recuperar las entradas de la cach\u00e9 DNS mediante el cmdlet Get-DnsClientCache. Este cmdlet obtiene los registros DNS de la cach\u00e9 local que coinciden con las palabras clave especificadas.<\/li>\n<li>A continuaci\u00f3n, los resultados se formatean para mostrar la entrada, el nombre del registro, el tipo de registro, los datos y el tiempo de vida (TTL) de cada registro DNS encontrado.<\/li>\n<\/ul>\n<h3>4. Gesti\u00f3n del output:<\/h3>\n<ul>\n<li>Si se especifica el campo personalizado multil\u00ednea opcional, el script intenta guardar los resultados en este campo utilizando una funci\u00f3n personalizada llamada Set-NinjaProperty. Esta funci\u00f3n maneja varios tipos de datos de entrada y garantiza que el campo se actualice correctamente.<\/li>\n<li>Si no se especifica el campo personalizado, los resultados se env\u00edan simplemente al feed de actividad, lo que permite una revisi\u00f3n y un an\u00e1lisis r\u00e1pidos.<\/li>\n<\/ul>\n<h2>Casos de uso concretos<\/h2>\n<p>Para ilustrar la utilidad de este script, imag\u00ednate a un profesional de TI que est\u00e1 solucionando un problema de red para un cliente, que informa de problemas intermitentes de conectividad con determinados sitios web. El profesional de TI sospecha que las entradas de cach\u00e9 DNS obsoletas o incorrectas pueden estar causando el problema.<\/p>\n<p>Con este script PowerShell, el profesional de TI puede buscar r\u00e1pidamente en la cach\u00e9 DNS cualquier registro relacionado con los sitios web problem\u00e1ticos. Al identificar estos registros, puede determinar si es necesario limpiar la cach\u00e9 DNS o actualizar entradas espec\u00edficas. Este enfoque selectivo ahorra tiempo y garantiza que los problemas de red del cliente se resuelvan con eficacia.<\/p>\n<h2>Comparaci\u00f3n con otros m\u00e9todos<\/h2>\n<p>Este script PowerShell proporciona un enfoque m\u00e1s automatizado y personalizable para buscar en la cach\u00e9 DNS en comparaci\u00f3n con otros m\u00e9todos manuales. Aunque es posible inspeccionar manualmente las entradas de la cach\u00e9 DNS utilizando el comando ipconfig \/displaydnscommand, este enfoque puede ser laborioso y llevar mucho tiempo, especialmente cuando se trata de cach\u00e9s grandes o de m\u00faltiples palabras clave.<\/p>\n<p>Adem\u00e1s, la posibilidad de guardar los resultados en un campo personalizado para su posterior revisi\u00f3n o documentaci\u00f3n diferencia este script de otros m\u00e9todos m\u00e1s b\u00e1sicos, lo que lo hace m\u00e1s vers\u00e1til para uso profesional.<\/p>\n<h2>Preguntas frecuentes<\/h2>\n<h3>\u00bfQu\u00e9 sistemas operativos admiten este script?<\/h3>\n<p>Este script es compatible con Windows 10 y Windows Server 2016 o posteriores.<\/p>\n<h3>\u00bfQu\u00e9 ocurre si no se proporcionan palabras clave?<\/h3>\n<p>El script saldr\u00e1 con un error, notificando al usuario que se necesitan palabras clave para realizar la b\u00fasqueda.<\/p>\n<h3>\u00bfSe pueden guardar los resultados para utilizarlos m\u00e1s adelante?<\/h3>\n<p>S\u00ed, los resultados pueden guardarse en un campo personalizado multil\u00ednea, que puede ser \u00fatil para documentaci\u00f3n o an\u00e1lisis posteriores.<\/p>\n<h2>Implicaciones para la seguridad de las b\u00fasquedas en la cach\u00e9 DNS<\/h2>\n<p>Buscar en la cach\u00e9 DNS no es s\u00f3lo solucionar problemas; tambi\u00e9n tiene importantes implicaciones para la seguridad. Mediante la supervisi\u00f3n peri\u00f3dica de las entradas de cach\u00e9 DNS, los profesionales de TI pueden detectar entradas potencialmente maliciosas o patrones inusuales que podr\u00edan indicar una brecha de seguridad o un intento de phishing. Este enfoque proactivo de la gesti\u00f3n de DNS es un aspecto crucial para mantener un entorno de red seguro.<\/p>\n<h2>Recomendaciones para utilizar este script<\/h2>\n<p>Cuando utilices este script, ten en cuenta las siguientes pr\u00e1cticas recomendadas:<\/p>\n<ul>\n<li>Supervisa regularmente la cach\u00e9 DNS para asegurarte de que las entradas est\u00e1n actualizadas y libres de registros potencialmente maliciosos.<\/li>\n<li>Documenta cualquier hallazgo significativo guardando los resultados en un campo personalizado, al que se puede hacer referencia en futuras soluciones de problemas o auditor\u00edas de seguridad.<\/li>\n<li>Combina este script con otras herramientas de gesti\u00f3n de DNS para un enfoque integral de la seguridad y el rendimiento de DNS.<\/li>\n<\/ul>\n<h2>Reflexiones finales<\/h2>\n<p>La gesti\u00f3n eficaz de la cach\u00e9 de DNS es una tarea cr\u00edtica para los profesionales de TI y los MSP, y este script de PowerShell ofrece una potente herramienta para agilizar este proceso. Al permitir b\u00fasquedas r\u00e1pidas y espec\u00edficas de las entradas de la cach\u00e9 DNS, los equipos de TI pueden resolver los problemas de la red con mayor eficacia y <a href=\"https:\/\/www.ninjaone.com\/blog\/what-is-wireless-network-security\/\" target=\"_blank\" rel=\"noopener\">mejorar la seguridad general de la red<\/a>.<\/p>\n<p>NinjaOne, l\u00edder en soluciones de gesti\u00f3n de TI, proporciona las herramientas necesarias para automatizar y optimizar dichas tareas, garantizando que los profesionales puedan mantener <a href=\"https:\/\/www.ninjaone.com\/es\/eficiencia\" target=\"_blank\" rel=\"noopener\">entornos de red robustos, seguros y eficientes<\/a>. Este script es s\u00f3lo un ejemplo de c\u00f3mo <a href=\"https:\/\/www.ninjaone.com\/es\/rmm\/automatizacion-de-ti\/\" target=\"_blank\" rel=\"noopener\">la automatizaci\u00f3n<\/a> y un scripting bien planteado pueden mejorar las operaciones de TI y la prestaci\u00f3n de servicios.<\/p>\n","protected":false},"author":35,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"open","ping_status":"open","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-374049","script_hub","type-script_hub","status-publish","hentry","script_hub_category-windows","use_cases-configuracion-general"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/script_hub\/374049","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=374049"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/media?parent=374049"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/operating_system?post=374049"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/es\/wp-json\/wp\/v2\/use_cases?post=374049"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}