批处理脚本:如何检查管理权限

如何检查当前批处理脚本是否具有管理权限?

我知道如何使它调用自己与runas,但不知道如何检查管理权限。我所见过的唯一解决方案是粗糙的黑客工作或使用外部程序。好吧,其实我不在乎这是不是一份苦差事,只要它能在Windows XP或更新版本上运行就行。

237659 次浏览

下面尝试在Windows目录中创建一个文件。如果成功,它将移除它。

copy /b/y NUL %WINDIR%\06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 >NUL 2>&1
if errorlevel 1 goto:nonadmin
del %WINDIR%\06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 >NUL 2>&1
:admin
rem here you are administrator
goto:eof
:nonadmin
rem here you are not administrator
goto:eof

请注意,06CF2EB6-94E6-4a60-91D8-AB945AE8CF38是今天生成的GUID,假定它与现有文件名不太可能冲突。

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"&&(
echo admin...
)
whoami /groups | find "S-1-16-12288" > nul
if not errorlevel 1 (
echo ...  connected as admin
)

安德斯解决方案为我工作,但我不确定如何反转它得到相反的(当你不是一个管理员)。

这是我的解决方案。它有两种情况,一个IF和ELSE情况,和一些ascii艺术,以确保人们实际阅读它。:)

最小的版本

Rushyo在这里发布了这个解决方案:如何检测CMD是否以管理员身份运行/具有提升的权限?

NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator PRIVILEGES Detected!
) ELSE (
ECHO NOT AN ADMIN!
)

添加错误消息、暂停和退出的版本

@rem ----[ This code block detects if the script is being running with admin PRIVILEGES If it isn't it pauses and then quits]-------
echo OFF
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator PRIVILEGES Detected!
) ELSE (
echo ######## ########  ########   #######  ########
echo ##       ##     ## ##     ## ##     ## ##     ##
echo ##       ##     ## ##     ## ##     ## ##     ##
echo ######   ########  ########  ##     ## ########
echo ##       ##   ##   ##   ##   ##     ## ##   ##
echo ##       ##    ##  ##    ##  ##     ## ##    ##
echo ######## ##     ## ##     ##  #######  ##     ##
echo.
echo.
echo ####### ERROR: ADMINISTRATOR PRIVILEGES REQUIRED #########
echo This script must be run as administrator to work properly!
echo If you're seeing this after clicking on a start menu icon, then right click on the shortcut and select "Run As Administrator".
echo ##########################################################
echo.
PAUSE
EXIT /B 1
)
@echo ON

适用于WinXP -> Win8(包括32/64位版本)。

编辑:8/28/2012更新到支持Windows 8。@BenHooper在他的回答中指出了这一点。请给他的答案投票。

问题

blak3r / Rushyo的解决方案适用于除Windows 8之外的所有系统。在Windows 8上运行AT会得到:

The AT command has been deprecated. Please use schtasks.exe instead.


The request is not supported.

(见截图#1),返回%errorLevel% 1

 

研究

所以,我开始寻找其他需要更高权限的命令。rationallyparanoid.com有几个列表,所以我在当前Windows操作系统(XP和8)的两个相反的极端上运行每个命令,希望找到一个命令,当以标准权限运行时,将在两个操作系统上被拒绝访问。

最终,我找到了一个——NET SESSION。一个真正的,干净,通用的解决方案,不包括:

  • 在安全位置上创建数据或与数据交互
  • 分析FOR循环返回的数据
  • 搜索字符串“;管理员”;
  • 使用AT (Windows 8不兼容)或WHOAMI (Windows XP不兼容)。

每一个都有自己的安全性、可用性和可移植性问题。

 

测试

我已经独立确认,这适用于:

  • Windows XP, x86
  • Windows XP, x64
  • Windows Vista, x86
  • Windows Vista, x64
  • Windows 7, x86
  • Windows 7, x64
  • Windows 8, x86
  • Windows 8, x64
  • Windows 10 v1909, x64

(见截图#2)

 

实施/使用

所以,要使用这个解决方案,只需像这样做:

@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

 

解释

NET SESSION是用于管理服务器计算机连接。不带参数使用时,[它]显示与本地计算机的所有会话的信息。的标准命令

所以,这是我给出的实现的基本过程:

    <李> @echo off
    • 禁止显示命令
    <李> goto check_Permissions
    • 跳转到:check_Permissions代码块
    <李> net session >nul 2>&1
    • 运行命令
    • 隐藏命令的可视输出
      1. 将标准输出(数字句柄1 / STDOUT)流重定向到nul
      2. 将标准错误输出流(数字句柄2 / STDERR)重定向到与数字句柄1相同的目标
    <李> if %errorLevel% == 0
    • 如果退出码(%errorLevel%)的值 0,那么这意味着没有发生错误,因此,前面的命令运行了成功
    <李> else
    • 如果退出码(%errorLevel%)的值不是 0,那么这意味着发生错误,因此,前面的命令运行了但没有成功
  1. 括号之间的代码将根据满足的条件执行

 

截图

Windows 8 __ABC0 %errorLevel%:

< img src = " https://i.imgur.com/01irE.png " alt = " [imgur] " / >

 

NET SESSION在Windows XP x86 - Windows 8 x64:

< img src = " https://i.stack.imgur.com/cAAIj.png " alt = " [imgur] " / >

 

谢谢你,@Tilka,把你接受的答案改成了我的。:)

不仅检查,而且自动获得管理权限
也就是win7/8/8.1 ff的自动UAC。
:下面是一个非常酷的,还有一个特性:这个批处理代码片段不仅检查管理权限,而且自动获取它们!(和之前的测试,如果生活在UAC功能的操作系统上。)

有了这个技巧,你不需要更长的时间右击你的批处理文件“与管理权限”。如果你忘记了,从提升权限开始,UAC自动出现!此外,首先它是测试,如果操作系统需要/提供UAC,所以它表现正确,例如Win 2000/XP,直到Win 8.1测试。

@echo off
REM Quick test for Windows generation: UAC aware or not ; all OS before NT4 ignored for simplicity
SET NewOSWith_UAC=YES
VER | FINDSTR /IL "5." > NUL
IF %ERRORLEVEL% == 0 SET NewOSWith_UAC=NO
VER | FINDSTR /IL "4." > NUL
IF %ERRORLEVEL% == 0 SET NewOSWith_UAC=NO




REM Test if Admin
CALL NET SESSION >nul 2>&1
IF NOT %ERRORLEVEL% == 0 (


if /i "%NewOSWith_UAC%"=="YES" (
rem Start batch again with UAC
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
)


rem Program will now start again automatically with admin rights!
rem pause
goto :eof
)

该代码片段将一些好的批处理模式合并在一起,特别是(1)本Hooper在这个线程中的管理测试和(2)在BatchGotAdmin上读取的UAC激活,并由robvanderwoude在批处理站点上引用(respect)。(3)对于“VER | FINDSTR模式”的操作系统标识,我只是没有找到参考。)

