[Errno 13]:尝试使用 .ps1、.py 和 .bat 中的脚本编辑主机文件时权限被拒绝。拥有完全编辑权限的 Hosts 文件

问题描述 投票:0回答:1

我想使用将从 Windows 任务计划程序运行的脚本编辑主机文件,但即使向该脚本授予提升的权限,当它尝试编辑主机文件时,访问也会被拒绝

([Errno 13]:Permission Denied)
。 我在 PowerShell (ps1)、Python (py) 和 .bat 脚本中创建了一个脚本,它们都拒绝访问。


但是当我以管理员身份在 PowerShell ISE 中运行 ps1 脚本时,它可以编辑主机文件。当我在 Pycharm 中以 Debug 模式运行 python 脚本时,它可以编辑主机文件。

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") ```
  • 我已经更改了主机文件的权限,所以现在一切都清楚了。
  • 我已经将PowerShell执行策略编辑为“无限制”和“绕过”,但也没有成功。
  • 我已经使用 PowerShell 和 Python 脚本创建了一个可执行文件,但它也允许访问被拒绝的主机。
  • 在任务调度程序中,任务是以更高的权限运行。
  • 我也禁用了 Windows UAC。
python windows powershell hosts hosts-file
1个回答
0
投票

通过在脚本开头添加 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}"

这些方法将帮助您克服权限访问问题。

© www.soinside.com 2019 - 2024. All rights reserved.