Jump to content

HOSTS file configurator


Rex
 Share

Recommended Posts

Hi

I created a simplee program to add/remove entries from windows hosts file.

I did originally create the program to a hosting company, and was bound to there servers by using a dropdown - so the user couldn't add there own IP, but I have changed it so every one could use it.

I'm no AutoIT expert, but I hope that it might can be useful to some one :)

#RequireAdmin

#include <Array.au3>
#include <ButtonConstants.au3>
#include <ComboConstants.au3>
#include <GUIComboBox.au3>
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <ListViewConstants.au3>
#include <GUIListView.au3>
#include <GuiListView.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <File.au3>
#include <GuiIPAddress.au3>
Opt("GUIOnEventMode", 1)

; Setting standart vars
$HOSTSfile = @WindowsDir & "\System32\Drivers\etc\hosts" ; HOSTS file path
$TempHosts = @ScriptDir & "\hosts.tmp"
$bUpdateHOSTS = False ; Default if False no update will be made to HOSTS file

#Region ### START Koda GUI section ### Form=F:\AutoIT3 Scripts\GUI Forms\idHostsGUI.kxf
$idHostsGUI = GUICreate("HOSTS Configurato", 398, 272, -1, -1, BitOR($WS_SYSMENU,$WS_CAPTION,$WS_POPUPWINDOW,$WS_BORDER))
GUISetBkColor(0xFFFFFF) ; Set gui background to white
GUISetOnEvent($GUI_EVENT_CLOSE, "idhostGUIClose")
$Label1 = GUICtrlCreateLabel("IPaddress", 8, 16, 109, 20)
GUICtrlSetFont($Label1, 10, 800, 0, "MS Sans Serif")
;$idDropdown = GUICtrlCreateCombo("", 8, 40, 129, 25, BitOR($CBS_DROPDOWNLIST,$CBS_AUTOHSCROLL))
$idIPAddress = _GUICtrlIpAddress_Create($idhostsGUI, 8, 40, 130, 21)
_GUICtrlIpAddress_Set($idIPAddress, "0.0.0.0")
;_GUICtrlIpAddress_ShowHide($idIPAddress, @SW_HIDE)
$Label2 = GUICtrlCreateLabel("Domain", 144, 16, 67, 20)
GUICtrlSetFont($Label2, 10, 800, 0, "MS Sans Serif")
$idInputDomain = GUICtrlCreateInput("", 144, 40, 180, 21, BitOR($GUI_SS_DEFAULT_INPUT,$ES_LOWERCASE,$ES_OEMCONVERT))
$idButtonAdd = GUICtrlCreateButton("Add", 330, 40, 55, 21, $BS_DEFPUSHBUTTON)
GUICtrlSetOnEvent($idButtonAdd, "idButtonAddClick")
$Label3 = GUICtrlCreateLabel("Indhold af HOSTS", 8, 80, 150, 20)
GUICtrlSetFont($Label3, 10, 800, 0, "MS Sans Serif")
$idListViewHosts = GUICtrlCreateListView("Ipaddress|Domain", 8, 104, 378, 158, BitOR($GUI_SS_DEFAULT_LISTVIEW,$LVS_NOLABELWRAP,$WS_VSCROLL), BitOR($WS_EX_CLIENTEDGE,$LVS_EX_GRIDLINES,$LVS_EX_FULLROWSELECT,$LVS_EX_FLATSB))
GUICtrlSendMsg($idListViewHosts, $LVM_SETCOLUMNWIDTH, 0, 100)
GUICtrlSendMsg($idListViewHosts, $LVM_SETCOLUMNWIDTH, 1, 250)
$idButtonRemove = GUICtrlCreateButton("Remove Chosen", 302, 80, 85, 20)
GUICtrlSetOnEvent($idButtonRemove, "idButtonRemoveClick")
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###


_Onload() ; On program startup we call the Onload function

While 1
    Sleep(100)
WEnd

Func idButtonAddClick() ; When user clicks the Add button
; Reading the ip entry
$sGetIP =  _GUICtrlIpAddress_Get($idIPAddress)
; Reading the Input entry
$ReadInput = GUICtrlRead($idInputDomain)
; performing checks
If $sGetIP = "0.0.0.0" then ; User did't choose a server from the dropdown
; We show a msgbox informing the user that they did't chose a server
MsgBox(266256,"IPAddress","You havn't typed any IP!" & @CRLF & "Please type an IPaddress")
Return ; returning to main screen
ElseIf $ReadInput = "" Then ; User did't typed a domain name
; We show a msgbox informing the user that the input is empty
MsgBox(266256,"Domain","You havn't typed any Domain!" & @CRLF & @CRLF & "Please type the Domain that should" & @CRLF & "de added to the HOSTS file.")
Return ; Returning to main screen
ElseIf $ReadInput <> "" Then ; The user typed something in the Input
    _ValidateDomain($sGetIP, $ReadInput) ; We calls the validate function