(关于一些非常小的限制,当“NET SESSION”不工作时,如另一个答案所述-请随意插入另一个这些命令。对我来说,运行在Windows安全模式或特殊标准服务,这不是一个重要的用例-对一些管理员来说可能是。)

一些服务器禁用命令“net session”所需的服务。 这导致管理检查总是说你没有管理权限,而你可能有

我有两种检查特权访问的方法,这两种方法都非常可靠,而且几乎在每个windows版本上都非常可移植。

1. 方法

set guid=%random%%random%-%random%-%random%-%random%-%random%%random%%random%


mkdir %WINDIR%\%guid%>nul 2>&1
rmdir %WINDIR%\%guid%>nul 2>&1


IF %ERRORLEVEL%==0 (
ECHO PRIVILEGED!
) ELSE (
ECHO NOT PRIVILEGED!
)

这是最可靠的方法之一,因为它很简单,而且这个非常原始的命令的行为不太可能改变。这不是其他内置CLI工具的情况,比如网络会议,可以通过管理/网络策略禁用,或者像fsutils这样的命令改变Windows 10上的输出。

* 适用于XP和以后

2. 方法

REG ADD HKLM /F>nul 2>&1


IF %ERRORLEVEL%==0 (
ECHO PRIVILEGED!
) ELSE (
ECHO NOT PRIVILEGED!
)
有时您不喜欢触摸用户磁盘的想法,即使它像使用fsutils或创建空文件夹一样无碍 这无法证明,但如果出了问题,可能会导致灾难性的失败。在这种情况下,您可以检查注册表的特权

为此,你可以尝试使用默认权限在HKEY_LOCAL_MACHINE上创建一个密钥,你将得到拒绝访问ERRORLEVEL == 1,但如果你以Admin身份运行,它将打印"命令执行成功"ERRORLEVEL == 0。由于键已经存在,它对注册表没有影响。这可能是最快的方法,而注册已经存在很长时间了。

* 这是不可用的pre NT (Win 9X)。

* 适用于XP和以后


工作示例

清除临时文件夹的脚本

@echo off
:main
echo.
echo. Clear Temp Files script
echo.


call :requirePrivilegies


rem Do something that require privilegies


echo.
del %temp%\*.*
echo. End!


pause>nul
goto :eof




:requirePrivilegies
set guid=%random%%random%-%random%-%random%-%random%-%random%%random%%random%
mkdir %WINDIR%\%guid%>nul 2>&1
rmdir %WINDIR%\%guid%>nul 2>&1
IF NOT %ERRORLEVEL%==0 (
echo ########## ERROR: ADMINISTRATOR PRIVILEGES REQUIRED ###########
echo # This script must be run as administrator to work properly!  #
echo # Right click on the script and select "Run As Administrator" #
echo ###############################################################
pause>nul
exit
)
goto :eof

以下是我的两便士:

在用户登录过程中,在“工作室”环境中,我需要在Domain环境中运行批处理,查看用户是否遵守“锁定”策略和受限视图(主要通过GPO集分布)。

在AD用户链接登录脚本之前应用Domain GPO集 创建一个GPO登录脚本太过成熟,因为用户的“新”配置文件还没有创建/加载/或准备好,无法及时应用“删除和/或固定”任务栏和开始菜单项vbscript +添加一些本地文件 < p >。:建议的“默认用户”配置文件环境需要一个“。URL' (.lnk)的快捷方式放置在“%ProgramData%\Microsoft\Windows\开始菜单\程序*MyNewOWA。Url *”,和 “C: \ \公共桌面\ \ * MyNewOWA用户。Url *"位置,在其他项目中

用户在域中有多台机器,其中只有这些设置的“工作室”pc需要这些策略。

这些文件夹需要“管理员”权限来修改,尽管“域用户”是本地“管理员”组的一部分,但UAC是下一个挑战。

在这里发现了各种适应和合并。我确实有一些用户自带设备,以及需要其他文件与烫发问题。 没有在XP(有点太旧的操作系统)上测试过,但代码是存在的,很乐意反馈

    :: ------------------------------------------------------------------------
:: You have a royalty-free right to use, modify, reproduce and distribute
:: the Sample Application Files (and/or any modified version) in any way
:: you find useful, provided that you agree that the author provides
:: no warranty, obligations or liability for any Sample Application Files.
:: ------------------------------------------------------------------------


