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

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


当前回答

更多的问题

正如@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%”为环境变量,返回安装操作系统的盘符。输出被重定向为null,因此被忽略。%errorlevel%变量只有在成功执行时才会被设置为0。

以下是文档的内容:

Fsutil dirty Queries or sets a volume's dirty bit. When a volume's dirty bit is set, autochk automatically checks the volume for errors the next time the computer is restarted. Syntax fsutil dirty {query | set} <VolumePath> Parameters 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. Remarks A volume's dirty bit indicates that the file system may be in an inconsistent state. The dirty bit can be set because: The volume is online and it has outstanding changes. Changes were made to the volume and the computer was shut down before the changes were committed to the disk. Corruption was detected on the volume. If the dirty bit is set when the computer restarts, chkdsk runs to verify the file system integrity and to attempt to fix any issues with the volume. Examples To query the dirty bit on drive C, type: 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而被丢弃。

以下是文档的节选:

香港证监会 扫描并验证所有受保护的系统文件的完整性,将错误的版本替换为正确的版本。 讲话 您必须作为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 --- Windows体育

其他回答

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

问题

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网站上列出了一些这样的命令,所以我在当前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 Disable displaying of commands goto check_Permissions Jump to the :check_Permissions code block net session >nul 2>&1 Run command Hide visual output of command by Redirecting the standard output (numeric handle 1 / STDOUT) stream to nul Redirecting the standard error output stream (numeric handle 2 / STDERR) to the same destination as numeric handle 1 if %errorLevel% == 0 If the value of the exit code (%errorLevel%) is 0 then this means that no errors have occurred and, therefore, the immediate previous command ran successfully else If the value of the exit code (%errorLevel%) is not 0 then this means that errors have occurred and, therefore, the immediate previous command ran unsuccessfully The code between the respective parenthesis will be executed depending on which criteria is met

 

截图

Windows 8 AT %errorLevel%:

 

NET SESSION在Windows XP x86 - Windows 8 x64上:

 

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

使用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.dll和advapi32.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中也可以工作。

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