[Errno 13]:尝试用.ps1、.py和.bat脚本编辑hosts文件时权限被拒绝,hosts文件已授予完全编辑权限

1 投票
1 回答
56 浏览
提问于 2025-04-14 16:51

我想用一个脚本来编辑 hosts 文件,这个脚本会通过 Windows 任务调度器运行。但是即使我给这个脚本提升了权限,当它尝试编辑 hosts 文件时,还是会出现访问被拒绝的错误 ([Errno 13]:Permission Denied)


我用 PowerShell(ps1)、Python(py)和 .bat 脚本都试过,结果都是访问被拒绝。

不过,当我以管理员身份在 PowerShell ISE 里运行 ps1 脚本时,它可以成功编辑 hosts 文件。而当我在 Pycharm 的调试模式下运行 Python 脚本时,它也能编辑 hosts 文件。

POWERSHELL:
$bloqueado = $false

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted -Force
Write-Host (Get-ExecutionPolicy)

$caminhoHosts = "$env:SystemRoot\System32\drivers\etc\hosts"
Add-Content -Path $caminhoHosts -Value "teste"

while ($true) {
    # Get a list of active RDP sessions
    $rdpSessions = quser | Where-Object { $_ -match 'rdp' }

    if ($rdpSessions) {
        if (-not $bloqueado) {
            Write-Host "VPN LIGADA"

            $textoAdicional1 = "127.0.0.1    x."
            $textoAdicional3 = "127.0.0.1    xx"
            $textoAdicional5 = "127.0.0.1    xxx"
            $textoAdicional6 = "127.0.0.1    xxxx"

            Add-Content -Path $caminhoHosts -Value "$textoAdicional1`r`n$textoAdicional3`r`n$textoAdicional5`r`n$textoAdicional6"

            $nomesNavegadores = @("chrome", "firefox", "iexplore", "msedge", "opera")
            foreach ($nome in $nomesNavegadores) {
                Stop-Process -Name $nome -Force -ErrorAction SilentlyContinue
            }

            $bloqueado = $true
        }
    }

    else {
        Write-Host "VPN DESLIGADA"

        if ($bloqueado) {
            $linhas = Get-Content -Path $caminhoHosts

            foreach ($indiceLinha in 0..($linhas.Count - 1)) {
                $linha = $linhas[$indiceLinha]
                if ($linha -match "x|x|x") {
                    $linhas = $linhas | Where-Object { $_ -ne $linha }
                }
                elseif($linha -match "x|x|x"){
                    $linhas = $linhas | Where-Object { $_ -ne $linha }
                }
            }

            $linhas | Set-Content -Path $caminhoHosts

            $bloqueado = $false
        }
    }

    Start-Sleep -Seconds 5
}```


Python:

hosts_path = r"C:\Windows\System32\drivers\etc\hosts"

with open(hosts_path, "a") as hosts_file:
    hosts_file.write(f"\n127.0.0.1 eae.com") ```
  • 我已经更改了 hosts 文件的权限,所以现在应该没有问题了。
  • 我也把 PowerShell 的执行策略改成了 "Unrestricted" 和 "Bypass",但还是没成功。
  • 我已经用 PowerShell 和 Python 脚本创建了一个可执行文件,但它也显示访问 hosts 被拒绝。
  • 在任务调度器里,这个任务是设置为以更高权限运行的。
  • 我也禁用了 Windows 的用户账户控制(UAC)。

1 个回答

-1

在脚本的开头加上 Set-ExecutionPolicy Bypass -Scope Process -Force 这行命令,可以暂时改变 PowerShell 的执行权限设置。

把你的脚本用一个 PowerShell 命令包裹起来,这样就可以以管理员身份运行:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process 
PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File 
\"your_script_path.ps1\"' -Verb RunAs}"

这些方法可以帮助你解决权限访问的问题。

撰写回答