Alteração do arquivo HOSTS do Windows via GPO

FelipeSantosBRA 61 Reputation points
2025-05-20T21:19:18.2033333+00:00

Boa noite, galera. 

Solicito o apoio da equipe de Windows para a seguinte demanda:

 

  • Eu criei um script .BAT que adiciona uma linha no arquivo HOSTS do Windows.
  • O script executado localmente, como administrador, funciona perfeitamente.
  • O problema está sendo executar esse script via GPO, pois nenhuma das alternativas que pesquisei e tentei consegue alterar o arquivo HOSTS nos desktops de homologação da TI (W10 e W11).
  • O problema parece ser a permissão necessária para que o script altere o arquivo HOSTS (não é uma substituição de arquivo, apenas uma adição de uma linha de dados).
  • Uma das alternativas pesquisadas foi a criação de dois scripts: um script launcher que executa o script de alteração. Depois, era só criar uma GPO que copiasse estes dois scripts para uma pasta na máquina local, além de adicioná-los no script de inicialização do computador. Porém, o problema de permissão parece persistir, pois o arquivo HOSTS continua inalterado.

Alguém consegue me ajudar com esta demanda? Seguem abaixo os scripts citados:

  • Script que altera o arquivo HOSTS (script_hosts_OK.bat):
@@echo off
setlocal EnableDelayedExpansion

:: Caminho do arquivo hosts
set "HOSTS=%SystemRoot%\System32\drivers\etc\hosts"

:: Diretório e arquivo de log (ajuste o caminho se necessário)
set "LOGDIR=%SystemRoot%\Temp"
set "LOGFILE=%LOGDIR%\script_hosts_OK.txt"

:: Garante que o diretório de log existe
if not exist "%LOGDIR%" mkdir "%LOGDIR%"

:: Início do log
echo ---------------------------------------- >> "%LOGFILE%"
echo [%DATE% %TIME%] Início do patch >> "%LOGFILE%"

:: Remove o atributo somente leitura
attrib -r "%HOSTS%" >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    echo [%DATE% %TIME%] Atributo 'somente leitura' removido de hosts >> "%LOGFILE%"
) else (
    echo [%DATE% %TIME%] Falha ao remover atributo 'somente leitura' >> "%LOGFILE%"
)

:: Entradas a adicionar (edite aqui)
set "ENTRY1=127.0.0.1 exemplo.com.br"

:: Verifica e adiciona cada uma
call :AddIfMissing "!ENTRY1!"

echo [%DATE% %TIME%] Fim do patch >> "%LOGFILE%"
echo. >> "%LOGFILE%"

endlocal
exit /b

:AddIfMissing
setlocal
set "LINE=%~1"

:: Ignora se linha vazia
if "%LINE%"=="" exit /b

:: Verifica se já existe
findstr /C:"%LINE%" "%HOSTS%" >nul 2>&1
if %ERRORLEVEL% NEQ 0 (
    >>"%HOSTS%" echo %LINE%
    echo [%DATE% %TIME%] Adicionado: %LINE% >> "%LOGFILE%"
) else (
    echo [%DATE% %TIME%] Já existia: %LINE% >> "%LOGFILE%"
)
endlocal
exit /b

  • Script executa o script acima (launcher_hosts.bat):
@echo off
setlocal

:: Caminho do script principal (ajuste se estiver em outro lugar)
set "SCRIPT=%~dp0script_hosts_OK.bat"

:: Verifica se o script existe
if not exist "%SCRIPT%" (
    echo Script não encontrado: %SCRIPT%
    exit /b 1
)

:: Executa o script de alteração silenciosamente
call "%SCRIPT%"

endlocal
exit /b

Obrigado pela atenção de todos.

Windows for business | Windows Client for IT Pros | Directory services | Active Directory
0 comments No comments
{count} votes

Accepted answer
  1. Benjamin Wang 75 Reputation points Microsoft External Staff Moderator
    2025-05-30T07:44:59.2533333+00:00

    Hello,

    Thank you for posting the question on Microsoft Windows forum!

    The problem you described does not appear to be with the script itself but is caused by the permissions used when executing the script through a GPO. When you run the script locally as an "administrator," it inherits all the necessary permissions to modify protected files (such as the HOSTS file located at C:\Windows\System32\drivers\etc\hosts). However, when the script is executed via a GPO—whether as a startup script or a logon script—the security context is different, and even when using the system account, it often does not have the same permissions, which results in the file not being modified.

    You can ensure that the HOSTS file has the appropriate permissions for modification. You can use a GPO to explicitly configure the ACL (Access Control List) for that file. For example, you can follow this path:

    Computer Configuration → Policies → Windows Settings → Security Settings → File System

    Under this path, you can add a new entry that points to the HOSTS file, and then grant write permissions either to the required group or directly to the Local System account. This way, the system account will also be able to modify the HOSTS file via the script.

    Hope the above steps are helpful!


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.