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
相关产品推荐
相关产品推荐

