{"id":807219,"date":"2026-05-12T09:24:02","date_gmt":"2026-05-12T09:24:02","guid":{"rendered":"https:\/\/www.ninjaone.com\/?post_type=script_hub&#038;p=807219"},"modified":"2026-05-12T09:24:02","modified_gmt":"2026-05-12T09:24:02","slug":"detectar-brute-force-attacks-com-powershell","status":"publish","type":"script_hub","link":"https:\/\/www.ninjaone.com\/pt-br\/script-hub\/detectar-brute-force-attacks-com-powershell\/","title":{"rendered":"Detec\u00e7\u00e3o e preven\u00e7\u00e3o de ataques de for\u00e7a bruta com o PowerShell"},"content":{"rendered":"<p>Embora as amea\u00e7as cibern\u00e9ticas certamente estejam em constante evolu\u00e7\u00e3o, o fato \u00e9 que a maioria das invas\u00f5es ainda depende de t\u00e9cnicas b\u00e1sicas e comprovadas. Quem precisa queimar um dia zero se adivinhar senhas comumente usadas ou explorar senhas usadas em v\u00e1rias contas pode lhe dar acesso f\u00e1cil?<\/p>\n<p>Os ataques de for\u00e7a bruta continuam sendo uma amea\u00e7a incrivelmente comum que as organiza\u00e7\u00f5es enfrentam. Detectar e bloquear essas tentativas o mais r\u00e1pido poss\u00edvel \u00e9 fundamental, pois elas costumam ser o pren\u00fancio de atividades mais prejudiciais e tentativas de acesso mal-intencionado que est\u00e3o por vir. Como cada minuto conta nessas situa\u00e7\u00f5es, a configura\u00e7\u00e3o de pol\u00edticas de bloqueio de contas e alertas em tempo real para tentativas de login fracassadas \u00e9 uma medida extremamente importante de dissuas\u00e3o e alerta antecipado.<\/p>\n<p>Mas e quanto \u00e0 <strong>detec\u00e7\u00e3o de ataques de for\u00e7a bruta<\/strong> remotamente e em escala em uma rede corporativa inteira?<\/p>\n<p>Como isso pode ser um desafio, fornecemos o seguinte script que os administradores podem usar para automatizar o processo, <a href=\"https:\/\/www.ninjaone.com\/blog\/find-failed-login-attempts-windows-powershell\/\">monitorando as tentativas de login com falha<\/a> e acionando alertas com base em limites personaliz\u00e1veis.<\/p>\n<h2>Script de detec\u00e7\u00e3o e preven\u00e7\u00e3o de ataques de for\u00e7a bruta<\/h2>\n<p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\">#Requires -Version 5.1\r\n\r\n&lt;#\r\n.SYNOPSIS\r\n    Condition for helping detect brute force login attempts.\r\n.DESCRIPTION\r\n    Condition for helping detect brute force login attempts.\r\n.EXAMPLE\r\n     -Hours 10\r\n    Number of hours back in time to look through in the event log.\r\n    Default is 1 hour.\r\n.EXAMPLE\r\n    -Attempts 100\r\n    Number of login attempts to trigger at or above this number.\r\n    Default is 8 attempts.\r\n.OUTPUTS\r\n    PSCustomObject[]\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    [Parameter()]\r\n    [int]\r\n    $Hours = 1,\r\n    [Parameter()]\r\n    [int]\r\n    $Attempts = 8\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    function Test-StringEmpty {\r\n        param([string]$Text)\r\n        # Returns true if string is empty, null, or whitespace\r\n        process { [string]::IsNullOrEmpty($Text) -or [string]::IsNullOrWhiteSpace($Text) }\r\n    }\r\n    if (-not $(Test-StringEmpty -Text $env:Hours)) {\r\n        $Hours = $env:Hours\r\n    }\r\n    if (-not $(Test-StringEmpty -Text $env:Attempts)) {\r\n        $Attempts = $env:Attempts\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    if ($(auditpol.exe \/get \/category:* | Where-Object { $_ -like \"*Logon*Success and Failure\" })) {\r\n        Write-Information \"Audit Policy for Logon is set to: Success and Failure\"\r\n    }\r\n    else {\r\n        Write-Error \"Audit Policy for Logon is NOT set to: Success and Failure\"\r\n        exit 1\r\n        # Write-Host \"Setting Logon to: Success and Failure\"\r\n        # auditpol.exe \/set \/subcategory:\"Logon\" \/success:enable \/failure:enable\r\n        # Write-Host \"Future failed login attempts will be captured.\"\r\n    }\r\n\r\n    $StartTime = (Get-Date).AddHours(0 - $Hours)\r\n    $EventId = 4625\r\n\r\n    # Get failed login attempts\r\n    try {\r\n        $Events = Get-WinEvent -FilterHashtable @{LogName = \"Security\"; ID = $EventId; StartTime = $StartTime } -ErrorAction Stop | ForEach-Object {\r\n            $Message = $_.Message -split [System.Environment]::NewLine\r\n            $Account = $($Message | Where-Object { $_ -Like \"*Account Name:*\" }) -split 's+' | Select-Object -Last 1\r\n            [int]$LogonType = $($Message | Where-Object { $_ -Like \"Logon Type:*\" }) -split 's+' | Select-Object -Last 1\r\n            $SourceNetworkAddress = $($Message | Where-Object { $_ -Like \"*Source Network Address:*\" }) -split 's+' | Select-Object -Last 1\r\n            [PSCustomObject]@{\r\n                Account              = $Account\r\n                LogonType            = $LogonType\r\n                SourceNetworkAddress = $SourceNetworkAddress\r\n            }\r\n        } | Where-Object { $_.LogonType -in @(2, 7, 10) }\r\n    }\r\n    catch {\r\n        if ($_.Exception.Message -like \"No events were found that match the specified selection criteria.\") {\r\n            Write-Host \"No failed logins found in the past $Hours hour(s).\"\r\n            exit 0\r\n        }\r\n        else {\r\n            Write-Error $_\r\n            exit 1\r\n        }\r\n    }\r\n\r\n    # Build a list of accounts \r\n    $UsersAccounts = [System.Collections.Generic.List[String]]::new()\r\n    try {\r\n        $ErrorActionPreference = \"Stop\"\r\n        Get-LocalUser | Select-Object -ExpandProperty Name | ForEach-Object { $UsersAccounts.Add($_) }\r\n        $ErrorActionPreference = \"Continue\"\r\n    }\r\n    catch {\r\n        $NetUser = net.exe user\r\n        $(\r\n            $NetUser | Select-Object -Skip 4 | Select-Object -SkipLast 2\r\n            # Join each line with a \",\"\r\n            # Replace and spaces with a \",\"\r\n            # Split everything by \",\"\r\n        ) -join ',' -replace 's+', ',' -split ',' |\r\n            # Sort and remove any duplicates\r\n            Sort-Object -Descending -Unique |\r\n            # Filter out empty strings\r\n            Where-Object { -not [string]::IsNullOrEmpty($_) -and -not [string]::IsNullOrWhiteSpace($_) } |\r\n            ForEach-Object {\r\n                $UsersAccounts.Add($_)\r\n            }\r\n    }\r\n    $Events | Select-Object -ExpandProperty Account | ForEach-Object { $UsersAccounts.Add($_) }\r\n\r\n    $Results = $UsersAccounts | Select-Object -Unique | ForEach-Object {\r\n        $Account = $_\r\n        $AccountEvents = $Events | Where-Object { $_.Account -like $Account }\r\n        $AttemptCount = $AccountEvents.Count\r\n        $SourceNetworkAddress = $AccountEvents | Select-Object -ExpandProperty SourceNetworkAddress -Unique\r\n        if ($AttemptCount -gt 0) {\r\n            [PSCustomObject]@{\r\n                Account              = $Account\r\n                Attempts             = $AttemptCount\r\n                SourceNetworkAddress = $SourceNetworkAddress\r\n            }\r\n        }\r\n    }\r\n\r\n    # Get only the accounts with fail login attempts at or over $Attempts\r\n    $BruteForceAttempts = $Results | Where-Object { $_.Attempts -ge $Attempts }\r\n    if ($BruteForceAttempts) {\r\n        $BruteForceAttempts | Out-String | Write-Host\r\n        exit 1\r\n    }\r\n    $Results | Out-String | Write-Host\r\n    exit 0\r\n}\r\nend {\r\n    $ScriptVariables = @(\r\n        [PSCustomObject]@{\r\n            name           = \"Hours\"\r\n            calculatedName = \"hours\" # Must be lowercase and no spaces\r\n            required       = $false\r\n            defaultValue   = [PSCustomObject]@{ # If not default value, then remove\r\n                type  = \"TEXT\"\r\n                value = \"1\"\r\n            }\r\n            valueType      = \"TEXT\"\r\n            valueList      = $null\r\n            description    = \"Number of hours back in time to look through in the event log.\"\r\n        }\r\n        [PSCustomObject]@{\r\n            name           = \"Attempts\"\r\n            calculatedName = \"attempts\" # Must be lowercase and no spaces\r\n            required       = $false\r\n            defaultValue   = [PSCustomObject]@{ # If not default value, then remove\r\n                type  = \"TEXT\"\r\n                value = \"8\"\r\n            }\r\n            valueType      = \"TEXT\"\r\n            valueList      = $null\r\n            description    = \"Number of login attempts to trigger at or above this number.\"\r\n        }\r\n    )\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<br \/>\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><\/p>\n<h2>Entendendo e usando o script<\/h2>\n<p>Nosso script se baseia em dois par\u00e2metros principais: `Hours` e `-Attempts`. O par\u00e2metro `-Hours` determina o per\u00edodo a ser revisado no registro de eventos (padr\u00e3o: 1 hora). O par\u00e2metro `-Attempts` define o limite de tentativas de login antes de acionar um alerta (padr\u00e3o definido como 8 tentativas).<\/p>\n<h3>Para instalar e executar o script, siga estas etapas:<\/h3>\n<ol>\n<li>Abra o PowerShell com privil\u00e9gios de administrador.<\/li>\n<li>Copie o script em seu ambiente do PowerShell.<\/li>\n<li>Personalize os par\u00e2metros `-Hours` e `-Attempts` conforme necess\u00e1rio.<\/li>\n<li>Execute o script.<\/li>\n<\/ol>\n<p>Em seguida, o script avaliar\u00e1 os registros de eventos com base nos par\u00e2metros fornecidos. Se o n\u00famero de tentativas de login com falha ultrapassar o limite dentro do per\u00edodo de tempo especificado, ele o alertar\u00e1 sobre um poss\u00edvel ataque de for\u00e7a bruta.<\/p>\n<p>Considere um exemplo em que voc\u00ea deseja monitorar as tentativas de login nas \u00faltimas tr\u00eas horas e deseja receber um alerta se houver mais de 15 tentativas com falha. Com o NinjaOne, voc\u00ea tem a flexibilidade de personalizar sua abordagem de seguran\u00e7a executando o script com par\u00e2metros personalizados, como -Hours 3 -Attempts 15. Esse recurso permite que voc\u00ea se adapte \u00e0s necessidades de seguran\u00e7a e aos perfis de risco exclusivos da sua organiza\u00e7\u00e3o.<\/p>\n<h2>Medidas de seguran\u00e7a adicionais<\/h2>\n<p>A detec\u00e7\u00e3o de ataques de for\u00e7a bruta \u00e9 apenas um componente de uma estrat\u00e9gia hol\u00edstica de seguran\u00e7a cibern\u00e9tica. Outras medidas cruciais incluem:<\/p>\n<ul>\n<li><strong> Senhas fortes:<\/strong> Incentive os usu\u00e1rios a criar senhas robustas e exclusivas &#8211; de prefer\u00eancia, uma combina\u00e7\u00e3o de letras, n\u00fameros e s\u00edmbolos. Os gerenciadores de senhas podem facilitar o <a href=\"https:\/\/www.ninjaone.com\/blog\/secure-msp-credentials-password-management\/\">gerenciamento de senhas complexas<\/a>.<\/li>\n<li><strong>Autentica\u00e7\u00e3o multifatorial (MFA):<\/strong> A MFA fornece uma camada adicional de seguran\u00e7a, exigindo que os usu\u00e1rios verifiquem sua identidade usando dois ou mais mecanismos (por exemplo, algo que eles sabem, algo que eles t\u00eam ou algo que eles s\u00e3o).<\/li>\n<li><strong>Atualiza\u00e7\u00f5es de software:<\/strong> A atualiza\u00e7\u00e3o regular do software \u00e9 fundamental. As atualiza\u00e7\u00f5es geralmente incluem <a href=\"https:\/\/www.ninjaone.com\/pt-br\/patch-management\/\">corre\u00e7\u00f5es para vulnerabilidades de seguran\u00e7a<\/a> que, se n\u00e3o forem corrigidas, podem ser uma porta aberta para ataques cibern\u00e9ticos.<\/li>\n<li><strong>Treinamento de funcion\u00e1rios<\/strong>: O estabelecimento de um programa de treinamento de conscientiza\u00e7\u00e3o sobre seguran\u00e7a ajuda a educar os funcion\u00e1rios sobre as amea\u00e7as cibern\u00e9ticas e o papel que eles desempenham na manuten\u00e7\u00e3o da seguran\u00e7a. O fator humano \u00e9 geralmente o elo mais fraco da seguran\u00e7a cibern\u00e9tica, e funcion\u00e1rios bem informados podem refor\u00e7ar significativamente suas defesas.<\/li>\n<\/ul>\n<h2>Considera\u00e7\u00f5es finais<\/h2>\n<p>A detec\u00e7\u00e3o eficaz de for\u00e7a bruta \u00e9 crucial no atual cen\u00e1rio digital, e nosso script do PowerShell oferece uma solu\u00e7\u00e3o potente e personaliz\u00e1vel. No entanto, \u00e9 essencial lembrar que ele faz parte de uma estrat\u00e9gia mais ampla de seguran\u00e7a cibern\u00e9tica. Ao combinar a detec\u00e7\u00e3o em tempo real com senhas fortes, MFA, atualiza\u00e7\u00f5es de software e treinamento de funcion\u00e1rios, \u00e9 poss\u00edvel criar um protocolo de seguran\u00e7a abrangente para proteger seus ativos digitais.<\/p>\n<p>O NinjaOne \u00e9 uma ferramenta abrangente que refor\u00e7a significativamente sua capacidade de detectar e neutralizar ataques de for\u00e7a bruta. Com <a href=\"https:\/\/www.ninjaone.com\/pt-br\/rmm\/seguranca-de-endpoint\/\">controle total sobre a seguran\u00e7a do endpoint<\/a>, voc\u00ea pode gerenciar aplicativos, editar registros remotamente e implementar scripts para aumentar a seguran\u00e7a. Os controles de acesso baseados em fun\u00e7\u00f5es garantem que seus t\u00e9cnicos tenham apenas os n\u00edveis de acesso necess\u00e1rios, reduzindo os poss\u00edveis pontos de viola\u00e7\u00e3o. A plataforma tamb\u00e9m oferece ferramentas de gerenciamento de criptografia de unidades e a capacidade de instalar e gerenciar automaticamente a prote\u00e7\u00e3o de endpoints, proporcionando controle granular sobre as opera\u00e7\u00f5es de antiv\u00edrus.<\/p>\n<p>Al\u00e9m disso, <a href=\"https:\/\/www.ninjaone.com\/pt-br\/rmm\/credential-exchange\/\">o recurso de troca de credenciais do NinjaOne protege as credenciais<\/a>, uma linha cr\u00edtica de defesa contra ataques de for\u00e7a bruta. Ele tamb\u00e9m permite a identifica\u00e7\u00e3o e a remo\u00e7\u00e3o de endpoints desonestos, acrescentando uma camada extra de prote\u00e7\u00e3o. N\u00e3o espere que ocorra uma viola\u00e7\u00e3o. <a href=\"https:\/\/www.ninjaone.com\/pt-br\/solicitar-teste-gratis\/\">Comece sua jornada para aumentar a seguran\u00e7a<\/a> hoje mesmo com o NinjaOne.<\/p>\n","protected":false},"author":35,"featured_media":141643,"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-807219","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\/807219","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=807219"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media\/141643"}],"wp:attachment":[{"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/media?parent=807219"}],"wp:term":[{"taxonomy":"script_hub_category","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/operating_system?post=807219"},{"taxonomy":"use_cases","embeddable":true,"href":"https:\/\/www.ninjaone.com\/pt-br\/wp-json\/wp\/v2\/use_cases?post=807219"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}