GUICtrlSetData($idInputDomain, "") ; Clearing Input entrys
;_UpdateCombo() ; reloads the Combo
_GUICtrlIpAddress_Set($idIPAddress, "0.0.0.0")
GUICtrlSetState($idIPAddress, $GUI_Focus)
EndIf



EndFunc
Func idButtonRemoveClick() ; When user clicks remove item
Local $aTempHOSTS

$sItemSelected = _GUICtrlListView_GetItemTextString($idListViewHosts, -1) ; Getting text from the selected item
$sSearchString = StringReplace($sItemSelected, "|", " ") ; Recreating original string format, by replacing the | with a "space"
If Not IsDeclared("iMsgBoxAnswer") Then Local $iMsgBoxAnswer
$iMsgBoxAnswer = MsgBox(266276,"Remove Chosen",'This will remove "' & $sSearchString & '"' & @CRLF & "from your HOSTS file, contenuine?")
Select
    Case $iMsgBoxAnswer = 6 ;Yes
 _GUICtrlListView_DeleteItemsSelected(GUICtrlGetHandle($idListViewHosts)) ; removing the selected item from listview
; Removing the selected from the hosts file
 _FileReadToArray($TempHosts, $aTempHOSTS) ; reading temp hostfile into an array
 $sIndex = _ArraySearch($aTempHOSTS, $sSearchString) ; Searching Array for the selected string, to get the index
 _ArrayDelete($aTempHOSTS, $sIndex) ; removing the selected item from array
 _FileWriteFromArray($TempHosts, $aTempHOSTS, 1) ; Rewrites the TempHOSTS file, now with out the seleced item.

 $bUpdateHOSTS = True

    Case $iMsgBoxAnswer = 7 ;No - The user clicked No
Return ; Returning without doing anything
EndSelect

EndFunc

Func idhostGUIClose()
If $bUpdateHOSTS = True Then ; If a change has been made - we updates the system HOSTS file
    _UpdateHosts() ; Doing an update on the hostfile
EndIf
; Removing temphosts
FileDelete($TempHosts)
if @error Then MsgBox(4112,"Error cleaning up","Couldn't delete the" & @CRLF & "tempory HOSTS file")
Exit ; Close
EndFunc

Func _Onload()
; At program start up we open the config ini file, to read the server entries.
; these entries do we load into the dropbox, allowing the user to choose from 'em.
; We also reads the section Added, to check if the program has been used to add any
; domains to the hosts file.
; also we opens the HOSTS file for reading, checking against the entries in the program
; config file to see if any of the entries from the host file is added by this program
; We copy's the original hosts file to the program dir as at temp file called hosts.meebox
; But first we needs to check if the program has admin rights
If IsAdmin() Then
    ;call a function
Else
    MsgBox (64,"Administrator","You need admin rights to use this function!.")
    Exit ;or what ever
EndIf

Local $aHosts
_FileReadToArray($HOSTSfile, $aHosts)
_FileWriteFromArray($TempHosts, $aHosts, 1)


; Reading HOSTS file and Adding the read entries to the ListView
$sString = FileRead($HOSTSfile) ; Reading HOSTS file into a var
$sString = StringRegExpReplace($sString, '#.*\s', '') ; Removing comments from input
$asReadFromHosts = StringRegExp($sString, '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]{1,3}[[:space:]]*[\w\.\-/æøåÆØÅ]*',3); Looking for patterns like 123.123.123.123 domain.com or 123.123.123.123 www.domain.com

For $i = 0 To UBound($asReadFromHosts) - 1
If @OSVersion = "WIN_XP" And StringInStr($asReadFromHosts[$i], "127.0.0.1       localhost") Then ; Standart loacal host entry in xp contains alot of spaces
$aIpDomainSplit = StringSplit($asReadFromHosts[$i], '       ', 1) ; Splitting xxx.xxx.xxx.xxx www.domain.com into seperate strings like "string1 = xxx.xxx.xxx.xxx" & "string2 = www.domain.com"
Else
$aIpDomainSplit = StringSplit($asReadFromHosts[$i], ' ') ; Splitting xxx.xxx.xxx.xxx www.domain.com into seperate strings like "string1 = xxx.xxx.xxx.xxx" & "string2 = www.domain.com"
EndIf
$sItemCountListView = _GUICtrlListView_GetItemCount($idListViewHosts)
GUICtrlCreateListViewItem($aIpDomainSplit[1]&"|"& $aIpDomainSplit[2], $idListViewHosts) ; Adding info to listview (IP adress of server)
    Next

EndFunc

