26

I am looking to write a script that takes user input, then makes system wide changes. I need this to be very generic, but simply put, at the top, I need it to check to see if it's being run 'As an Administrator'. If it's not, then I want to display a message to tell them that; if it is, I want it to continue on. Is there a constant way to verify this? I am not looking to start a new session as the Administrator, I just want to detect if it's currently run as admin

3

5 Answers 5

21

Found this on Stack Overflow:

@echo off
goto check_Permissions

:check_Permissions
echo Administrative permissions required. Detecting permissions...

net session >nul 2>&1
if %errorLevel% == 0 (
    echo Success: Administrative permissions confirmed.
) else (
    echo Failure: Current permissions inadequate.
)

pause >nul
5
  • What was the reason it was deleted? Oct 31, 2013 at 10:50
  • This works, both from the Administrator account, and when I run as a limited user, but choose 'Run as Administrator' Oct 31, 2013 at 16:36
  • 2
    Same idea, but using conditional execution operators: net session >nul 2>&1 && echo Success || echo Failure. I find this compact syntax more convenient.
    – dbenham
    Oct 31, 2013 at 17:20
  • 9
    This requires the "Server" service to be running. Dec 5, 2016 at 8:01
  • 1
    @ivan_pozdeev You were right. Jan 7, 2021 at 12:53
12

This checks for high integrity level. (works for Windows Vista and higher)

@echo off

whoami /groups | find "S-1-16-12288" > nul

if %errorlevel% == 0 (
 echo Welcome, Admin
) else (
 echo Get lost, User
)
6
  • 1
    whoami isn't supported in xp my awnser is better supports all os from windows xp to windows 8
    – Alex
    Oct 31, 2013 at 9:40
  • 2
    This works if I just open the Command Prompt. If I run the CMD As Administrator, it still shows that it's run as a user though Oct 31, 2013 at 16:36
  • 2
    @Alex Support for more OS's is great, but this method is more reliable as it directly queries the permissions given to the current session instead of taking absence of a less-reliable negative to infer a positive.
    – Iszi
    Sep 10, 2014 at 18:33
  • 2
    week, whoami /groups has an edge case where you get the wrong information. See stackoverflow.com/questions/4051883/… Jun 18, 2015 at 17:27
  • 1
    @week whoami is missing on XP. Dec 5, 2016 at 8:03
5

Many, many answers to this and multiple other questions across SE (1,2,3 to name a few), all of which are deficient in this way or another, have clearly shown that Windows doesn't provide a reliable built-in utility. So, it's time to roll out your own.

Without any further dirty hacks:

Compile the following program (instructions follow), or get a precompiled copy. This only needs to be done once, then you can copy the .exe everywhere (e.g. alongside the Sysinternals Suite).

The code works in Win2k+1, both with and without UAC, domain, transitive groups, whatever - because it uses the same way as the system itself when it's checking permissions. chkadmin prints "Admin" or "Non-admin" and sets the exit code to 0 or 1, respectively. The output can be suppressed with the /q switch.

chkadmin.c:

#include <malloc.h>
#include <stdio.h>
#include <windows.h>
#pragma comment (lib,"Advapi32.lib")

int main(int argc, char** argv) {
    BOOL quiet = FALSE;
    DWORD cbSid = SECURITY_MAX_SID_SIZE;
    PSID pSid = _alloca(cbSid);
    BOOL isAdmin;

    if (argc > 1) {
        if (!strcmp(argv[1],"/q")) quiet=TRUE;
        else if (!strcmp(argv[1],"/?")) {fprintf(stderr,"Usage: %s [/q]\n",argv[0]);return 0;}
    }

    if (!CreateWellKnownSid(WinBuiltinAdministratorsSid,NULL,pSid,&cbSid)) {
        fprintf(stderr,"CreateWellKnownSid: error %d\n",GetLastError());exit(-1);}

    if (!CheckTokenMembership(NULL,pSid,&isAdmin)) {
        fprintf(stderr,"CheckTokenMembership: error %d\n",GetLastError());exit(-1);}

    if (!quiet) puts(isAdmin ? "Admin" : "Non-admin");
    return !isAdmin;
}

