Batch DOS code for Hosts Update (usable in Domain GPO)


To totally unlock this section you need to Log-in


Login

SCENARIO

There is the need to update hosts files on all the machines in your Windows environment/domain to prevent users to go on specific websites. You have to use a GPO (Group Policy Object) and the Startup policy to force the application of the solution in your domain.

SOLUTION

On a typical NT Domain you could use the gpedit.msc on a Domain Controller to access the Computer Configuration, then Windows Settings, then Scripts (Startup/Shutdown) and select the Startup entity.

The script we could use is the following, which it will add all entries in a text file (data.txt) to the hosts system file (C:\Windows\system32\drivers\etc):

@echo off

setLocal EnableDelayedExpansion
pushd C:\WINNT\system32\drivers\etc
for /f "tokens=1-2 delims= " %%a in (data.txt) do (
find /i "%%b" < hosts > nul
if errorlevel 1 echo %%a %%b >> hosts
)

An alternative script that we could use, specifying all the addresses to add in the hosts file:

@echo off

setLocal EnableDelayedExpansion
cd C:\Windows\system32\drivers\etc
find /i "www.example1.com" < hosts > nul
if errorlevel 1 (echo www.example1.com 127.0.0.1 >> hosts && echo www.example2.com 127.0.0.1 >> hosts && echo www.example3.com 127.0.0.1 >> hosts)
exit

NOTE: Startup scripts are machine specific and run before a user logs on. As a result they run in the context of the localSystem account on a computer. As localSystem, they have privilege to do just about anything on a Windows system. If a startup script needs to access network resources (e.g. a server share) however, localSystem will not work.

1 thought on “Batch DOS code for Hosts Update (usable in Domain GPO)”

Comments are closed.