Reputation: 11
I want to edit the hosts file with a script that will run from the Windows Task Scheduler, but even granting elevated permissions to this script, when it tries to edit the hosts file, access is denied ([Errno 13]:Permission Denied)
.
I created a script in PowerShell (ps1), in Python (py) and a .bat script and they all give access denied.
But when I run the ps1 script in PowerShell ISE as administrator it can edit the hosts file. When I run the python script in Pycharm in Debug mode it can edit the hosts file.
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") ```
Upvotes: 1
Views: 171