Batch script access denied even with admin privileges
Asked Answered
Y

2

6

I have a batch script in Windows7 to update the hosts file that fails. I am logged as a user with administrative rights.

Even if I run the script with the "Run as administrator" option I get Access denied. 0 files copied when executing this part of the script:

for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%

REM create changing part of hosts file...   
if exist %temp%\temp.txt del %temp%\temp.txt
echo %ip% myproxy >> %temp%\temp.txt  

REM check this...
set hostpath=C:\WINDOWS\system32\drivers\etc

REM add static part of hosts file
type "%hostpath%\hosts-static" >> %temp%\temp.txt

REM replace hosts file
copy /y %temp%\temp.txt "%hostpath%\hosts"

ipconfig /flushdns
netsh interface IP delete arpcache
pause

I also tried to create a shortcut and set the "Advanced -> Run as Administrator" option but no luck.

If I open a cmd shell as Administrator and then run the script from there everything works fine, but no way of running it directly double-clicking on the file (or its link). Any idea?


EDIT:

  • added the whole script.

  • I tried creating a shortcut for the following command to execute as Administrator

    C:\Windows\System32\cmd.exe /c script.bat

and it is also failing. From the same shortcut (without arguments) I can open a window where I can execute the batch correctly. I really cannot see why.

Ywis answered 28/6, 2017 at 9:59 Comment(3)
Working fine on my machine with Admin privileges. Got an Access is denied without it. I ran it by double clicking. Can you show the rest of the code?Duleba
Try restarting your system, seems like a process has an active lock on the fileExhortative
Try restarting your PC and if this doesn't work try giving your system more control or run the batch file with adminAntons
P
1

Obviously a late response, but just solved this issue with a very straightforward solution so I thought I'd share:

Using ICACLS you can modify access control lists (ACLs) to bypass access denied errors. Run the following command:

ICACLS C:\path\to\batch\file\directory\* /C

the parameter /C tells the batch file to bypass access denied errors. Cheers.

Paddock answered 12/7, 2019 at 13:59 Comment(0)
E
0

Try attrib -r -s -h -a "%hostpath%\hosts" before your copy command. If any file is attributed +r, +s, or +h, you'll get "Access is denied" if you try to overwrite it using copy.

Ectoenzyme answered 28/6, 2017 at 12:33 Comment(3)
I tried to add the line in the script but I still get the error.Ywis
@ValentinaDiGiacomo Could be virus scanner software preventing hosts from being overwritten? Try disabling your virus scanner / Internet security software, CryptoPrevent, etc? Also, try BatchGotAdmin to force admin elevation.Ectoenzyme
May be. Unfortunately it is the company's firewall and antivirsus, so I cannot change the settings.Ywis

© 2022 - 2024 — McMap. All rights reserved.