:: ********************************************************************************
::* Sample batch script to demonstrate the usage of RunAs.cmd
::*
::* File:           RunAs.cmd
::* Date:           12/10/2013
::* Version:        1.0.2
::*
::* Main Function:  Verifies status of 'bespoke' Scripts ability to 'Run As - Admin'
::*                 elevated privileges and without UAC prompt
::*
::* Usage:          Run RunAs.cmd from desired location
::*         Bespoke.cmd will be created and called from C:\Utilities location
::*         Choose whether to delete the script after its run by removing out-comment
::*                 (::) before the 'Del /q Bespoke.cmd' command
::*
::* Distributed under a "GNU GPL" type basis.
::*
::* Revisions:
::* 1.0.0 - 08/10/2013 - Created.
::* 1.0.1 - 09/10/2013 - Include new path creation.
::* 1.0.2 - 12/10/2013 - Modify/shorten UAC disable process for Admins
::*
::* REFERENCES:
::* Sample "*.inf" secpol.msc export from Wins 8 x64 @ bottom,
::* Would be default but for 'no password complexities'
::*
::* To recreate UAC default:
::* Goto:Secpol, edit out Exit, modify .inf set, export as "Wins8x64.inf"
::* and import using secedit cmd provided
::*
:: ********************************************************************************


@echo off & cls
color 9F
Title RUN AS
Setlocal
:: Verify local folder availability for script
IF NOT EXIST C:\Utilities (
mkdir C:\Utilities & GOTO:GenBatch
) ELSE (
Goto:GenBatch
)
:GenBatch
c:
cd\
cd C:\Utilities
IF NOT EXIST C:\Utilities\Bespoke.cmd (
GOTO:CreateBatch
) ELSE (
Goto:RunBatch
)
:CreateBatch
Echo. >Bespoke.cmd
Echo :: ------------------------------------------------------------------------ >>Bespoke.cmd
Echo :: You have a royalty-free right to use, modify, reproduce and distribute >>Bespoke.cmd
Echo :: the Sample Application Files (and/or any modified version) in any way >>Bespoke.cmd
Echo :: you find useful, provided that you agree that the author provides >>Bespoke.cmd
Echo :: has no warranty, obligations or liability for any Sample Application Files. >>Bespoke.cmd
Echo :: ------------------------------------------------------------------------ >>Bespoke.cmd
Echo. >>Bespoke.cmd
Echo :: ******************************************************************************** >>Bespoke.cmd
Echo ::* Sample batch script to demonstrate the usage of Bespoke.cmd >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* File:           Bespoke.cmd >>Bespoke.cmd
Echo ::* Date:           10/10/2013 >>Bespoke.cmd
Echo ::* Version:        1.0.1 >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* Main Function:  Allows for running of Bespoke batch with elevated rights and no future UAC 'pop-up' >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* Usage:          Called and created by RunAs.cmd run from desired location >>Bespoke.cmd
Echo ::*                 Found in the C:\Utilities folder >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* Distributed under a "GNU GPL" type basis. >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* Revisions: >>Bespoke.cmd
Echo ::* 1.0.0 - 09/10/2013 - Created. >>Bespoke.cmd
Echo ::* 1.0.1 - 10/10/2013 - Modified, added ability to temp disable UAC pop-up warning. >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* REFERENCES: >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* Exit code (%%^ErrorLevel%%) 0 - No errors have occurred, i.e. immediate previous command ran successfully >>Bespoke.cmd
Echo ::* Exit code (%%^ErrorLevel%%) 1 - Errors occurred, i.e. immediate previous command ran Unsuccessfully >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* MS OS version check >>Bespoke.cmd
Echo ::* http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833%28v=vs.85%29.aspx >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* Copying to certain folders and running certain apps require elevated perms >>Bespoke.cmd
Echo ::* Even with 'Run As ...' perms, UAC still pops up. >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* To run a script or application in the Windows Shell >>Bespoke.cmd
Echo ::* http://ss64.com/vb/shellexecute.html >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo ::* Machines joined to a corporate Domain should have the UAC feature set from, and >>Bespoke.cmd
Echo ::* pushed out from a DC GPO policy >>Bespoke.cmd
Echo ::* e.g.: 'Computer Configuration - Policies - Windows Settings - Security Settings -  >>Bespoke.cmd
Echo ::* Local Policies/Security Options - User Account Control -  >>Bespoke.cmd
Echo ::* Policy: User Account Control: Behavior of the elevation prompt for administrators >>Bespoke.cmd
Echo ::*         in Admin Approval Mode  Setting: Elevate without prompting >>Bespoke.cmd
Echo ::* >>Bespoke.cmd
Echo :: ******************************************************************************** >>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo @Echo off ^& cls>>Bespoke.cmd
Echo color 9F>>Bespoke.cmd
Echo Title RUN AS ADMIN>>Bespoke.cmd
Echo Setlocal>>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo Set "_OSVer=">>Bespoke.cmd
Echo Set "_OSVer=UAC">>Bespoke.cmd
Echo VER ^| FINDSTR /IL "5." ^>NUL>>Bespoke.cmd
Echo IF %%^ErrorLevel%%==0 SET "_OSVer=PreUAC">>Bespoke.cmd
Echo IF %%^_OSVer%%==PreUAC Goto:XPAdmin>>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo :: Check if machine part of a Domain or within a Workgroup environment >>Bespoke.cmd
Echo Set "_DomainStat=">>Bespoke.cmd
Echo Set "_DomainStat=%%USERDOMAIN%%">>Bespoke.cmd
Echo If /i %%^_DomainStat%% EQU %%^computername%% (>>Bespoke.cmd
Echo Goto:WorkgroupMember>>Bespoke.cmd
Echo ) ELSE (>>Bespoke.cmd
Echo Set "_DomainStat=DomMember" ^& Goto:DomainMember>>Bespoke.cmd
Echo )>>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo :WorkgroupMember>>Bespoke.cmd
Echo :: Verify status of Secpol.msc 'ConsentPromptBehaviorAdmin' Reg key >>Bespoke.cmd
Echo reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin ^| Find /i "0x0">>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo If %%^ErrorLevel%%==0 (>>Bespoke.cmd
Echo    Goto:BespokeBuild>>Bespoke.cmd
Echo ) Else (>>Bespoke.cmd
Echo    Goto:DisUAC>>Bespoke.cmd
Echo )>>Bespoke.cmd
Echo :DisUAC>>Bespoke.cmd
Echo :XPAdmin>>Bespoke.cmd
Echo :DomainMember>>Bespoke.cmd
Echo :: Get ADMIN Privileges, Start batch again, modify UAC ConsentPromptBehaviorAdmin reg if needed >>Bespoke.cmd
Echo ^>nul ^2^>^&1 ^"^%%^SYSTEMROOT%%\system32\cacls.exe^"^ ^"^%%^SYSTEMROOT%%\system32\config\system^">>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo IF ^'^%%^Errorlevel%%^'^ NEQ '0' (>>Bespoke.cmd
Echo    echo Set objShell = CreateObject^^("Shell.Application"^^) ^> ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
Echo    echo objShell.ShellExecute ^"^%%~s0^"^, "", "", "runas", 1 ^>^> ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
Echo    ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
Echo    del ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
Echo    exit /B>>Bespoke.cmd
Echo ) else (>>Bespoke.cmd
Echo    pushd ^"^%%^cd%%^">>Bespoke.cmd
Echo    cd /d ^"^%%~dp0^">>Bespoke.cmd
Echo    @echo off>>Bespoke.cmd
Echo )>>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo IF %%^_OSVer%%==PreUAC Goto:BespokeBuild>>Bespoke.cmd
Echo IF %%^_DomainStat%%==DomMember Goto:BespokeBuild>>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f>>Bespoke.cmd
Echo.>>Bespoke.cmd
Echo :BespokeBuild>>Bespoke.cmd
Echo :: Add your script requiring elevated perm and no UAC below: >>Bespoke.cmd
Echo.>>Bespoke.cmd