To compile, run in Windows SDK command prompt:

cl /Ox chkadmin.c

(if using VS2012+, more adjustments are needed if you need to target 2k/XP)


The method is courtesy of https://stackoverflow.com/questions/4230602/detect-if-program-is-running-with-full-administrator-rights/4230908#4230908

1MSDN claims the APIs are XP+ but this is false. CheckTokenMembership is 2k+ and the other one is even older.

4

The cleanest way to check for admin privileges using a CMD script, that I have found, is something like this:

@echo off

REM  Calling verify with no args just checks the verify flag,
REM   we use this for its side effect of setting errorlevel to zero
verify >nul

REM  Attempt to read a particular system directory - the DIR
REM   command will fail with a nonzero errorlevel if the directory is
REM   unreadable by the current process.  The DACL on the
REM   c:\windows\system32\config\systemprofile directory, by default,
REM   only permits SYSTEM and Administrators.
dir %windir%\system32\config\systemprofile >nul 2>nul

REM  Use IF ERRORLEVEL or %errorlevel% to check the result
if not errorlevel 1 echo has Admin privs
if     errorlevel 1 echo has only User privs

This method only uses CMD.exe builtins, so it should be very fast. It also checks for the actual capabilities of the process rather than checking for SIDs or group memberships, so the effective permission is tested. And this works as far back as Windows 2003 and XP. Normal user processes or nonelevated processes fail the directory probe, where as Admin or elevated processes succeed.

This test fails if the Everyone, BUILTIN\Users, or other similar group is given read permission to systemprofile. Granted, that's a non-standard configuration other than on machines configured as Windows domain controllers which give 'NT AUTHORITY\Authenticated Users' read/execute rights to systemprofile.

4
  • >verify VERIFY is off. >verify /? Tells cmd.exe whether to verify that your files are written correctly to a disk. VERIFY [ON | OFF] Type VERIFY without a parameter to display the current VERIFY setting. How does this command help the script? Sep 7, 2016 at 19:23
  • 3
    @Canadian Luke, Some built-in commands commands do not clear errorlevel if there is no error. Thus, people got into the habit of clearing errorlevel using hacks such as verify. I tend to use cd . (cd space dot) which sets errorlevel to 0, produces no output, and is also useful for creating a zero length file via cd . >somefile. That said, I tested 'dir' on Windows 2000, XP, Vista, 2003, 2008, 2012, 7, 8, and 10. For all of those 'dir' will clear errorlevel to 0 on success if it had been set before the 'dir'. Thus I'm not sure why william used 'verify' to first clear errorlevel. Dec 3, 2016 at 23:13
  • a half a liner [basically 3 terms so "if exist file ..."] is bestiest and most greatest in whole flat world world: if EXIST "%windir%\System32\Config\sam" echo / set / goto as x_admin=true you can use sam or system or any number of files or directory like systemprofile & also as far as setting/clearing errorlevel if you don't want even run an exe let alone access files use either (call ) or (call) (call )&& echo see: call+space clears !ERRORLEVEL! || echo missed me burp (call) && echo skipped me blah || echo see: call-space sets !ERRORLEVEL! Mar 10, 2021 at 11:53
  • Clean, effective, and well commented solution. Worked for me. Thank you!
    – Frank Wang
    Dec 30, 2021 at 17:38
2

DIR "%SystemRoot%\System32\Config..." fails if a luser abusing the "protected" Administrator account created during Setup opens this directory in Explorer and let it modify permissions.

Better use one of the following command sequences:

DATE %DATE% 2>NUL:
IF ERRORLEVEL 1 ECHO Unprivileged!

TIME %TIME% 2>NUL:
IF NOT ERRORLEVEL 1 ECHO Privileged!
2
  • That fails on, for example, NT4-style Samba domains, where the Change System Time privilege needs to be held by the Everyone group May 30, 2020 at 18:38
  • 1
    This introduces a discrepancy into the system time: it will go back by the amount of time that passed between getting and setting it. Moreover, it will eventually set the date to an incorrect value if run around midnight. Jan 7, 2021 at 13:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .