You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows任务计划执行脚本修改hosts文件遇[Errno 13]权限拒绝

问题:Windows任务计划程序运行脚本修改hosts文件时权限拒绝

我希望通过Windows任务计划程序运行脚本修改hosts文件,但即使设置了提升权限,仍提示权限拒绝错误([Errno 13]:Permission Denied)。PowerShell(.ps1)、Python(.py)和批处理(.bat)脚本均出现此问题。

但直接以管理员身份在PowerShell ISE中运行ps1脚本、在PyCharm Debug模式下运行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脚本打包为可执行文件,仍提示权限拒绝
  • 任务计划中已设置以高权限运行
  • 已禁用Windows UAC

内容的提问来源于stack exchange,提问作者Desenvolvimento spr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:48:25