:: PROVIDE BRIEF EXPLINATION AS TO WHAT YOUR SCRIPT WILL ACHIEVE
Echo ::


:: ADD THE "PAUSE" BELOW ONLY IF YOU SET TO SEE RESULTS FROM YOUR SCRIPT
Echo Pause>>Bespoke.cmd


Echo Goto:EOF>>Bespoke.cmd
Echo :EOF>>Bespoke.cmd
Echo Exit>>Bespoke.cmd


Timeout /T 1 /NOBREAK >Nul
:RunBatch
call "Bespoke.cmd"
:: Del /F /Q "Bespoke.cmd"


:Secpol
:: Edit out the 'Exit (rem or ::) to run & import default wins 8 security policy provided below
Exit


:: Check if machine part of a Domain or within a Workgroup environment
Set "_DomainStat="
Set _DomainStat=%USERDOMAIN%
If /i %_DomainStat% EQU %computername% (
Goto:WorkgroupPC
) ELSE (
Echo PC Member of a Domain, Security Policy determined by GPO
Pause
Goto:EOF
)


:WorkgroupPC


reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin | Find /i "0x5"
Echo.
If %ErrorLevel%==0 (
Echo Machine already set for UAC 'Prompt'
Pause
Goto:EOF
) else (
Goto:EnableUAC
)
:EnableUAC
IF NOT EXIST C:\Utilities\Wins8x64Def.inf (
GOTO:CreateInf
) ELSE (
Goto:RunInf
)
:CreateInf
:: This will create the default '*.inf' file and import it into the
:: local security policy for the Wins 8 machine
Echo [Unicode]>>Wins8x64Def.inf
Echo Unicode=yes>>Wins8x64Def.inf
Echo [System Access]>>Wins8x64Def.inf
Echo MinimumPasswordAge = ^0>>Wins8x64Def.inf
Echo MaximumPasswordAge = ^-1>>Wins8x64Def.inf
Echo MinimumPasswordLength = ^0>>Wins8x64Def.inf
Echo PasswordComplexity = ^0>>Wins8x64Def.inf
Echo PasswordHistorySize = ^0>>Wins8x64Def.inf
Echo LockoutBadCount = ^0>>Wins8x64Def.inf
Echo RequireLogonToChangePassword = ^0>>Wins8x64Def.inf
Echo ForceLogoffWhenHourExpire = ^0>>Wins8x64Def.inf
Echo NewAdministratorName = ^"^Administrator^">>Wins8x64Def.inf
Echo NewGuestName = ^"^Guest^">>Wins8x64Def.inf
Echo ClearTextPassword = ^0>>Wins8x64Def.inf
Echo LSAAnonymousNameLookup = ^0>>Wins8x64Def.inf
Echo EnableAdminAccount = ^0>>Wins8x64Def.inf
Echo EnableGuestAccount = ^0>>Wins8x64Def.inf
Echo [Event Audit]>>Wins8x64Def.inf
Echo AuditSystemEvents = ^0>>Wins8x64Def.inf
Echo AuditLogonEvents = ^0>>Wins8x64Def.inf
Echo AuditObjectAccess = ^0>>Wins8x64Def.inf
Echo AuditPrivilegeUse = ^0>>Wins8x64Def.inf
Echo AuditPolicyChange = ^0>>Wins8x64Def.inf
Echo AuditAccountManage = ^0>>Wins8x64Def.inf
Echo AuditProcessTracking = ^0>>Wins8x64Def.inf
Echo AuditDSAccess = ^0>>Wins8x64Def.inf
Echo AuditAccountLogon = ^0>>Wins8x64Def.inf
Echo [Registry Values]>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SecurityLevel=4,^0>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SetCommand=4,^0>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\CachedLogonsCount=1,"10">>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ForceUnlockLogon=4,^0>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\PasswordExpiryWarning=4,5>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ScRemoveOption=1,"0">>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorAdmin=4,5>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorUser=4,3>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableCAD=4,1>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLastUserName=4,^0>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableInstallerDetection=4,1>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA=4,1>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableSecureUIAPaths=4,1>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableUIADesktopToggle=4,^0>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableVirtualization=4,1>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\FilterAdministratorToken=4,^0>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeCaption=1,"">>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeText=7,>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\PromptOnSecureDesktop=4,1>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ScForceOption=4,^0>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ShutdownWithoutLogon=4,1>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\UndockWithoutLogon=4,1>>Wins8x64Def.inf
Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ValidateAdminCodeSignatures=4,^0>>Wins8x64Def.inf
Echo MACHINE\Software\Policies\Microsoft\Windows\Safer\CodeIdentifiers\AuthenticodeEnabled=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\AuditBaseObjects=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\CrashOnAuditFail=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\DisableDomainCreds=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\EveryoneIncludesAnonymous=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\ForceGuest=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\FullPrivilegeAuditing=3,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\LimitBlankPasswordUse=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinClientSec=4,536870912>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinServerSec=4,536870912>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\NoLMHash=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymous=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymousSAM=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Print\Providers\LanMan Print Services\Servers\AddPrinterDrivers=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedExactPaths\Machine=7,System\CurrentControlSet\Control\ProductOptions,System\CurrentControlSet\Control\Server Applications,Software\Microsoft\Windows NT\CurrentVersion>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedPaths\Machine=7,System\CurrentControlSet\Control\Print\Printers,System\CurrentControlSet\Services\Eventlog,Software\Microsoft\OLAP Server,Software\Microsoft\Windows NT\CurrentVersion\Print,Software\Microsoft\Windows NT\CurrentVersion\Windows,System\CurrentControlSet\Control\ContentIndex,System\CurrentControlSet\Control\Terminal Server,System\CurrentControlSet\Control\Terminal Server\UserConfig,System\CurrentControlSet\Control\Terminal Server\DefaultUserConfiguration,Software\Microsoft\Windows NT\CurrentVersion\Perflib,System\CurrentControlSet\Services\SysmonLog>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Session Manager\Kernel\ObCaseInsensitive=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Session Manager\Memory Management\ClearPageFileAtShutdown=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Session Manager\ProtectionMode=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems\optional=7,Posix>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\AutoDisconnect=4,15>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableForcedLogOff=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableSecuritySignature=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\NullSessionPipes=7,>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RequireSecuritySignature=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RestrictNullSessAccess=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnablePlainTextPassword=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnableSecuritySignature=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\RequireSecuritySignature=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\LDAP\LDAPClientIntegrity=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\DisablePasswordChange=4,^0>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\MaximumPasswordAge=4,30>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireSignOrSeal=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireStrongKey=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SealSecureChannel=4,1>>Wins8x64Def.inf
Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SignSecureChannel=4,1>>Wins8x64Def.inf
Echo [Privilege Rights]>>Wins8x64Def.inf
Echo SeNetworkLogonRight = *S-1-1-0,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
Echo SeBackupPrivilege = *S-1-5-32-544,*S-1-5-32-551>>Wins8x64Def.inf
Echo SeChangeNotifyPrivilege = *S-1-1-0,*S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551,*S-1-5-90-^0>>Wins8x64Def.inf
Echo SeSystemtimePrivilege = *S-1-5-19,*S-1-5-32-544>>Wins8x64Def.inf
Echo SeCreatePagefilePrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeDebugPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeRemoteShutdownPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeAuditPrivilege = *S-1-5-19,*S-1-5-20>>Wins8x64Def.inf
Echo SeIncreaseQuotaPrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544>>Wins8x64Def.inf
Echo SeIncreaseBasePriorityPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeLoadDriverPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeBatchLogonRight = *S-1-5-32-544,*S-1-5-32-551,*S-1-5-32-559>>Wins8x64Def.inf
Echo SeServiceLogonRight = *S-1-5-80-0,*S-1-5-83-^0>>Wins8x64Def.inf
Echo SeInteractiveLogonRight = Guest,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
Echo SeSecurityPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeSystemEnvironmentPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeProfileSingleProcessPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeSystemProfilePrivilege = *S-1-5-32-544,*S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420>>Wins8x64Def.inf
Echo SeAssignPrimaryTokenPrivilege = *S-1-5-19,*S-1-5-20>>Wins8x64Def.inf
Echo SeRestorePrivilege = *S-1-5-32-544,*S-1-5-32-551>>Wins8x64Def.inf
Echo SeShutdownPrivilege = *S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
Echo SeTakeOwnershipPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeDenyNetworkLogonRight = Guest>>Wins8x64Def.inf
Echo SeDenyInteractiveLogonRight = Guest>>Wins8x64Def.inf
Echo SeUndockPrivilege = *S-1-5-32-544,*S-1-5-32-545>>Wins8x64Def.inf
Echo SeManageVolumePrivilege = *S-1-5-32-544>>Wins8x64Def.inf
Echo SeRemoteInteractiveLogonRight = *S-1-5-32-544,*S-1-5-32-555>>Wins8x64Def.inf
Echo SeImpersonatePrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-6>>Wins8x64Def.inf
Echo SeCreateGlobalPrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-6>>Wins8x64Def.inf
Echo SeIncreaseWorkingSetPrivilege = *S-1-5-32-545,*S-1-5-90-^0>>Wins8x64Def.inf
Echo SeTimeZonePrivilege = *S-1-5-19,*S-1-5-32-544,*S-1-5-32-545>>Wins8x64Def.inf
Echo SeCreateSymbolicLinkPrivilege = *S-1-5-32-544,*S-1-5-83-^0>>Wins8x64Def.inf
Echo [Version]>>Wins8x64Def.inf
Echo signature="$CHICAGO$">>Wins8x64Def.inf
Echo Revision=1>>Wins8x64Def.inf


