0

I want to know whether my host file has access to EDIT or not using errorcode but i am always getting error code as 0..Please help me out in getting the code to check for a admin access for a particular specified file

I am using below code, but not working

@echo off
setlocal enabledelayedexpansion enableextensions

attrib -s -h -r %systemroot%\system32\drivers\etc\hosts

echo %errorlevel%
echo.

IF %errorlevel% NEQ 0 (
    echo.
    echo Do not have access..
    pause >nul
    exit
) else (
    echo Has Access..
    pause >nul
)
Squashman
  • 13,649
  • 5
  • 27
  • 36
Shiv
  • 101
  • 3
  • 15
  • Do you really need to check it on a particular file or do you just want to see if you are [running as admin](https://stackoverflow.com/questions/4051883/batch-script-how-to-check-for-admin-rights#11995662) – Squashman Nov 17 '17 at 19:50
  • `ATTRIB` does not set the `ERRORLEVEL` if it cannot change the file attributes but the system does output an error message: **Access denied - C:\Windows\System32\drivers\etc\hosts**. So just pipe the output from the `ATTRIB` command to the `FIND` command to search for Access Denied, which will then set the errorlevel to 0 if it finds Access Denied and 1 if it does not find Access Denied. – Squashman Nov 17 '17 at 19:54
  • Squashman i am very new to batch script could you please write it for me whatever you told in your latest comment.. Thank you – Shiv Nov 17 '17 at 20:10
  • If you don't know your files attributes why are you changing them before you have checked? Also there should be no need to change its hidden and system attributes if you're only intending to write to it. – Compo Nov 17 '17 at 21:50
  • Could you please advise me how to do that without changing the attributes by writing the small code. – Shiv Nov 18 '17 at 00:46
  • Ignoring your script issues, what exactly are you trying to accomplish? Have you read [Ask], yet? – jwdonahue Nov 18 '17 at 04:08

1 Answers1

0

You need to check the file permission,there are many ways to achieve this one by reading the file and another getting file permission using cacls command.. *(for example)

@echo off
SETLOCAL EnableDelayedExpansion

findstr /c:"any string" %systemroot%\system32\drivers\etc\hosts

echo %errorlevel%
echo.

if errorlevel 1 (
echo.
echo File Required Administrator Access
pause >nul
exit
) else (
echo Administrator Access ..
pause >nul
)
Gourav
  • 116
  • 1
  • 6