访问权限为hosts文件

时间:2016-08-20 11:28:49

标签: vb.net vbscript

当我在Visual Studio中运行我的程序时,它在没有管理员权限的情况下完美运行。但是当我使用.exe文件运行程序时发生错误 - 访问路径C:/Windows/System32/drivers/etc/host我尝试以管理员身份运行它,根本不起作用!

这是我的代码 -

Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("C:/Windows/System32/drivers/etc/hosts", True)
file.WriteLine("127.0.0.1 " + www.google.lk)
file.Close()

2 个答案:

答案 0 :(得分:0)

正如您所看到的,只有管理员可以写信给它。

 C:\Windows\system32>icacls "C:\Windows\System32\drivers\etc\hosts"

 C:\Windows\System32\drivers\etc\hosts NT AUTHORITY\SYSTEM:(I)(F)

                                       BUILTIN\Administrators:(I)(F)

                                       BUILTIN\Users:(I)(RX)

                                       APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)

 Successfully processed 1 files; Failed processing 0 files

答案 1 :(得分:0)

您是否安装了任何类型的反间谍程序?有些会阻止主机文件被修改。这个vbscript对我有用。删除只读属性,执行编辑并重新应用只读属性。因为它有一些重复的代码,所以应该修改它以使函数更“正确”。

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

Const ForReading =   1
Const ForWriting =   2
Const ForAppending = 8
Const ReadOnly =     1

strWinDir = WshShell.ExpandEnvironmentStrings("%windir%")
HostsFile = strWinDir & "\System32\drivers\etc\hosts"

Set objFile = objFSO.GetFile(HostsFile)
If objFile.Attributes AND ReadOnly Then
  objFile.Attributes = objFile.Attributes XOR ReadOnly
End If

Set objFile = objFSO.OpenTextFile(HostsFile, ForAppending)
objFile.WriteLine(vbNewLine & "127.0.0.1 www.google.lk")
objFile.Close

Set objFile = objFSO.GetFile(HostsFile)
If Not objFile.Attributes AND ReadOnly Then
  objFile.Attributes = objFile.Attributes XOR ReadOnly
End If

删除相同字符串的代码。

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

Const ForReading =   1
Const ForWriting =   2
Const ForAppending = 8
Const ReadOnly =     1

strWinDir = WshShell.ExpandEnvironmentStrings("%windir%")
HostsFile = strWinDir & "\System32\drivers\etc\hosts"

Set objFile = objFSO.GetFile(HostsFile)
If objFile.Attributes AND ReadOnly Then
  objFile.Attributes = objFile.Attributes XOR ReadOnly
End If

Set objFile = objFSO.OpenTextFile(HostsFile, ForReading)

Do Until objFile.AtEndOfStream
  strLine = objFile.ReadLine
    If InStr(strLine, "127.0.0.1 www.google.lk") = 0 Then
      strContents = strContents & strLine & vbCrLf
    End If
Loop
objFile.Close

Set objFile = objFSO.OpenTextFile(HostsFile, ForWriting)
objFile.Write strContents
objFile.Close

Set objFile = objFSO.GetFile(HostsFile)
If Not objFile.Attributes AND ReadOnly Then
  objFile.Attributes = objFile.Attributes XOR ReadOnly
End If