:RunInf
:: Import 'Wins8x64Def.inf' with ADMIN Privileges, to modify UAC ConsentPromptBehaviorAdmin reg
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%%\system32\config\system"
IF '%Errorlevel%' NEQ '0' (
echo Set objShell = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo objShell.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
Secedit /configure /db secedit.sdb /cfg C:\Utilities\Wins8x64Def.inf /overwrite
Goto:CheckUAC
) else (
Secedit /configure /db secedit.sdb /cfg C:\Utilities\Wins8x64Def.inf /overwrite
@echo off
)
:CheckUAC
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin | Find /i "0x5"
Echo.
If %ErrorLevel%==0 (
Echo ConsentPromptBehaviorAdmin set to 'Prompt'
Pause
Del /Q C:\Utilities\Wins8x64Def.inf
Goto:EOF
) else (
Echo ConsentPromptBehaviorAdmin NOT set to default
Pause
)
ENDLOCAL
:EOF
Exit
域PC应该尽可能多地由GPO集管理。 工作组/独立机器可以通过该脚本进行管理

请记住,对于BYOD工作组PC, UAC提示至少会弹出一次(当需要第一次提升到“Admin perms”时),但是随着本地安全策略被修改为管理使用,弹出窗口将会消失。

域PC应该在“已经”创建的“锁定”策略中设置GPO“conssentpromptbehavioradmin”策略-如脚本“REFERENCES”部分所述。

