Windows

Batch scripting of Windows host file changes

DNS is the manageable way to resolve computer names to IP addresses, yet Windows admins usually use host files because they always work. But when you need to make a change to a bunch of host entries, where do you start?

DNS is the manageable way to resolve computer names to IP addresses, yet Windows admins usually use host files because they always work. But when you need to make a change to a bunch of host entries, where do you start?

----------------------------------------------------------------------------------------------------------------

It can be risky to use the Windows host file (which is located at C:\windows\system32\drivers\etc\hosts) for default installations if you need to make a change to a large number of systems with a local entry. Fortunately, there are a few ways to change these entries.

For example, look at a simple host file entry:

127.0.0.1                    localhost

192.168.1.10                 dhcp-122

192.168.1.14                 server94

Imagine that the DHCP-122 host is frequently used and many systems have a host entry with that IP address. As the system becomes more important, it is moved to another network and a static IP address. Assuming there is a resolution mechanism, the task is to replace the entry with a hashed out entry, as shown below:

#192.168.3.133              dhcp-122

Let's also assume that we don't want to remove the other entries in the file. This change comments out the entry and puts the new IP address in place. In the event that DNS or another mechanism cannot resolve the address, we can easily flip this entry for access.

To accomplish this task for a large number of systems, there are a few ways of going about it. One tool that I came across recently is Advanced Find and Replace, where a text file of paths can be loaded for a large find and replace task. The text file would contain entries like this:

Server393c$windowssystem32driversetchosts
Workstation2c$windowssystem32driversetchosts

Advanced Find and Replace can then go through all of those paths and make the requested change if the text string exists in the file. This task can also be accomplished with a stream editing tool like Sed for Windows.

Another way to address easy short name resolution without the nightmarish management of host files is to migrate to Windows Server 2008's DNS engine and use the GlobalNames zone -- although the host files would need to be removed for the DNS results to work.

Whatever tool you use to modify the entry, make sure you do not add a file extension to the hosts file -- the file will not function correctly with an extension. In general, you should stay away from using host files; however, certain situations warrant their use, and the manageability issues will soon follow.

Stay on top of the latest Windows Server 2003 and Windows Server 2008 tips and tricks with our free Windows Server newsletter, delivered each Wednesday. Automatically sign up today!

About

Rick Vanover is a software strategy specialist for Veeam Software, based in Columbus, Ohio. Rick has years of IT experience and focuses on virtualization, Windows-based server administration, and system hardware.

20 comments
The 'G-Man.'
The 'G-Man.'

I use it to hard code the private network details that exist between our servers so that nothing can cause name resolution problems with connections. All inter-server specific traffic runs over the private network and not near the PC LAN.

Michael Kassner
Michael Kassner

I guess I'm confused. I only use the host file as a last resort. Why would I even want to mess with it, especially as volatile as addressing is.

jgarcia
jgarcia

Are hosts files only used in a static environment? Can they be utilized in a DHCP environment? If so, what parameters would I need to use them in a DHCP Environment. Thanks. JG

b4real
b4real

Michael: I agree with you - but, the host files happen. My particular situation that caused me to automate the replacement of them actually replaced the entries with a removal of the entry. Sometimes IT staffers use them because 'they always work' for name resolution. Make no mistake, clearly, the better approach is DNS.

jcroson
jcroson

I've only used HOSTS files for an additional layer of protection for my users against sites that are known to contribute to the trojan/malware problem, in addition to 3rd party ads and cookies. http://www.mvps.org/winhelp2002/hosts.htm I script this in my users login using a variation of their mvps.bat script. Otherwise, I see know reason to replace my 2k3 AD's DNS role, as it IS part of AD. Of course, I also have my tried and true Debian BIND box as backup.... ;-)

thomasm
thomasm

I expected to see a script that would run with the login script to automatically update host file entries to all workstations, in case the dns server is failing. does anyone know how to create a batch-file that can only add an entrie to host file?

b4real
b4real

DNS is the way to go - but host files are used more frequently than we want to admit or know about!

Dumphrey
Dumphrey

The hosts file is more to do with DNS, not DHCP. The host file will take precedent over DNS (think of it as a static dns cache on the local machine). It does not assign IP addresses, it resolves IPs to names. Using static ip addressing and a hosts file is a good alternative to DNS for work groups. It can be used in a dynamic environment with some careful planning and thought. To see how it works, edit your host file to add the line 127.0.0.1 www.google.com save the file, close your browser, and ipconfig /flushdns in a cms window. Open your browser and try to open google.

