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

时间:2010-10-29 12:35:46

标签: windows batch-file cmd admin

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

我知道如何使用runas调用自己,而不是如何检查管理员权限。我见过的唯一解决方案是粗暴的黑客工作或使用外部程序。好吧,实际上我并不关心它是否是一个黑客工作,只要它适用于Windows XP及更新版本。

28 个答案:

答案 0 :(得分:417)

问题

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 true ,干净,通用的解决方案,不涉及:

  • 在安全位置创建或与数据交互
  • 分析从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

(见截图#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

此处可用,如果你很懒:https://dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat

说明

NET SESSION是用于"manage server computer connections. Used without parameters, [it] displays information about all sessions with the local computer."

的标准命令

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

  1. @echo off
    • 禁用显示命令
  2. goto check_Permissions
    • 跳转到:check_Permissions代码块
  3. net session >nul 2>&1
    • 运行命令
    • 隐藏命令的视觉输出
      1. 将标准输出(数字句柄1 / STDOUT)流重定向到nul
      2. 将标准错误输出流(数字句柄2 / STDERR)重定向到与数字句柄1相同的目标
  4. if %errorLevel% == 0
    • 如果退出代码(%errorLevel%的值 0,那么这意味着没有发生错误,因此,立即上一个命令成功
  5. else
    • 如果退出代码(%errorLevel%的值不是 0,则表示错误已发生,因此,立即上一个命令运行失败
  6. 将根据符合的标准执行相应括号之间的代码
  7. 截图

    Windows 8 AT %errorLevel%

    [imgur]

    NET SESSION on Windows XP x86 - Windows 8 x64

    [imgur]

    感谢@Tilka将您接受的答案更改为我的答案。 :)

答案 1 :(得分:74)

Anders解决方案对我有用但我不知道如何反转它以获得相反的结果(当你不是管理员时)。

这是我的解决方案。它有两个案例是IF和ELSE案例,还有一些ascii艺术,以确保人们真正阅读它。 :)

最小版本

Rushyo在此发布了此解决方案:How to detect if CMD is running as Administrator/has elevated privileges?

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在下面的回答中指出了这一点。请提出他的回答。

答案 2 :(得分:37)

更多问题

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

The Server service is not started.

More help is available by typing NET HELPMSG 2114

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

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

寻找替代方案

东西:

  • 可以在Windows XP及更高版本(32位和64位)上开箱即用;
  • 不会触及注册表或任何系统文件/文件夹;
  • 无论系统区域设置如何都可以使用;
  • 即使在安全模式下也能得到正确的结果。

所以我启动了一个vanilla Windows XP虚拟机,然后我开始滚动浏览C:\Windows\System32文件夹中的应用程序列表,尝试获取一些想法。经过试验和错误,这是我提出的(双关语)方法:

fsutil dirty query %systemdrive% >nul

fsutil dirty命令需要管理员权限才能运行,否则将失败。 %systemdrive%environment variable,它返回安装操作系统的驱动器号。输出重定向到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以来supported in all Windows version参数:/SCANNOW。搜索不区分大小写,并通过将其重定向到nul来丢弃输出。

以下是文档的摘录:

  

Sfc

     

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

     

说明

     

您必须以管理员组成员的身份登录才能运行 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
    ---
  • Windows PE

答案 3 :(得分:17)

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"&&(
 echo admin...
)

答案 4 :(得分:17)

另一种方式

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

fltmc命令自XP以来在每个Windows系统上都可用,所以这应该是非常便携的。


XP8.17上测试了另一个解决方案(遗憾的是,它不适用于所有win10台机器 - 请参阅评论。) - 那里有一个特定变量=::仅在控制台会话没有管理员权限时才会显示。由于创建包含=的变量并不容易,因此这是一个相对可靠的方法检查管理员权限(并且非常快,因为它不调用外部可执行文件)

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

答案 5 :(得分:13)