Func _ValidateDomain($sIP, $sDomain)
; First we checks for illegal chars
    $sCheckChar = StringRegExp($sDomain, "[^0-9|a-z||æ|ø|å|\.|\-|]", 0)
    If $sCheckChar = 1 Then
; Warn user about illegal chars
MsgBox(4112,"Illegal chars","A Domain name can only contain" & @CRLF & 'Numbers 0-9, Letters a-z and "-"')
Return ; Returning to main screen
Else
$sGetIP =  _GUICtrlIpAddress_Get($idIPAddress)
; Writing the read info to the temp hostfile we created in programdir
$CountLines = _FileCountLines($TempHosts)
    _FileWriteToLine($TempHosts, $CountLines+1, $sIP & " " & $sDomain)
$sItemCountListView = _GUICtrlListView_GetItemCount($idListViewHosts) ; Getting Index of items in listview
GUICtrlCreateListViewItem($sIP & "|" & $sDomain, $idListViewHosts) ; Adding info to listview (IP adress of server)
$bUpdateHOSTS = True
EndIf
EndFunc

Func _UpdateHosts()
FileCopy($HOSTSfile, $HOSTSfile & ".bak", 1) ; Making a backup of the original HOSTS file, just in chase
If @error Then MsgBox(4112,"Backup Error","Could't create a backup of the HOSTS file")
FileCopy($TempHosts, $HOSTSfile, 1) ; Copying our tempery HOSTS file with overwrite option.
If @error Then MsgBox(4112,"Write Error","Could't write to HOSTS file")
EndFunc

Cheers

c;") /Rex

:Edit Bad typing

Edited by Rex
Link to comment
Share on other sites

A good start, but like anything there is always room for improvement. For example a couple of points I can see.

1. It presumes a HOSTS file is IPADDRESS URL, whereas it can also be IPADDRESS URL URL URL (3 urls on a single line.)

2. The class [^0-9|a-z||æ|ø|å|.|-|] is incorrect, as it's not OR in the class. Are you looking for characters that aren't w and .?

3. You could use a regular expression to 'delete' the URL from the HOSTS file and thus wouldn't need the use of reading to array, searching and writing back.

For someome who claims not to be an expert, it's a decent start at least. Well done.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Moderators

Rex,

 

The program is originally created to a hosting company, and was bound to there servers by using a dropdown - so the user couldn't add there own IP, but I have changed it so every one could use it

Is this copyright material that you have posted? :huh:

M23

Edited by Melba23
Modified the question

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Rex,

 

Is this copyright material that you have hacked? And if so, how did you hack it? Decompiled the original by any chance? :huh:

M23

Nope I did it my self, well I had a little help with from Guinness and jchd the regex '?do=embed' frameborder='0' data-embedContent>>

Other then that, the work is all my own. I might should had written "I original created the program to a hosting company"

Cheers

c;") /Rex

Link to comment
Share on other sites

A good start, but like anything there is always room for improvement. For example a couple of points I can see.

1. It presumes a HOSTS file is IPADDRESS URL, whereas it can also be IPADDRESS URL URL URL (3 urls on a single line.)

2. The class [^0-9|a-z||æ|ø|å|.|-|] is incorrect, as it's not OR in the class. Are you looking for characters that aren't w and .?

3. You could use a regular expression to 'delete' the URL from the HOSTS file and thus wouldn't need the use of reading to array, searching and writing back.

For someome who claims not to be an expert, it's a decent start at least. Well done.

Thx for replying

1. Yes it does, I didn't know that one could had more then one url at the line - I may have to update my script to take that in counter :)

2. Hmm funny thing is works, if I type # or & or other like that - it throws the warning ?

3. Yes, but my regex isn't that good yet - I couldn't even get it to only grap an full string eg. xxx.xxx.xxx.xxx url - it kept grap the IP's in the comments also :(

Thx for that, nice to know that I'm not that much off :P

Cheers

c;") /Rex

Link to comment
Share on other sites

  • Moderators

Rex,

Thanks for clearing that up. :thumbsup:

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Great.

  1. Just search the Internet for 'optimise HOSTS file' and you will see a lots of information about optimising the HOSTS file. I use it for malicious sites and normally have 9 per line.
  2. It might work, but it's still incorrectly written. What should it accept? As I will re-write it for you.
  3. Just remove the comments first and then parse the HOSTS file.

 

My gift for you is this...it's what I use to strip the comments. StringRegExpReplace()

