我想使用将从 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") ```
通过在脚本开头添加 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}"
这些方法将帮助您克服权限访问问题。