不仅要检查,还要自动获得管理员权限 又名自动UAC for Win 7/8 / 8.1 ff。:以下是一个非常酷的一个,还有一个功能:这个批处理片段不仅检查管理员权限,而且自动获取它们! (以前的测试,如果生活在支持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)Ben Hooper在此线程中的管理测试和(2)在BatchGotAdmin上读取的UAC激活,并由robvanderwoude(尊重)在批处站点上引用。 (3)对于通过“VER | FINDSTR模式”识别操作系统,我只是找不到参考。)

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

答案 6 :(得分:13)

替代解决方案:

@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

答案 7 :(得分:11)

我有两种检查特权访问的方法,两者都非常可靠,并且几乎在每个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,但如果您运行为管理员,它将打印“命令已成功执行”ERRORLEVEL == 0。由于密钥已存在,因此对注册表没有影响。这可能是最快的方式, REG 很长一段时间。

     

* 在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

答案 8 :(得分:6)

我发现使用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。正常用户进程或非高速进程无法通过目录探测,而管理员或提升的进程也会失败。

答案 9 :(得分:5)

在我写给获取管理员权限的批处理脚本 Elevate.cmd (请参阅this link)中,我已通过以下方式完成此操作:

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

这已经针对Windows 7、8、8.1、10甚至Windows XP进行了测试,并且不需要任何资源,例如特殊目录,文件或注册表项。

答案 10 :(得分:5)

以下尝试在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,并且假定它不可能与现有文件名冲突。

答案 11 :(得分:3)

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,你就会得到错误的信息。

答案 12 :(得分:2)

某些服务器禁用命令“net session”所需的服务。 这导致管理员检查时总是说您没有管理员权限。

答案 13 :(得分:2)

whoami /groups | find "S-1-16-12288" > nul
if not errorlevel 1 (
  echo ...  connected as admin
)

答案 14 :(得分:2)

编辑:copyitright指出这是不可靠的。批准使用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

很少依赖和快速。

答案 15 :(得分:1)

注意: 使用\ system32 \ config \ system的cacls进行检查 总是会在WOW64中失败,(例如来自%systemroot%\ syswow64 \ cmd.exe / 32位Total Commander)所以在64位系统中以32位shell运行的脚本将永远循环... 更好的是检查Prefetch目录的权限:

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

Win XP到7测试,但它在WinPE中失败,因为在windows 7 install.wim中没有这样的目录也没有cacls.exe

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

OPENFILES > nul

在Windows 7中,它将以“1”的错误级别显示“目标系统需要为32位操作系统”的信息

在恢复控制台中,这两项检查都可能会失败。

在Windows XP中运行 - 8 32/64位,在WOW64和WinPE中是:dir创建测试(IF管理员没有地毯轰炸的Windows目录,每个人的权限......)和

net session

reg add HKLM /F

检查。

在某些Windows XP(以及其他版本可能也是如此,取决于管理员的修补)中还有一个注意事项,具体取决于直接从.vbs脚本调用bat / cmd的注册表项将失败,并显示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

答案 16 :(得分:1)

这是另一个要添加到列表中的内容; - )

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

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重新初始化屏幕并在没有写入系统位置的权限时抑制任何文本/错误。

答案 17 :(得分:1)

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

答案 18 :(得分:1)

在这个和相关问题以及SE的其他地方,几乎所有答案都有这样或那样的不足,已经清楚地表明Windows并没有提供可靠的内置控制台实用程序。所以,是时候推出自己的了。

基于Detect if program is running with full administrator rights的以下C代码适用于Win2k + 1 ,在任何地方和所有情况下(UAC,域,传递组......) - 因为它也是如此作为系统本身检查权限时。它通过消息(可以通过开关静音)和退出代码发出结果信号。

只需要编译一次,然后你就可以在任何地方复制.exe - 它只取决于kernel32.dlladvapi32.dll(我uploaded a copy )。

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

1 MSDN声称API是XP +,但这是错误的。 CheckTokenMembership is 2k+和另一个is even older。最后一个链接还包含一个更复杂的方法,甚至可以在NT中使用。

