Rex Posted June 2, 2013 Share Posted June 2, 2013 (edited) 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 expandcollapse popup#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 June 2, 2013 by Rex mesale0077 1 Link to comment Share on other sites More sharing options...
guinness Posted June 2, 2013 Share Posted June 2, 2013 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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
Moderators Melba23 Posted June 2, 2013 Moderators Share Posted June 2, 2013 (edited) 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 itIs this copyright material that you have posted? M23 Edited June 2, 2013 by Melba23 Modified the question 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 columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area Link to comment Share on other sites More sharing options...
Rex Posted June 2, 2013 Author Share Posted June 2, 2013 Rex, Is this copyright material that you have hacked? And if so, how did you hack it? Decompiled the original by any chance? 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 More sharing options...
Rex Posted June 2, 2013 Author Share Posted June 2, 2013 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 Cheers c;") /Rex Link to comment Share on other sites More sharing options...
Moderators Melba23 Posted June 2, 2013 Moderators Share Posted June 2, 2013 Rex,Thanks for clearing that up. M23 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 columnsChooseFileFolder ---- Single and multiple selections from specified path treeview listingDate_Time_Convert -- Easily convert date/time formats, including the language usedExtMsgBox --------- A highly customisable replacement for MsgBoxGUIExtender -------- Extend and retract multiple sections within a GUIGUIFrame ---------- Subdivide GUIs into many adjustable framesGUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView itemsGUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeViewMarquee ----------- Scrolling tickertape GUIsNoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxesNotify ------------- Small notifications on the edge of the displayScrollbars ----------Automatically sized scrollbars with a single commandStringSize ---------- Automatically size controls to fit textToast -------------- Small GUIs which pop out of the notification area Link to comment Share on other sites More sharing options...
guinness Posted June 2, 2013 Share Posted June 2, 2013 (edited) Great. 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. It might work, but it's still incorrectly written. What should it accept? As I will re-write it for you. 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 June 2, 2013 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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
guinness Posted June 2, 2013 Share Posted June 2, 2013 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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
Rex Posted June 3, 2013 Author Share Posted June 3, 2013 Great. 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. It might work, but it's still incorrectly written. What should it accept? As I will re-write it for you. 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 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 I will update my script to use the one for comments Cheers c;") /Rex Link to comment Share on other sites More sharing options...
Rex Posted June 3, 2013 Author Share Posted June 3, 2013 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 More sharing options...
guinness Posted June 3, 2013 Share Posted June 3, 2013 (edited) 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 June 3, 2013 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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
Rex Posted June 3, 2013 Author Share Posted June 3, 2013 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 More sharing options...
guinness Posted June 3, 2013 Share Posted June 3, 2013 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 parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018 Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now