batch to replace hosts file windows
Solution 1
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.
Solution 2
None of it is necessary. An administrator can modify the hosts
file, no attrib
or cacls
required.
Just use:
copy /v /y "%HOMEDRIVE%\test\hosts" "%WinDir%\system32\drivers\etc\hosts"
Related videos on Youtube
acgbox
Updated on September 18, 2022Comments
-
acgbox over 1 year
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
-
acgbox about 5 yearsI do not see any answer I only see that he repeats exactly the same thing that I say in my question
-
shawn about 5 yearsHis answer is correct and complete. Perhaps your question needs work. I suspect what you're trying to ask is how do you reset the permissions on the hosts file to their defaults.
-
acgbox about 5 years@shawn You are right. I updated the question by adding what you mention. However I would like to receive an answer that does not repeat the same things that I already tried and that I describe in my question
-
-
Kinnectus about 5 yearsRun the script either as an administrator (right click "Run as Administrator") or create an on-demand Scheduled Task that has as administrator credentials. You can then run the task and it'll perform the task with the admin credentials... the recommended is the scheduled task (in Microsoft's eyes)...