再次,运行默认` .exe的secedit.exe导入。如果你被整个“去UAC还是不去UAC”的争论困住了:-)。

< p >顺便说一句: @boileau 检查你的失败:

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

通过在命令提示符中只运行“%SYSTEMROOT%\system32\cacls.exe”或“%SYSTEMROOT%\system32\config\system”或两者都运行(提升与否),可以全面检查结果。

< p >注意: 检查\system32\config\系统的调用 将总是失败在WOW64,(例如从%systemroot%\syswow64\cmd.exe / 32位Total Commander),所以脚本运行在32位shell在64位系统将永远循环… 更好的方法是检查预读目录的权限:

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\Prefetch\"

Win XP到7测试,但它失败在WinPE在windows 7安装。Wim没有这样的dir或cacls.exe

在winPE和wow64中,使用openfiles.exe检查失败:

OPENFILES > nul

在Windows 7中,它将errorlevel为“1”,信息为“目标系统需要是32位操作系统”

这两个检查也可能在恢复控制台失败。

什么工作在Windows XP - 8 32/64位,在WOW64和WinPE是:目录创建测试(如果管理员没有地毯轰炸Windows目录的权限为每个人…)和

net session

而且

reg add HKLM /F

检查。

还有一个注意在一些windows XP(和其他版本可能太,取决于管理员的修补)依赖于注册表项直接调用bat/cmd从.vbs脚本将失败的信息,bat/cmd文件不与任何相关…

echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
cscript "%temp%\getadmin.vbs" //nologo

另一方面,用bat/cmd文件的参数调用cmd.exe可以正常工作:

echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd.exe", "/C %~s0", "", "runas", 1 >> "%temp%\getadmin.vbs"
cscript "%temp%\getadmin.vbs" //nologo

更多的问题

正如@Lectrode所指出的,如果你试图在服务器服务停止时运行net session命令,你会收到以下错误消息:

The Server service is not started.


More help is available by typing NET HELPMSG 2114

在这种情况下,%errorLevel%变量将被设置为2

请注意服务器服务在安全模式下(有或没有网络)没有启动。

寻找替代方案

的东西:

  • 可以在Windows XP及更高版本(32位和64位)上运行;
  • 不涉及注册表或任何系统文件/文件夹;
  • 与系统区域无关的工作;
  • 即使在安全模式下也能给出正确的结果。

所以我启动了一个普通的Windows XP虚拟机,我开始滚动C:\Windows\System32文件夹中的应用程序列表,试图得到一些想法。经过反复试验,这是我想出的(双关语)方法:

fsutil dirty query %systemdrive% >nul

fsutil dirty命令需要管理员权限才能运行,否则将失败。%systemdrive%是一个环境变量,它返回安装操作系统的驱动器号。输出被重定向到nul,因此被忽略。%errorlevel%变量只有在成功执行时才会被设置为0

以下是文档的内容:

Fsutil dirty

查询或设置卷的脏位。当设置了卷的脏位时,autochk将在下次计算机重新启动时自动检查卷是否有错误。

语法

fsutil dirty {query | set} <VolumePath>

参数

query           Queries the specified volume's dirty bit.
set             Sets the specified volume's dirty bit.
<VolumePath>    Specifies the drive name followed by a colon or GUID.

讲话

卷的脏位表示文件系统可能处于不一致状态。脏位可以设置,因为:

  • 卷已经上线,变化比较突出。
  • 对卷进行了更改,并且在将更改提交到磁盘之前关闭了计算机。
  • 在卷上检测到腐败。

如果脏位是在计算机重新启动时设置的,chkdsk将运行以验证文件系统的完整性,并尝试修复卷的任何问题。

例子

查询C盘的脏位,输入:

fsutil dirty query C:

进一步的研究

虽然上面的解决方案从Windows XP开始工作,但值得补充的是,Windows 2000和Windows PE(预安装环境)没有附带fsutil.exe,所以我们必须求助于其他东西。

在我之前的测试中,我注意到不带任何参数运行sfc命令会导致:

  • 如果您没有足够的权限,则会出现错误;
  • 可用参数及其用法的列表。

即:没有参数,任何一方。这个想法是我们可以解析输出并检查我们是否得到了错误以外的任何东西:

sfc 2>&1 | find /i "/SCANNOW" >nul

错误输出首先被重定向到标准输出,然后通过管道传输到find命令。此时,我们必须寻找自Windows 2000以来为所有Windows版本均支持只有参数:/SCANNOW。搜索不区分大小写,输出被重定向到nul而被丢弃。

以下是文档的节选:

证监会< a href = " http://technet.microsoft.com/en-us/library/ff950779.aspx " > < / >

扫描并验证所有受保护的系统文件的完整性,将错误的版本替换为正确的版本。

讲话

您必须作为Administrators组的成员登录才能运行sfc.exe

示例使用

下面是一些粘贴后运行的例子:

Windows XP及以上版本

@echo off


call :isAdmin
if %errorlevel% == 0 (
echo Running with admin rights.
) else (
echo Error: Access denied.
)


pause >nul
exit /b


:isAdmin
fsutil dirty query %systemdrive% >nul
exit /b

Windows 2000 / Windows PE

@echo off


call :isAdmin
if %errorlevel% == 0 (
echo Running with admin rights.
) else (
echo Error: Access denied.
)


pause >nul
exit /b


:isAdmin
sfc 2>&1 | find /i "/SCANNOW" >nul
exit /b

适用于

  • Windows 2000
  • Windows XP
  • Windows Vista
  • Windows 7
  • Windows 8
  • <李> Windows 8.1
    ——< br >
  • Windows体育

可选择的解决方案:

@echo off
pushd %SystemRoot%
openfiles.exe 1>nul 2>&1
if not %errorlevel% equ 0 (
Echo here you are not administrator!
) else (
Echo here you are administrator!
)
popd
Pause

替代方案:使用专门为此目的设计的外部实用程序,例如IsAdmin.exe(无限制免费软件)。

退出代码:

0 -当前用户不是Administrators组的成员

1 -管理员的当前用户成员和运行提升

2 -管理员的当前用户成员,但未运行提升

@echo off
ver
set ADMDIR=C:\Users\Administrator
dir %ADMDIR% 1>nul 2>&1
echo [%errorlevel%] %ADMDIR%
if "%errorlevel%"=="0" goto main
:: further checks e.g. try to list the contents of admin folders
:: wherever they are stored on older versions of Windows
echo You need administrator privileges to run this script: %0
echo Exiting...
exit /b


:main
echo Executing with Administrator privileges...

还有两种方法——快速和向后兼容。

fltmc >nul 2>&1 && (
echo has admin permissions
) || (
echo has NOT admin permissions
)

fltmc命令在XP以来的每个windows系统上都可用,所以这应该是相当可移植的。


XP8.17上测试的另一个真正快速的解决方案-有一个特定的变量=::,它只在控制台会话没有管理权限时才会出现。由于创建名称中包含=的变量并不容易,因此这是一种相对可靠的检查管理权限的方法(它不调用外部可执行文件,因此性能良好)

setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! (
echo has NOT admin permissions
) else (
echo has admin permissions
)

如果你想通过命令行直接使用,而不是从批处理文件,你可以使用:

set ^"|find "::"||echo has admin permissions

另一种方法。

REM    # # # #      CHECKING OR IS STARTED AS ADMINISTRATOR     # # # # #


FSUTIL | findstr /I "volume" > nul&if not errorlevel 1  goto Administrator_OK


cls
echo *******************************************************
echo ***    R U N    A S    A D M I N I S T R A T O R    ***
echo *******************************************************
echo.
echo.
echo Call up just as the Administrator. Abbreviation can be done to the script and set:
echo.
echo      Shortcut ^> Advanced ^> Run as Administrator
echo.
echo.
echo Alternatively, a single run "Run as Administrator"
echo or in the Schedule tasks with highest privileges
pause > nul
goto:eof
:Administrator_OK


REM Some next lines code ...
@echo off
:start
set randname=%random%%random%%random%%random%%random%
md \windows\%randname% 2>nul
if %errorlevel%==0 (echo You're elevated!!!
goto end)
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)
goto start
:end
rd \windows\%randname% 2>nul
pause >nul

我将逐行解释代码:

@echo off

如果没有这个选项,用户会对超过一行的代码感到厌烦。

:start

指向程序开始的位置。

set randname=%random%%random%%random%%random%%random%

设置要创建的目录的文件名。

md \windows\%randname% 2>nul

<DL>:\Windows上创建目录(将<DL>替换为驱动器号)。

if %errorlevel%==0 (echo You're elevated!!!
goto end)

如果ERRORLEVEL环境变量为0,则返回成功消息

.

.

.

.

.
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)

如果ERRORLEVEL为1,回显失败消息并返回结束。

goto start

如果文件名已经存在,则重新创建文件夹(否则goto end命令将不让该文件夹运行)。

:end

指定结束点

rd \windows\%randname% 2>nul

删除已创建的目录。

pause >nul

暂停以便用户可以看到消息。

请注意: >nul2>nul过滤这些命令的输出。

whoami /groups在一种情况下不起作用。如果你已经完全关闭UAC(不仅仅是关闭通知),而且你从一个管理员提示开始,然后发出:

runas /trustlevel:0x20000 cmd

你将运行非提升,但发出:

whoami /groups

会说你升职了。这是错误的。这就是为什么它是错误的:

在此状态下运行时,如果IsUserAdmin (https://msdn.microsoft.com/en-us/library/windows/desktop/aa376389 (v = vs.85) . aspx)返回FALSE且UAC完全禁用,并且GetTokenInformation返回TokenElevationTypeDefault (http://blogs.msdn.com/b/cjacks/archive/2006/10/24/modifying-the-mandatory-integrity-level-for-a-securable-object-in-windows-vista.aspx),则进程是正在运行提升,但whoami /groups声称它是。

实际上,从批处理文件中做到这一点的最好方法是:

net session >nul 2>nul
net session >nul 2>nul
echo %errorlevel%

你应该做net session两次,因为如果有人事先做了at,你会得到错误的信息。

net user %username% >nul 2>&1 && echo admin || echo not admin

使用CMD脚本检查管理权限的最干净的方法,我发现,是这样的:

@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

这个方法只使用CMD.exe内置程序,所以它应该非常快。它还检查进程的实际功能,而不是检查sid或组成员关系,因此测试有效的权限。这可以追溯到Windows 2003和XP。普通用户进程或非提升进程目录探测失败,而Admin进程或提升进程成功。

从字面上看,在SE上有几十个答案和相关的问题,所有这些都在这样或那样的方式上存在缺陷,清楚地表明Windows没有提供可靠的内置控制台实用程序。所以,是时候推出你自己的了。

下面的C代码基于检测程序是否以完全管理员权限运行,在Win2k+1中工作,在任何地方和所有情况下(UAC,域,可传递组…)-因为它在检查权限时与系统本身相同。它用消息(可以用开关使其静音)和退出代码表示结果。

它只需要编译一次,然后你可以复制.exe到任何地方——它只依赖于kernel32.dlladvapi32.dll(我已经上传副本)。

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;
}

1MSDN声称api是XP+,但这是错误的。CheckTokenMembership 是2k+和另一个更老。最后一个链接还包含一种更复杂的方法,即使在NT中也可以工作。

编辑:版权已指出这是不可靠的。使用UAC批准读访问将允许dir成功。我有更多的脚本来提供另一种可能性,但它不是只读的。

reg query "HKLM\SOFTWARE\Foo" >NUL 2>NUL && goto :error_key_exists
reg add "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_not_admin
reg delete "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_failed_delete
goto :success


:error_failed_delete
echo Error unable to delete test key
exit /b 3
:error_key_exists
echo Error test key exists
exit /b 2
:error_not_admin
echo Not admin
exit /b 1
:success
echo Am admin

旧答案如下

警告:不可靠


根据and31415提出的其他一些很好的答案和观点,我发现我是以下人的粉丝:

dir "%SystemRoot%\System32\config\DRIVERS" 2>nul >nul || echo Not Admin

依赖性少,速度快。

PowerShell有人知道吗?

param (
[string]$Role = "Administrators"
)


#check for local role


$identity  = New-Object Security.Principal.WindowsIdentity($env:UserName)
$principal = New-Object Security.Principal.WindowsPrincipal($identity)


Write-Host "IsInRole('$Role'): " $principal.IsInRole($Role)


#enumerate AD roles and lookup


$groups = $identity::GetCurrent().Groups
foreach ($group in $groups) {
$trans = $group.Translate([Security.Principal.NTAccount]);
if ($trans.Value -eq $Role) {
Write-Host "User is in '$Role' role"
}
}

这里有另一个添加到列表中;-)

(尝试在系统位置创建文件)

CD.>"%SystemRoot%\System32\Drivers\etc\_"
MODE CON COLS=80 LINES=25


IF EXIST "%SystemRoot%\System32\Drivers\etc\_" (


DEL "%SystemRoot%\System32\Drivers\etc\_"


ECHO Has Admin privileges


) ELSE (


ECHO No Admin privileges


)

当没有权限写入系统位置时,MODE CON将重新初始化屏幕并压制任何文本/错误。

在批处理脚本Elevate.cmd(见< >强这个链接< / >强)中,我已经写到了获得管理员权限,我已经这样做了:

@echo off


:checkPrivileges
NET FILE 1>NUL 2>NUL
if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

脚本的其余部分看起来像这样:

:getPrivileges
rem need to get admin rights, check batch script Elevate.cmd to see how to do that
echo You have no admin rights. Cannot continue.
goto end


:gotPrivileges
echo You have admin rights. Continuing...
rem *** do your admin tasks here ***


:end
pause

这是在Windows 7、8、8.1、10甚至Windows XP上进行了测试,不需要任何资源,如特殊的目录,文件或注册表项。

它使用的事实是,命令NET FILE需要有管理权限才能运行,如果它成功运行(并且检测到管理权限),将返回一个错误级别0,否则它返回一个错误级别>0. 任何消息都被1>NUL 2>NULL抑制。

NET FILE的优点是,它不会改变系统上的任何东西来检测管理权限(就像其他解决方案试图通过在受保护区域中创建注册表键或文件/目录来探测管理权限)。

本页中四个看似最兼容的方法的集合。第一个真的很天才。从XP开始测试。令人困惑的是,没有标准的命令可以检查管理权限。我猜他们现在只是专注于PowerShell,这对于我自己的大部分工作来说都是无用的。

我把这个批处理称为“exit-if-not-admin”。Cmd `可以从其他批中调用,以确保如果没有给定所需的管理权限,它们不会继续执行。

rem Sun May 03, 2020


rem Methods for XP+ used herein based on:
rem https://stackoverflow.com/questions/4051883/batch-script-how-to-check-for-admin-rights
goto method1


:method1
setlocal enabledelayedexpansion
set "dv==::"
if defined !dv! goto notadmin
goto admin


:method2
call fsutil dirty query %SystemDrive% >nul
if %ERRORLEVEL%==0 goto admin
goto notadmin


:method3
net session >nul 2>&1
if %ERRORLEVEL%==0 goto admin
goto notadmin


:method4
fltmc >nul 2>&1 && goto admin
goto notadmin


:admin
echo Administrator rights detected
goto end


:notadmin
echo ERROR: This batch must be run with Administrator privileges
pause
exit /b
goto end


:end```