在测试工作中要经常修改hosts来做为内外网切换的,正好公司就有用autoit写好的monkey工具,用在这基础上修改吧:</p><p>其实主要是修改hosts的特定字符串,字符串从ini文件中读取,下面放出方法吧</p><pre name="code" class="plain">#include <File.au3>Global $iniPathParm = @ScriptDir&'\config.ini'$testParm = IniRead($iniPathParm,'hostInfo','upKeyword','no')Global $inihostParm = @ScriptDir&'\host'_ReplaceStringInFile($inihostParm,"xx.xx.xx.xx cb.ksmobile.com","")$filename = $inihostParm$str = fileread($filename)$file = FileOpen($filename, 10)FileWrite($file, StringRegExpReplace($str, "\s+$", ""))FileClose($file)FileWriteLine($inihostParm,@CRLF&"设置外网")_ReplaceStringInFile($inihostParm,"设置外网","xx.xx.xx.xx www.baidu.com")
这里没有对文件的容错进行处理,开始先直接从config.ini文件用自己建立的方法去读的对应的字段
这里是读取的方法,其实也是autoit自带的方法:
Func ReadIniInfo($section, $keyword)
$uploadDir = IniRead($iniPathParm, $section, $keyword, "NotFound")
Return $uploadDir
EndFunc
读取完了存进字符串中,再对对应的处理,如果是设置外网,就删除对应的hosts地址,是设置内网就添加对应的hosts地址
下面放出写的比较完整的两个方法吧:
<span style="white-space:pre"> </span>Case $nMsg = $Button3 ;内网升级hosts 也做了一些处理
;------检查是不是有内网设置地址,如果存在,则删除,重新设置
If FileExists($hostsPath) = 0 Then
MsgBox(16,"Error","can't open hosts file")
EndIf
FileSetAttrib($hostsPath,"-RSAH")
_ReplaceStringInFile($hostsPath,$internalHostParm,"")
;清除空格
$str = FileRead($hostsPath)
$replaceFile = FileOpen($hostsPath,10)
FileWrite($replaceFile,StringRegExpReplace($str, "\s+$", ""))
FileClose($replaceFile)
;写入文件
FileWriteLine($hostsPath,@CRLF&"设置外网")
Local $reval = _ReplaceStringInFile($hostsPath,"设置外网",$internalHostParm)
If $reval > 0 Then
MsgBox(48,"Message","设置内网成功",2)
Else
MsgBox(16,"Error","设置失败,请重试!!",3000)
EndIf
内网还有一个就麻烦地方就是还要去检测对应的hosts是否存在,不存在才添加,存在了删除再添加(也可不用管)
这个是外网设置:
Case $nMsg = $Button4 ;外网升级hosts
;------检查是不是有内网设置地址,如果存在,则删除,重新设置
If FileExists($hostsPath) = 0 Then
MsgBox(16,"Error","can't open hosts file")
EndIf
FileSetAttrib($hostsPath,"-RSAH")
Local $reval = _ReplaceStringInFile($hostsPath,$internalHostParm,"")
If $reval > 0 Then
MsgBox(48,"Message","设置外网成功",2)
;~ Else
;~ MsgBox(16,"Error","设置失败,请重试!!",3000)
EndIf
外网的就简单了吧,初学就这样了,也就玩玩吧,有需要的还是要继续学习,有什么问题的可以提出
这个是config.ini文件
[hostInfo]
internalHost=xx.xx.xx.xx www.baidu.com