We help IT Professionals succeed at work.
Get Started

modify host file with autoit

1,211 Views
Last Modified: 2015-06-23
have some servers that i need to modify the host file on if they can't resolve. would like to do it with autoit
Basically i want to check to see if say "myserver.domain.com" is pinging and if it isn't then change/add entry to host file to the correct ip address.

So if its currently 12.12.12.1   i want to search the host file and comment out the line for 12.12.12.1 if it exist and change it to 10.10.10.1 (obviously the ips are examples).

i have this so far but not sure how to parse the host file and change existing entries. thanks!
changehost()

Func changehost()
    ; Ping myserver.domain.com with a timeout of 250ms.
    Local $iPing = Ping("myserver.domain.com", 250)
    Local $ipaddress = TCPNameToIP("myserver.domain.com")
	$Server = "myserver.domain.com"
    If $iPing Then ; If a value greater than 0 then all is good..

	 Else ; we need to change the host entry
		 if $ipaddress = "12.12.12.1" Then
			$OPENHOSTS = FileOpen("C:\WINDOWS\system32\drivers\etc\hosts", 1)
			FileWrite($OPENHOSTS, "10.10.10.1" & @TAB & $Server & @CRLF)
			FileClose($OPENHOSTS)
			; write to host file 10.10.10.1 and remove entry with 12.12.12.1 this is where i'm confused on how to do that
		 Else
			$OPENHOSTS = FileOpen("C:\WINDOWS\system32\drivers\etc\hosts", 1)
			FileWrite($OPENHOSTS, "12.12.12.1" & @TAB & $Server & @CRLF)
			FileClose($OPENHOSTS)
			;write to the host file 12.12.12.1 and remove 10.10.10.1 entry
		 EndIf
        
    EndIf
 EndFunc   ;==>changehost

Open in new window

Comment
Watch Question
Commented:
This problem has been solved!
Unlock 1 Answer and 12 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE