Replace an IP in the "hosts" file with the IP from a ping result Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
alin89c
Posts: 6
Joined: 14 Sep 2021, 23:26
Contact:

Replace an IP in the "hosts" file with the IP from a ping result

Post by alin89c » 18 Sep 2021, 03:44

Hi there!

I would like to write a script that when triggered would do the following:
1. Execute the following Command Prompt line: "ping aaa".
2. Extract the IP address of the computer named "aaa" and store it in a variable ("new_ip").
3. Open the "hosts" file and replace the "192.168.43.2 osc_server" line with this one: "%new_ip% osc_server".

I would like to know how to do the first two steps.

Thank you!
User avatar
mikeyww
Posts: 26595
Joined: 09 Sep 2014, 18:38

Re: Replace an IP in the "hosts" file with the IP from a ping result  Topic is solved

Post by mikeyww » 18 Sep 2021, 06:38

Code: Select all

Clipboard =
RunWait, %ComSpec% /c ping -n 1 google.com | clip,, Hide
ClipWait, 0
If ErrorLevel {
 MsgBox, 48, Error, An error occurred while waiting for the clipboard.
 Return
} Else RegExMatch(Clipboard, "Reply from \K[\d.]+", new_ip)
MsgBox, 64, IP address, %new_ip%
User avatar
alin89c
Posts: 6
Joined: 14 Sep 2021, 23:26
Contact:

Re: Replace an IP in the "hosts" file with the IP from a ping result

Post by alin89c » 18 Sep 2021, 11:10

Have done it. Hurray!
Thank you, @mikeyww !

Code: Select all

!a::
; 1) new_ip variale
; (store the IP of the computer named "aaa" into the "%new_ip%" variable)
; Credit goes to mikeyww (https://www.autohotkey.com/boards/memberlist.php?mode=viewprofile&u=59977)
Clipboard =
RunWait, %ComSpec% /c ping -n 1 aaa | clip,, Hide
ClipWait, 0
If ErrorLevel {
 MsgBox, 48, Error, An error occurred while waiting for the clipboard.
 Return
} Else RegExMatch(Clipboard, "Reply from \K[\d.]+", new_ip)

; 2) LineNum variable
; (store to a variable the line number in which "osc_server" is contained; this helps in finding which line should be replaced in the next step)
strToFind := "osc_server"
Loop, Read, c:\Windows\System32\drivers\etc\hosts
{
         IfInString, A_LoopReadLine, %strToFind%
            {
               LineNum := A_Index
             } 
}

; 3) Replace the line containing "osc_server"
newLineContent = %new_ip% osc_server
Loop, Read, c:\Windows\System32\drivers\etc\hosts
	{
		If A_Index = %LineNum%
			FileAppend, %newLineContent%`n, %A_Temp%\Temp.txt
		Else
			FileAppend, %A_LoopReadLine%`n, %A_Temp%\Temp.txt
	}
FileMove, %A_Temp%\Temp.txt, c:\Windows\System32\drivers\etc\hosts, 1
Post Reply

Return to “Ask for Help (v1)”