(?:#[^\r\n]*)

and this is what I use to remove the address at the start of a line. StringRegExpReplace()

(?m:^\s*\S+\s*)
Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

That regular expression can be whittled down to...as per the MsgBox description.

ConsoleWrite('# This contains non-word chars. >> ' & _IsNotValidWord('# This contains non-word chars.') & @CRLF)
ConsoleWrite('google >> ' & _IsNotValidWord('google') & @CRLF)

; A Domain name can only contain numbers 0-9, Letters A-Z and '-'. (What about . or /?)
Func _IsNotValidWord($sString) ; By guinness 2013.
    Return StringRegExp($sString, '\W') = 1 ; Returns True if the string contains characters which are not 0-9a-zA-Z_.
EndFunc   ;==>_IsNotValidWord

but you might have meant this...

ConsoleWrite('google#.com >> ' & _IsNotValidWord('google#.com') & @CRLF)
ConsoleWrite('google.com >> ' & _IsNotValidWord('google.com') & @CRLF)

; A Domain name can only contain numbers 0-9, Letters A-Z and '-'. (What about . or /?)
Func _IsNotValidWord($sString) ; By guinness 2013.
    Return StringRegExp($sString, '[^\w.\-/]') = 1 ; Returns True if the string contains characters which are not 0-9a-zA-Z_-./.
EndFunc   ;==>_IsNotValidWord

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

 

Great.

  1. Just search the Internet for 'optimise HOSTS file' and you will see a lots of information about optimising the HOSTS file. I use it for malicious sites and normally have 9 per line.
  2. It might work, but it's still incorrectly written. What should it accept? As I will re-write it for you.
  3. Just remove the comments first and then parse the HOSTS file.

 

My gift for you is this...it's what I use to strip the comments. StringRegExpReplace()

(?:#[^\r\n]*)

and this is what I use to remove the address at the start of a line. StringRegExpReplace()

(?m:^\s*\S+\s*)

Hi thx for replying

1. Ill do that :).  Up to 9 hosts pr line :o thats alot ;) - Though I did write it to a hosting company - allowing there customers to add there domain to the host file so they could access it before the dns was updated, and for that a single line was ok.

But for the ones I have posted her I might could update it to read/write up till the 9 lines, but I think that to do that I really need to get a better understanding of regex.

2. I look for chars not in class and reacts if a match is found. but as if I understand you correct the correct code should be ([^0-9][a-z][æøå][.-])

3. Do you mean this

Local $aHosts
_FileReadToArray($HOSTSfile, $aHosts)
_FileWriteFromArray($TempHosts, $aHosts, 1)

should be done after I removed the comments?

Thx for the gifts :huggles: I will update my script to use the one for comments :)

Cheers

c;") /Rex

Link to comment
Share on other sites

 

That regular expression can be whittled down to...as per the MsgBox description.

ConsoleWrite('# This contains non-word chars. >> ' & _IsNotValidWord('# This contains non-word chars.') & @CRLF)
ConsoleWrite('google >> ' & _IsNotValidWord('google') & @CRLF)

; A Domain name can only contain numbers 0-9, Letters A-Z and '-'. (What about . or /?)
Func _IsNotValidWord($sString) ; By guinness 2013.
    Return StringRegExp($sString, '\W') = 1 ; Returns True if the string contains characters which are not 0-9a-zA-Z_.
EndFunc   ;==>_IsNotValidWord

but you might have meant this...

ConsoleWrite('google#.com >> ' & _IsNotValidWord('google#.com') & @CRLF)
ConsoleWrite('google.com >> ' & _IsNotValidWord('google.com') & @CRLF)

; A Domain name can only contain numbers 0-9, Letters A-Z and '-'. (What about . or /?)
Func _IsNotValidWord($sString) ; By guinness 2013.
    Return StringRegExp($sString, '[^\w.\-/]') = 1 ; Returns True if the string contains characters which are not 0-9a-zA-Z_-./.
EndFunc   ;==>_IsNotValidWord

Wow I can see that I still have a lot to learn about correct coding

thx for helping me, I really appreciate that - if some day we meet ill buy you a big beer :)

Cheers

c;") /Rex

Link to comment
Share on other sites

This class [^0-9][a-z][æøå][.-] should be [^0-9A-Za-zæøå.-] but the function I provided should meet your requirements.

To parse a HOSTS file with 9 domains per line is easy. Read the file, strip comments and then parse using the regular expression from the forum post of mine (the one that I linked to in your help topic.)

Edited by guinness

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

This class [^0-9][a-z][æøå][.-] should be [^0-9A-Za-zæøå.-] but the function I provided should meet your requirements.

To parse a HOSTS file with 9 domains per line is easy. Read the file, strip comments and then parse using the regular expression from the forum post of mine (the one that I linked to in your help topic.)

Ahh thx, as I Said  I need to learn the regex better :>

I read the post you linked to, but as I understand it you removes the Ip 2 - and I want to keep the Ip so it also can be added to the listview.

Cheers

c;") /Rex

Link to comment
Share on other sites

Ah, true. That regular expression is a little more complex then, perhaps above my pay grade.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...