答案 19 :(得分:0)

此页面上四个看似最兼容的方法的集合。第一个真的很天才。从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```

答案 20 :(得分:0)

我认为最简单的方法是尝试更改系统日期(需要管理员权限):

date %date%
if errorlevel 1 (
   echo You have NOT admin rights
) else (
   echo You have admin rights
)

如果%date%变量可能包含星期几,那么只需从DATE命令的最后一部分获取日期:

for /F "delims=" %%a in ('date ^<NUL') do set "today=%%a" & goto break
:break
for %%a in (%today%) do set "today=%%a"
date %today%
if errorlevel 1 ...

答案 21 :(得分:0)

我找到了一个可以使用net session的用户,即使他们不是管理员。我没有调查原因。我的解决方法是测试用户是否可以在Windows文件夹中创建一个文件夹。

这是我的代码:

::::::: :testadmin function START :::::::
:: this function tests if current user is admin.  results are returned as "true" or "false" in %isadmin%
:: Test "%isadmin" after calling this function
:: Usage: "call :testadmin"
echo Your script entered the :testadmin function by error.  Usage: "call :testadmin"
pause
exit /b
:testadmin

 rd %windir%\local_admin_test > nul 2> nul
 md %windir%\local_admin_test > nul 2> nul
 if [%errorlevel%]==[0] set isadmin=true
 if not [%errorlevel%]==[0] set isadmin=false
 rd %windir%\local_admin_test > nul 2> nul

 if [%isadmin%]==[true] (
   echo User IS admin.
 )
 if not [%isadmin%]==[true] (
   echo User IS NOT admin.
   timeout 30
   :: or use "pause" instead of "timeout"
   exit /b
 )
exit /b
:::::: :testadmin function END ::::::

答案 22 :(得分:0)

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

答案 23 :(得分:0)

@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

如果没有这条线,用户将会被超过1条线路烦恼。

:start

程序开始的位置。

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

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

md \windows\%randname% 2>nul

<DL>:\Windows上创建目录(用驱动器号替换&lt; DL&gt;)。

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

如果ERRORLEVEL环境变量为零,则回显成功消息 到最后(不要再继续)。

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正在过滤这些命令的输出。

答案 24 :(得分:0)

@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...

答案 25 :(得分:0)

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

退出代码:

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

1 - 管理员的当前用户成员并且正在运行提升

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

答案 26 :(得分:-1)

这是我的2便士价值:

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

在AD用户链接登录脚本之前应用域GPO集 创建GPO登录脚本过于成熟,因为用户“新”配置文件尚未及时创建/加载/或准备好应用“删除和/或Pin”任务栏和开始菜单项vbscript +添加一些本地文件

例如:建议的“默认用户”配置文件环境需要在“%ProgramData%\ Microsoft \ Windows \ Start Menu \ Programs * MyNewOWA.url *”中放置“.URL”(。lnk)快捷方式,并且 “C:\ Users \ Public \ Desktop \ * MyNewOWA.url *”位置,以及其他项目

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

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

在这里找到各种改编并合并。我确实有一些用户使用BYOD设备,这需要其他带有烫发问题的文件。 没有在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集进行管理。 工作组/独立计算机可以由此脚本管理。

请记住,UAC提示将至少与BYOD工作组PC一起弹出一次(一旦需要第一次提升为'Admin perms'),但是从此点开始修改本地安全策略以供管理员使用弹出窗口将消失。

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

再次,如果你被困在整个“To UAC or Not to UAC”辩论中,请运行默认的'.inf'文件的secedit.exe导入: - )。

顺便说一句: @boileau 请检查您的失败:

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

通过在命令提示符下仅运行“%SYSTEMROOT%\ system32 \ cacls.exe”或“%SYSTEMROOT%\ system32 \ config \ system”或两者,无论是否提升,都要检查结果。

答案 27 :(得分:-2)

另一种方法。

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 ...