Windows – batch to replace hosts file windows

batchbatch filecommand linewindows

I am creating a batch script that replace hosts file in:

%WinDir%\system32\drivers\etc\hosts

I'm going to replace it with a backup that I have in a specific path:

batch script (run with administrative privileges):

%homedrive%\test\hosts-replace.bat

Content:

attrib -s -h -r "%WinDir%\system32\drivers\etc\hosts"
copy /v /y "%HOMEDRIVE%\test\hosts" "%WinDir%\system32\drivers\etc\hosts"
attrib +s +h +r "%WinDir%\system32\drivers\etc\hosts"

The problem is that i'm not sure if this is enough, since bleepingcomputer.com recommends running this command before the replacement (But the site does not explain how to reverse the command or its objective):

echo,Y|cacls "%WinDir%\system32\drivers\etc\hosts" /G everyone:f

Question: What is the correct way to replace hosts file with a batch script and reset the permissions on the hosts file to default?

Thanks in advance

Best Answer

To answer the permissions question, you can revoke everyone access with:

echo,Y|cacls "%WinDir%\system32\drivers\etc\hosts" /e /r everyone

This has the side-effect of revoking all rights since everyone is a group, so you should completely reset the permissions. The easy way is to delete the hosts file instead of copying it over itself, which will reset the permissions as assigned by the parent folder. As long as the etc folder hasn't also had its permissions munged you should be fine with:

del /f "%WinDir%\system32\drivers\etc\hosts"
copy /v "%HOMEDRIVE%\test\hosts" "%WinDir%\system32\drivers\etc\hosts"

Using only copy /y doesn't delete and recreate the file, so it won't reset the permissions to their defaults.

Related Question