Michael Kassner
Michael Kassner

Thanks for explaining that Rick, IMO, it seems like so much extra work. I guess I'd try to resolve the issue through other means.

JCitizen
JCitizen

replication failure. I know this is unlikely(hopefully); but shouldn't the whole study of disaster recovery include all scenarios? Perhaps even seemingly unlikely ones?

davidmastro
davidmastro

The following VBS script helps computers on my network find my SharePoint server located at 10.1.1.100: On Error Resume Next Const ForRead = 1 '*Opens file for reading Const ForWriting = 2 '*Opens file for writing, overwriting file Const ForAppend = 8 '*Opens file for Appending strComputer = "." '* This computer '* Connect to the WMI Service Set objWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") '* Open the host File Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile1 = objFSO.OpenTextFile("C:\Windows\System32\Drivers\Etc\hosts", ForRead) Set objFile2 = objFSO.CreateTextFile("C:\Windows\System32\Drivers\Etc\temphosts") Dim boolFound boolFound = False Do Until objFile1.AtEndOfStream '* Read line from input file strLine = objFile1.ReadLine If instr(strLine, "sharepoint") then strLine=Replace(strLine, "10.1.1.100 sharepoint" ) boolFound = True End If objFile2.Writeline strLine Loop If boolFound = False then objFile2.Writeline "10.1.1.100 sharepoint" End If objFSO.Copyfile "C:\Windows\System32\Drivers\Etc\temphosts", "C:\Windows\System32\Drivers\Etc\hosts" objFile1.Close objFile2.Close

laman
laman

Use AD to run this command on computers: echo 10.10.10.10 www.site.com > $PATH\hosts Or use your favourite scripting method.

kerjuk
kerjuk

Instead of trying to tweak the existing file on users/servers machines, I would suggest creating an Active Directory group or groups dependant on the hosts file content, then take copies and set Group Policy to distribute them. This method allows you to modify one file and rely on GP to handle the overwrite. A simple VBscript or batch file would suit the copy and replace.

frank.domnick
frank.domnick

Hi Thomas, I don't think that you would ever want to do this. It is not only the possible complexity of the scipt because the necessary string-operations might not really be straight forward. But that's just a question of how much work you are going to put into it until it will work. No, the point is that users would need to have write access to yout hosts file! Just imagine the damage that an "evil" user could do to your network if e.g. www.google.com is re-directed to a site with malware behind it!!

b4real
b4real

That is why I did this 'one-timer' to stop using the host entries on this collection of systems that I inherited. Funny thing is, sometimes products install host entries - making it tough.

Wizard-09
Wizard-09

I have a mix of DNS and host files, your right DNS is the right approch. The reason i used LMhost files is to do domain trusting with a few other sites we have. Clearly DNS was not doing it's job i was new to the company and did not have the time to fiddle about with DNS so i used lmhost files for the mapping.

davidmastro
davidmastro

Hmmm, not sure why the WMI service is connected, nor why the objFSO.Copyfile function incorrectly initiates the flux capacitor; but I can say that whatever this script does, it has without fail added a line to the hosts file of hundreds of computers for me. Someone provided me this script and I just changed the IP and hostname in it, i'm not really sure exactly how it works, but it worked for me, so I am merely passing it on in hope it may help someone else... if it's not up to your par then don't use it. Why waste everyone's time by simply criticizing it if you are so intelligent, I'm sure anyone reading this would much rather you post a reply with a new more efficient script than listening to you whine about why my post is a problem.

neilb
neilb

There's a couple of other interesting features as well. I'm pretty certain that the program that you've posted won't work. The objFSO.Copyfile function should be AFTER you've closed the files! The Replace function doesn't have sufficient parameters. Anyway, why not just have ' strLine="10.1.1.100 sharepoint" ' if you're changing an entry? If you use the CreateTextFile method and don't add the Overwrite parameter set to True, the program will fail if the 'temphosts' file exists. Neil :) I'm not being nasty but if you post a program that some people might find useful - and this is such a case - you really ought to debug it properly.

JCitizen
JCitizen

but I haven't played with GP or scripting for a while.

Editor's Picks