How do I check if the current batch script has admin rights?
如何检查当前批处理脚本是否具有管理权限?
I know how to make it call itself with runas but not how to check for admin rights. The only solutions I've seen are crude hack jobs or use external programs. Well, actually I don't care if it is a hack job as long as it works on Windows XP and newer.
我知道如何用runas进行调用,但不知道如何检查管理权限。我所看到的唯一解决方案是粗糙的hack作业或使用外部程序。实际上,我并不介意它是一份黑客工作,只要它在Windows XP和更新版本上运行。
26 个解决方案
#1
369
Issues
blak3r / Rushyo's solution works fine for everything except Windows 8. Running AT
on Windows 8 results in:
blak3r / Rushyo的解决方案适用于除Windows 8之外的一切。Windows 8的运行结果如下:
The AT command has been deprecated. Please use schtasks.exe instead.
The request is not supported.
(see screenshot #1) and will return %errorLevel%
1
.
(见截图#1)并返回%errorLevel% 1。
Research
So, I went searching for other commands that require elevated permissions. rationallyparanoid.com had a list of a few, so I ran each command on the two opposite extremes of current Windows OSs (XP and 8) in the hopes of finding a command that would be denied access on both OSs when run with standard permissions.
因此,我搜索了其他需要提升权限的命令。“rationallyparanoid.com”有一个列表,所以我在当前Windows操作系统(XP和8)的两个极端上运行每个命令,希望找到一个命令,在使用标准权限运行时,两个OSs都无法访问。
Eventually, I did find one - NET SESSION
. A true, clean, universal solution that doesn't involve:
最后,我确实找到了一个网络会话。一个真实、干净、通用的解决方案,不涉及:
- the creation of or interaction with data in secure locations
- 在安全位置创建或交互数据。
- analyzing data returned from
FOR
loops - 分析从FOR循环返回的数据。
- searching strings for "Administrator"
- 搜索字符串“管理员”
- using
AT
(Windows 8 incompatible) orWHOAMI
(Windows XP incompatible). - 使用AT (Windows 8不兼容)或WHOAMI (Windows XP不兼容)。
Each of which have their own security, usability, and portability issues.
每一个都有自己的安全性、可用性和可移植性问题。
Testing
I've independently confirmed that this works on:
我已经独立地证实了这一点:
- Windows XP, x86
- Windows XP,x86
- Windows XP, x64
- Windows XP,x64
- Windows Vista, x86
- Windows Vista,x86
- Windows Vista, x64
- Windows Vista,x64
- Windows 7, x86
- Windows 7,x86
- Windows 7, x64
- Windows 7,x64
- Windows 8, x86
- Windows 8,x86
- Windows 8, x64
- Windows 8,x64
(see screenshot #2)
(见截图# 2)
Implementation / Usage
So, to use this solution, simply do something like this:
因此,要使用这个解决方案,只需做如下的事情:
@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
Available here, if you're lazy: https://dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat
如果您很懒,可以在这里使用:https://dl.l.l.l.l.l.l.l.a.u/27573003/distribution/binaries/check_permissions.bat。
Explanation
NET SESSION
is a standard command used to "manage server computer connections. Used without parameters, [it] displays information about all sessions with the local computer."
NET会话是用于“管理服务器计算机连接”的标准命令。在没有参数的情况下,[它]显示有关所有会话与本地计算机的信息。
So, here's the basic process of my given implementation:
下面是我给出的实现的基本过程:
-
@echo off
- Disable displaying of commands
- 禁用显示的命令
- @echo关闭命令的显示。
-
goto check_Permissions
- Jump to the
:check_Permissions
code block - 跳转到:check_Permissions代码块。
- Jump to the
- goto check_Permissions跳转到:check_Permissions代码块。
-
net session >nul 2>&1
- Run command
- 运行命令
- Hide visual output of command by
- Redirecting the standard output (numeric handle 1 /
STDOUT
) stream tonul
- 将标准输出(数字句柄1 / STDOUT)重定向到nul。
- Redirecting the standard error output stream (numeric handle 2 /
STDERR
) to the same destination as numeric handle 1 - 将标准错误输出流(数字句柄2 / STDERR)重定向到与数字句柄1相同的目的地。
- Redirecting the standard output (numeric handle 1 /
- 通过将标准输出(数字句柄1 / STDOUT)重定向到nul,将标准输出流(数字句柄2 / STDERR)重定向到与数字句柄1相同的目的地,从而隐藏命令的可视化输出。
- 通过将标准输出(数字句柄1 / STDOUT)重定向到nul,将标准错误输出流(数字句柄2 / STDERR)重定向到与数字句柄1相同的目标,从而隐藏了命令的可视化输出。
-
if %errorLevel% == 0
- If the value of the exit code (
%errorLevel%
) is0
then this means that no errors have occurred and, therefore, the immediate previous command ran successfully - 如果退出代码的值(%errorLevel%)是0,那么这意味着没有发生错误,因此,前面的命令运行成功。
- If the value of the exit code (
- 如果%errorLevel% == 0,如果退出代码的值(%errorLevel%)是0,那么这意味着没有发生错误,因此,前面的命令运行成功。
-
else
- If the value of the exit code (
%errorLevel%
) is not0
then this means that errors have occurred and, therefore, the immediate previous command ran unsuccessfully - 如果退出代码的值(%errorLevel%)不是0,那么这意味着错误已经发生,因此,前面的命令运行失败。
- If the value of the exit code (
- 如果退出代码的值(%errorLevel%)不是0,那么这意味着错误已经发生,因此,前面的命令运行失败。
- The code between the respective parenthesis will be executed depending on which criteria is met
- 每个括号之间的代码将根据所满足的标准执行。
Screenshots
Windows 8在%返回码%:
NET SESSION
on Windows XP x86 - Windows 8 x64:
Windows XP x86 - Windows 8 x64的网络会话:
Thank you, @Tilka, for changing your accepted answer to mine. :)
谢谢你,@Tilka,改变你接受我的答案。:)
#2
68
Anders solution worked for me but I wasn't sure how to invert it to get the opposite (when you weren't an admin).
安德斯解决方案为我工作,但我不知道如何反转它来得到相反的结果(当你不是管理员的时候)。
Here's my solution. It has two cases an IF and ELSE case, and some ascii art to ensure people actually read it. :)
这是我的解决方案。它有两个案例,一个IF和ELSE case,以及一些ascii艺术,以确保人们真正读到它。:)
Minimal Version
Rushyo posted this solution here: How to detect if CMD is running as Administrator/has elevated privileges?
Rushyo在这里发布了这个解决方案:如何检测CMD是否以管理员身份运行?
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator PRIVILEGES Detected!
) ELSE (
ECHO NOT AN ADMIN!
)
Version which adds an Error Messages, Pauses, and Exits
@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
Works on WinXP --> Win8 (including 32/64 bit versions).
适用于WinXP——> Win8(包括32/64位版本)。
EDIT: 8/28/2012 Updated to support Windows 8. @BenHooper pointed this out in his answer below. Please upvote his answer.
编辑:8/28/2012更新支持Windows 8。@BenHooper在下面的回答中指出了这一点。请upvote他的答案。
#3
32
More issues
As pointed out by @Lectrode, if you try to run the net session
command while the Server service is stopped, you receive the following error message:
如@Lectrode所指出的,如果在停止服务器服务时尝试运行net会话命令,则会收到以下错误消息:
The Server service is not started.
More help is available by typing NET HELPMSG 2114
In this case the %errorLevel%
variable will be set to 2
.
在这种情况下,%errorLevel%变量将被设置为2。
Note The Server service is not started while in Safe Mode (with or without networking).
注意,在安全模式下(有或没有网络),服务器服务不会启动。
Looking for an alternative
Something that:
的东西:
- can be run out of the box on Windows XP and later (32 and 64 bit);
- 可以在Windows XP和之后的(32和64位)上运行。
- doesn't touch the registry or any system file/folder;
- 不触及注册表或任何系统文件/文件夹;
- works regardless of the system locale;
- 不考虑系统区域设置;
- gives correct results even in Safe Mode.
- 即使在安全模式下也能给出正确的结果。
So I booted a vanilla Windows XP virtual machine and I started scrolling through the list of applications in the C:\Windows\System32
folder, trying to get some ideas. After trials and errors, this is the dirty (pun intended) approach I've come up with:
我启动一个香草Windows XP虚拟机和我开始滚动的列表应用程序C:\Windows\System32文件夹,试图得到一些想法。经过试验和错误,这是我提出的肮脏的(双关语)方法:
fsutil dirty query %systemdrive% >nul
The fsutil dirty
command requires admin rights to run, and will fail otherwise. %systemdrive%
is an environment variable which returns the drive letter where the operating system is installed. The output is redirected to nul
, thus ignored. The %errorlevel%
variable will be set to 0
only upon successful execution.
fsutil脏命令需要管理权限才能运行,否则将会失败。%systemdrive%是一个环境变量,它返回安装操作系统的驱动器号。输出被重定向到nul,因此被忽略。只有在成功执行后,%errorlevel%变量将被设置为0。
Here is what the documentation says:
以下是文件的内容:
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.
查询或设置卷的脏位。当设置一个卷的脏位时,autochk将在下一次重新启动计算机时自动检查卷中的错误。
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.
如果在计算机重新启动时设置了脏位,chkdsk将运行验证文件系统的完整性,并尝试修复与卷的任何问题。
Examples
To query the dirty bit on drive C, type:
查询驱动器C上的脏位,键入:
fsutil dirty query C:
Further research
While the solution above works from Windows XP onwards, it's worth adding that Windows 2000 and Windows PE (Preinstalled Environment) don't come with fsutil.exe
, so we have to resort to something else.
虽然上面的解决方案从Windows XP开始,但值得补充的是,Windows 2000和Windows PE(预装环境)不会与fsutil一起出现。exe,所以我们不得不求助于别的东西。
During my previous tests I noticed that running the sfc
command without any parameters would either result in:
在之前的测试中,我注意到没有任何参数运行sfc命令会导致:
- an error, if you didn't have enough privileges;
- 一个错误,如果你没有足够的特权;
- a list of the available parameters and their usage.
- 可用参数的列表及其用法。
That is: no parameters, no party. The idea is that we can parse the output and check if we got anything but an error:
那就是:没有参数,没有聚会。我们的想法是,我们可以解析输出,并检查是否有错误:
sfc 2>&1 | find /i "/SCANNOW" >nul
The error output is first redirected to the standard output, which is then piped to the find
command. At this point we have to look for the only parameter that is supported in all Windows version since Windows 2000: /SCANNOW
. The search is case insensitive, and the output is discarded by redirecting it to nul
.
错误输出首先被重定向到标准输出,然后用管道传输到find命令。此时,我们必须寻找自Windows 2000以来所有Windows版本中唯一支持的参数:/SCANNOW。搜索是不区分大小写的,并且通过将其重定向到nul来丢弃输出。
Here's an excerpt from the documentation:
以下是文件摘录:
Sfc
Scans and verifies the integrity of all protected system files and replaces incorrect versions with correct versions.
扫描并验证所有受保护系统文件的完整性,并使用正确的版本替换错误的版本。
Remarks
You must be logged on as a member of the Administrators group to run sfc.exe.
您必须作为管理员组的成员登录以运行sfc.exe。
Sample Usage
Here are some paste-and-run examples:
这里有一些经过了巴斯德和运行的例子:
Windows XP and later
@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
Applies to
- Windows 2000
- Windows 2000
- Windows XP
- Windows XP
- Windows Vista
- Windows Vista
- Windows 7
- Windows 7
- Windows 8
- Windows 8
- Windows 8.1
---
- Windows 8.1 - - - - - -
- Windows PE
- Windows体育
#4
17
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"&&(
echo admin...
)
#5
15
one more way
多一个方式
fltmc >nul 2>&1 && (
echo has admin permissions
) || (
echo has NOT admin permissions
)
fltmc
command is available on every windows system since XP so this should be pretty portable.
在每个windows系统上都可以使用fltmc命令,因为这应该是非常便携的。
One more solution tested on XP
,8.1
,7
(unfortunately does not work on all win10
machines - see the comments.) - there's one specific variable =::
which is presented only if the console session has no admin privileges.As it is not so easy to create variable that contains =
in it's name this is comparatively reliable way to check for admin permission (and pretty fast as it does not call external executables)
在XP、8.1、7(不幸的是,在所有win10机器上都没有工作)的另一个解决方案——参见注释。)——只有一个特定的变量=::只有在控制台会话没有管理员权限的情况下才会显示。因为创建包含=的变量不是那么容易,所以这是检查管理权限的比较可靠的方法(而且非常快,因为它不调用外部可执行文件)
setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! (
echo has NOT admin permissions
) else (
echo has admin permissions
)
#6
11
alternative solution:
可选择的解决方案:
@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
Not only check but GETTING admin rights automatically
aka Automatic UAC for Win 7/8/8.1 ff.: The following is a really cool one with one more feature: This batch snippet does not only check for admin rights, but gets them automatically! (and tests before, if living on an UAC capable OS.)
不仅可以检查,而且还可以自动地获得管理权限,也就是自动的UAC,获得7/8/8.1 ff。以下是一个非常酷的功能:这批代码片段不仅检查了管理员权限,还自动获取了它们!(如果是在UAC有能力的操作系统上的话,也要测试一下。)
With this trick you don´t need longer to right klick on your batch file "with admin rights". If you have forgotten, to start it with elevated rights, UAC comes up automatically! Moreoever, at first it is tested, if the OS needs/provides UAC, so it behaves correct e.g. for Win 2000/XP until Win 8.1- tested.
有了这个技巧,你就不需要在你的批处理文件“有管理权限”上花更长的时间了。如果你忘记了,用高升的权利启动它,UAC会自动出现!而且,如果OS需要/提供UAC,那么它的行为是正确的,例如,在赢得2000/XP的时候,直到win8.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
)
The snippet merges some good batch patterns together, especially (1) the admin test in this thread by Ben Hooper and (2) the UAC activation read on BatchGotAdmin and cited on the batch site by robvanderwoude (respect). (3) For the OS identificaton by "VER | FINDSTR pattern" I just don't find the reference.)
这段代码合并了一些好的批处理模式,特别是(1)Ben Hooper和(2)在BatchGotAdmin中读取的UAC激活,以及robvanderwoude (respect)在批处理站点上引用的UAC激活。(3)对于“VER | FINDSTR模式”的OS标识,我只是找不到参考。
(Concerning some very minor restrictions, when "NET SESSION" do not work as mentioned in another answer- feel free to insert another of those commands. For me running in Windows safe mode or special standard services down and such are not an important use cases- for some admins maybe they are.)
(关于一些非常小的限制,当“NET会话”不像另一个答案中提到的那样工作时,请随意插入另一个命令。对我来说,运行Windows安全模式或特殊标准服务并不是一个重要的用例——对于一些管理员来说可能是这样。
#8
9
I have two ways of checking for privileged access, both are pretty reliable, and very portable across almost every windows version.
我有两种检查特权访问的方法,它们都非常可靠,而且在几乎所有的windows版本中都非常方便。
1. Method
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!
)
This is one of the most reliable methods, because of its simplicity, and the behavior of this very primitive command is very unlikely to change. That is not the case of other built-in CLI tools like net session that can be disabled by admin/network policies, or commands like fsutils that changed the output on Windows 10.
这是最可靠的方法之一,因为它的简单性,并且这种非常原始的命令的行为不太可能改变。这不是其他内置CLI工具的情况,比如可以通过管理/网络策略禁用的网络会话,或者像fsutils这样的命令,这些命令改变了Windows 10的输出。
* Works on XP and later
*在XP和以后工作。
2. Method
REG ADD HKLM /F>nul 2>&1
IF %ERRORLEVEL%==0 (
ECHO PRIVILEGED!
) ELSE (
ECHO NOT PRIVILEGED!
)
Sometimes you don't like the idea of touching the user disk, even if it is as inoffensive as using fsutils or creating a empty folder, is it unprovable but it can result in a catastrophic failure if something goes wrong. In this scenario you can just check the registry for privileges.
有时您不喜欢触摸用户磁盘,即使它像使用fsutils或创建一个空文件夹一样不令人讨厌,但它是无法证明的,但如果出现问题,它可能导致灾难性的失败。在这个场景中,您可以检查注册表中的特权。
For this you can try to create a key on HKEY_LOCAL_MACHINE using default permissions you'll get Access Denied and the
ERRORLEVEL == 1
, but if you run as Admin, it will print "command executed successfully" andERRORLEVEL == 0
. Since the key already exists it have no effect on the registry. This is probably the fastest way, and the REG is there for a long time.为此,您可以尝试使用默认权限在HKEY_LOCAL_MACHINE上创建一个密钥,您将访问被拒绝的权限和ERRORLEVEL == 1,但是如果您以Admin的身份运行,它将打印“成功执行的命令”和ERRORLEVEL == 0。由于密钥已经存在,所以它对注册表没有影响。这可能是最快的方法,而且雷格在那里已经很长时间了。
* It's not avaliable on pre NT (Win 9X).
在NT (Win 9X)之前是不可用的。
* Works on XP and later
*在XP和以后工作。
Working example
A script that clear the temp folder
清除临时文件夹的脚本。
@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
#9
5
The following tries to create a file in the Windows directory. If it suceeds it will remove it.
下面尝试在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
Note that 06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 is a GUID that was generated today and it is assumed to be improbable to conflict with an existing filename.
注意,06CF2EB6-94E6-4a60-91D8-AB945AE8CF38是今天生成的一个GUID,假定它不可能与现有的文件名发生冲突。
#10
5
The cleanest way to check for admin privileges using a CMD script, that I have found, is something like this:
我发现,使用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
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.
此方法仅使用CMD。exe内置的,所以应该很快。它还检查流程的实际功能,而不是检查SIDs或组成员身份,因此测试了有效的权限。这可以追溯到Windows 2003和XP。正常的用户进程或非提升进程失败了目录探针,在其中,管理或提升过程成功。
#11
3
The whoami /groups doesn't work in one case. If you have UAC totally turned off (not just notification turned off), and you started from an Administrator prompt then issued:
whoami /组在一个例子中不起作用。如果您的UAC完全关闭(不只是通知关闭),并且您从一个管理员提示开始,然后发出:
runas /trustlevel:0x20000 cmd
you will be running non-elevated, but issuing:
您将运行非提升,但发行:
whoami /groups
will say you're elevated. It's wrong. Here's why it's wrong:
会说你升高。这是错误的。这就是为什么它是错误的:
When running in this state, if IsUserAdmin (https://msdn.microsoft.com/en-us/library/windows/desktop/aa376389(v=vs.85).aspx) returns FALSE and UAC is fully disabled, and GetTokenInformation returns TokenElevationTypeDefault (http://blogs.msdn.com/b/cjacks/archive/2006/10/24/modifying-the-mandatory-integrity-level-for-a-securable-object-in-windows-vista.aspx) then the process is not running elevated, but whoami /groups
claims it is.
当在这个状态下运行时,如果IsUserAdmin (https://msdn.microsoft.com/en-us/library/windows/desktop/aa376389(v=vs.85),返回FALSE和UAC是完全禁用的,并且GetTokenInformation返回TokenElevationTypeDefault (http://blogs.msdn.com/b/cjacks/archive/2006/10/24/modifying- on -window -vista.aspx),那么这个过程并没有被提升,但是whoami /组声称它是。
really, the best way to do this from a batch file is:
实际上,从批处理文件中做到这一点的最好方法是:
net session >nul 2>nul
net session >nul 2>nul
echo %errorlevel%
You should do net session
twice because if someone did an at
before hand, you'll get the wrong information.
你应该做两次网络会话,因为如果有人在你之前做了一件事,你会得到错误的信息。
#12
2
whoami /groups | find "S-1-16-12288" > nul
if not errorlevel 1 (
echo ... connected as admin
)
#13
2
Some servers disable services that the command "net session" requires. This results in the admin check always saying you don't have admin rights when you may have.
有些服务器禁用了命令“net会话”所需要的服务。这导致管理员检查总是说,您可能没有管理员权限。
#14
2
Edit: copyitright has pointed out that this is unreliable. Approving read access with UAC will allow dir to succeed. I have a bit more script to offer another possibility, but it's not read-only.
编辑: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
Old answer below
老回答下面
Warning: unreliable
警告:不可靠
Based on a number of other good answers here and points brought up by and31415 I found that I am a fan of the following:
在此基础上,我找到了许多其他的好答案,并指出我是以下几点的粉丝:
dir "%SystemRoot%\System32\config\DRIVERS" 2>nul >nul || echo Not Admin
Few dependencies and fast.
一些依赖项和快速。
#15
1
Note: Checking with cacls for \system32\config\system will ALWAYS fail in WOW64, (for example from %systemroot%\syswow64\cmd.exe / 32 bit Total Commander) so scripts that run in 32bit shell in 64bit system will loop forever... Better would be checking for rights on Prefetch directory:
注意:在WOW64中,用cacls检查\system32\config\系统总是会失败(例如%systemroot%\syswow64\cmd)。exe / 32位总指挥官)所以在64位系统中运行32位shell的脚本将永远循环……更好的方法是检查预取目录的权限:
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\Prefetch\"
Win XP to 7 tested, however it fails in WinPE as in windows 7 install.wim there is no such dir nor cacls.exe
Win XP到7测试,但是它在WinPE失败,就像windows 7安装。没有这样的处所,也没有仙人掌。
Also in winPE AND wow64 fails check with openfiles.exe :
同样在winPE和wow64中,也不能检查openfiles。exe:
OPENFILES > nul
In Windows 7 it will errorlevel with "1" with info that "Target system needs to be 32bit operating system"
在Windows 7中,它将在“1”和“目标系统需要32位操作系统”的信息中出错。
Both check will probably also fail in recovery console.
这两种检查在恢复控制台可能也会失败。
What works in Windows XP - 8 32/64 bit, in WOW64 and in WinPE are: dir creation tests (IF admin didn't carpet bombed Windows directory with permissions for everyone...) and
在Windows XP - 8 32/64位,WOW64和WinPE的工作是:dir创建测试(如果admin没有对每个人都有权限的Windows目录),并且!
net session
and
和
reg add HKLM /F
checks.
检查。
Also one more note in some windows XP (and other versions probably too, depending on admin's tinkering) depending on registry entries directly calling bat/cmd from .vbs script will fail with info that bat/cmd files are not associated with anything...
另外,在一些windows XP(以及其他版本可能也是如此,取决于管理员的修改),取决于注册表项直接调用bat/cmd from .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
Calling cmd.exe with parameter of bat/cmd file on the other hand works OK:
调用cmd。另一方面,exe具有bat/cmd文件的参数,可以:
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
Literally dozens of answers in this and linked questions and elsewhere at SE, all of which are deficient in this way or another, have clearly shown that Windows doesn't provide a reliable built-in console utility. So, it's time to roll out your own.
实际上,在这个问题和其他问题上的几十个答案,所有这些都有缺陷,都清楚地表明Windows并没有提供一个可靠的内置控制台实用程序。所以,是时候推出你自己的了。
The following C code, based on Detect if program is running with full administrator rights, works in Win2k+1, anywhere and in all cases (UAC, domains, transitive groups...) - because it does the same as the system itself when it checks permissions. It signals of the result both with a message (that can be silenced with a switch) and exit code.
下面的C代码基于检测程序是否具有完全的管理员权限,在Win2k+1中工作,在任何地方(UAC、域、传递组…)中,因为它在检查权限时与系统本身相同。它通过一个消息(可以用一个开关来保持沉默)和退出代码来表示结果。
It only needs to be compiled once, then you can just copy the .exe
everywhere - it only depends on kernel32.dll
and advapi32.dll
(I've uploaded a copy).
它只需要编译一次,然后就可以在任何地方复制.exe—它只依赖于kernel32。dll和advapi32。dll(我上传了一个副本)。
chkadmin.c
:
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 claims the APIs are XP+ but this is false. CheckTokenMembership
is 2k+ and the other one is even older. The last link also contains a much more complicated way that would work even in NT.
1MSDN声称api是XP+,但这是错误的。CheckTokenMembership是2k+,另一个甚至更老。最后一个链接也包含了一个更复杂的方法,即使在NT中也是如此。
#17
1
PowerShell anyone?
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
Here is another one to add to the list ;-)
这里是另一个添加到列表中的;-)
(attempt a file creation in system location)
(尝试在系统位置创建文件)
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
)
The MODE CON
reinitializes the screen and surpresses any text/errors when not having the permission to write to the system location.
当没有权限写入系统位置时,模式可以重新初始化屏幕并克服任何文本/错误。
#19
0
Alternative: Use an external utility that is designed for this purpose, e.g., IsAdmin.exe (unrestricted freeware).
备选:使用为这个目的而设计的外部实用程序,例如IsAdmin。exe(无限制免费)。
Exit codes:
退出代码:
0 - Current user not member of Administrators group
0 -当前用户不是管理员组的成员。
1 - Current user member of Administrators and running elevated
1 -当前管理员用户名,运行提升。
2 - Current user member of Administrators, but not running elevated
2 -当前管理员用户,但不运行高架。
#20
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...
#21
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
I will explain the code line by line:
我将逐行解释代码:
@echo off
Users will be annoyed with many more than 1 lines without this.
如果没有这个,用户将会被超过1行代码所困扰。
:start
Point where the program starts.
点,程序启动。
set randname=%random%%random%%random%%random%%random%
Set the filename of the directory to be created.
设置要创建的目录的文件名。
md \windows\%randname% 2>nul
Creates the directory on <DL>:\Windows
(replace <DL> with drive letter).
创建
-
:\Windows(用驱动字母替换
-
)的目录。
if %errorlevel%==0 (echo You're elevated!!!
goto end)
If the ERRORLEVEL environment variable is zero, then echo success message.
Go to the end (don't proceed any further).
如果ERRORLEVEL环境变量为0,则返回成功消息。走到终点(不要再往前走)。
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)
If ERRORLEVEL is one, echo failure message and go to the end.
如果ERRORLEVEL为1,则返回失败消息并进行到末尾。
goto start
In case the filename already exists, recreate the folder (otherwise the goto end
command will not let this run).
如果文件名已经存在,重新创建文件夹(否则goto end命令将不会让此运行)。
:end
Specify the ending point
指定终点
rd \windows\%randname% 2>nul
Remove the created directory.
删除创建的目录。
pause >nul
Pause so the user can see the message.
暂停,这样用户就可以看到消息了。
Note: The >nul
and 2>nul
are filtering the output of these commands.
注意:>nul和2>nul正在过滤这些命令的输出。
#22
0
net user %username% >nul 2>&1 && echo admin || echo not admin
用户的用户名% >nul 2> && & echo admin || echo而不是admin。
#23
0
I think the simplest way is trying to change the system date (that requires admin rights):
我认为最简单的方法是尝试更改系统日期(这需要管理权限):
date %date%
if errorlevel 1 (
echo You have NOT admin rights
) else (
echo You have admin rights
)
If %date%
variable may include the day of week, just get the date from last part of DATE
command:
如果%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 ...
#24
0
I found a user that can use net session
even though they are not admin. I didn't look into why. My workaround is to test if the user can make a folder in the windows folder.
我发现一个用户可以使用net会话,即使他们不是管理员。我没有调查原因。我的工作是测试用户是否可以在windows文件夹中创建一个文件夹。
Here is my code:
这是我的代码:
::::::: :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 ::::::
#25
-1
Here's my 2-pennies worth:
这是我的2便士的价值:
I needed a batch to run within a Domain environment during the user login process, within a 'workroom' environment, seeing users adhere to a "lock-down" policy and restricted view (mainly distributed via GPO sets).
我需要在用户登录过程中在一个域环境中运行一个批处理,在“工作空间”环境中,看到用户坚持“锁定”策略和受限视图(主要通过GPO集合进行分发)。
A Domain GPO set is applied before an AD user linked login script Creating a GPO login script was too per-mature as the users "new" profile hadn't been created/loaded/or ready in time to apply a "remove and/or Pin" taskbar and Start Menu items vbscript + add some local files.
一个域GPO集是在一个AD用户链接的登录脚本创建一个GPO登录脚本之前被应用的,因为用户的“新”配置文件没有被创建/加载/或准备好及时应用一个“删除和/或Pin”任务栏和开始菜单项vbscript +添加一些本地文件。
e.g.: The proposed 'default-user' profile environment requires a ".URL' (.lnk) shortcut placed within the "%ProgramData%\Microsoft\Windows\Start Menu\Programs*MyNewOWA.url*", and the "C:\Users\Public\Desktop\*MyNewOWA.url*" locations, amongst other items
例:提议的“默认用户”配置文件环境需要“。URL' (.lnk)快捷方式放置在“%ProgramData%\Microsoft\Windows\开始菜单\程序*MyNewOWA”中。url *”和“C:\ \公共桌面\ \ * MyNewOWA用户。url*“位置,以及其他项目。
The users have multiple machines within the domain, where only these set 'workroom' PCs require these policies.
用户在域中有多个机器,只有这些设置的“工作区”pc需要这些策略。
These folders require 'Admin' rights to modify, and although the 'Domain User' is part of the local 'Admin' group - UAC was the next challenge.
这些文件夹需要“管理员”权限来修改,尽管“域用户”是本地“Admin”组的一部分,但UAC是下一个挑战。
Found various adaptations and amalgamated here. I do have some users with BYOD devices as well that required other files with perm issues. Have not tested on XP (a little too old an OS), but the code is present, would love feed back.
在这里发现了各种各样的适应和融合。我确实有一些使用BYOD设备的用户,也需要使用perm问题的其他文件。没有在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
Domain PC's should be governed as much as possible by GPO sets. Workgroup/Standalone machines can be governed by this script.
域PC应该尽可能地由GPO集合管理。工作组/独立机器可以受此脚本控制。
Remember, a UAC prompt will pop-up at least once with a BYOD workgroup PC (as soon as the first elevating to 'Admin perms' is required), but as the local security policy is modified for admin use from this point on, the pop-ups will disappear.
请记住,UAC提示符至少有一次会弹出一个BYOD工作组PC(当第一个提升到“Admin perms”时),但是随着本地安全策略从这一点修改为Admin使用,弹出窗口将会消失。
A Domain PC should have the GPO "ConsentPromptBehaviorAdmin" policy set within your 'already' created "Lock-down" policy - as explained in the script 'REFERENCES' section.
域PC应该在您的“已经”创建的“锁定”策略中设置GPO“consentpromptactions”策略,正如在脚本“引用”部分中所解释的那样。
Again, run the secedit.exe import of the default '.inf' file if you are stuck on the whole "To UAC or Not to UAC" debate :-).
再次运行secedit。exe导入默认值。inf' file如果你被困在整个“UAC或不UAC”辩论:-)。
btw: @boileau Do check your failure on the:
@boileau检查你的失败:
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
By running only "%SYSTEMROOT%\system32\cacls.exe" or "%SYSTEMROOT%\system32\config\system" or both from the command prompt - elevated or not, check the result across the board.
只通过运行“% SYSTEMROOT % \ system32系统\ cacls。或者“%SYSTEMROOT%\system32\config\system”,或者从命令提示符(不管是否升高),检查结果是否全面。
#26
-2
Another way to do this.
另一种方法。
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 ...
#1
369
Issues
blak3r / Rushyo's solution works fine for everything except Windows 8. Running AT
on Windows 8 results in:
blak3r / Rushyo的解决方案适用于除Windows 8之外的一切。Windows 8的运行结果如下:
The AT command has been deprecated. Please use schtasks.exe instead.
The request is not supported.
(see screenshot #1) and will return %errorLevel%
1
.
(见截图#1)并返回%errorLevel% 1。
Research
So, I went searching for other commands that require elevated permissions. rationallyparanoid.com had a list of a few, so I ran each command on the two opposite extremes of current Windows OSs (XP and 8) in the hopes of finding a command that would be denied access on both OSs when run with standard permissions.
因此,我搜索了其他需要提升权限的命令。“rationallyparanoid.com”有一个列表,所以我在当前Windows操作系统(XP和8)的两个极端上运行每个命令,希望找到一个命令,在使用标准权限运行时,两个OSs都无法访问。
Eventually, I did find one - NET SESSION
. A true, clean, universal solution that doesn't involve:
最后,我确实找到了一个网络会话。一个真实、干净、通用的解决方案,不涉及:
- the creation of or interaction with data in secure locations
- 在安全位置创建或交互数据。
- analyzing data returned from
FOR
loops - 分析从FOR循环返回的数据。
- searching strings for "Administrator"
- 搜索字符串“管理员”
- using
AT
(Windows 8 incompatible) orWHOAMI
(Windows XP incompatible). - 使用AT (Windows 8不兼容)或WHOAMI (Windows XP不兼容)。
Each of which have their own security, usability, and portability issues.
每一个都有自己的安全性、可用性和可移植性问题。
Testing
I've independently confirmed that this works on:
我已经独立地证实了这一点:
- Windows XP, x86
- Windows XP,x86
- Windows XP, x64
- Windows XP,x64
- Windows Vista, x86
- Windows Vista,x86
- Windows Vista, x64
- Windows Vista,x64
- Windows 7, x86
- Windows 7,x86
- Windows 7, x64
- Windows 7,x64
- Windows 8, x86
- Windows 8,x86
- Windows 8, x64
- Windows 8,x64
(see screenshot #2)
(见截图# 2)
Implementation / Usage
So, to use this solution, simply do something like this:
因此,要使用这个解决方案,只需做如下的事情:
@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
Available here, if you're lazy: https://dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat
如果您很懒,可以在这里使用:https://dl.l.l.l.l.l.l.l.a.u/27573003/distribution/binaries/check_permissions.bat。
Explanation
NET SESSION
is a standard command used to "manage server computer connections. Used without parameters, [it] displays information about all sessions with the local computer."
NET会话是用于“管理服务器计算机连接”的标准命令。在没有参数的情况下,[它]显示有关所有会话与本地计算机的信息。
So, here's the basic process of my given implementation:
下面是我给出的实现的基本过程:
-
@echo off
- Disable displaying of commands
- 禁用显示的命令
- @echo关闭命令的显示。
-
goto check_Permissions
- Jump to the
:check_Permissions
code block - 跳转到:check_Permissions代码块。
- Jump to the
- goto check_Permissions跳转到:check_Permissions代码块。
-
net session >nul 2>&1
- Run command
- 运行命令
- Hide visual output of command by
- Redirecting the standard output (numeric handle 1 /
STDOUT
) stream tonul
- 将标准输出(数字句柄1 / STDOUT)重定向到nul。
- Redirecting the standard error output stream (numeric handle 2 /
STDERR
) to the same destination as numeric handle 1 - 将标准错误输出流(数字句柄2 / STDERR)重定向到与数字句柄1相同的目的地。
- Redirecting the standard output (numeric handle 1 /
- 通过将标准输出(数字句柄1 / STDOUT)重定向到nul,将标准输出流(数字句柄2 / STDERR)重定向到与数字句柄1相同的目的地,从而隐藏命令的可视化输出。
- 通过将标准输出(数字句柄1 / STDOUT)重定向到nul,将标准错误输出流(数字句柄2 / STDERR)重定向到与数字句柄1相同的目标,从而隐藏了命令的可视化输出。
-
if %errorLevel% == 0
- If the value of the exit code (
%errorLevel%
) is0
then this means that no errors have occurred and, therefore, the immediate previous command ran successfully - 如果退出代码的值(%errorLevel%)是0,那么这意味着没有发生错误,因此,前面的命令运行成功。
- If the value of the exit code (
- 如果%errorLevel% == 0,如果退出代码的值(%errorLevel%)是0,那么这意味着没有发生错误,因此,前面的命令运行成功。
-
else
- If the value of the exit code (
%errorLevel%
) is not0
then this means that errors have occurred and, therefore, the immediate previous command ran unsuccessfully - 如果退出代码的值(%errorLevel%)不是0,那么这意味着错误已经发生,因此,前面的命令运行失败。
- If the value of the exit code (
- 如果退出代码的值(%errorLevel%)不是0,那么这意味着错误已经发生,因此,前面的命令运行失败。
- The code between the respective parenthesis will be executed depending on which criteria is met
- 每个括号之间的代码将根据所满足的标准执行。
Screenshots
Windows 8在%返回码%:
NET SESSION
on Windows XP x86 - Windows 8 x64:
Windows XP x86 - Windows 8 x64的网络会话:
Thank you, @Tilka, for changing your accepted answer to mine. :)
谢谢你,@Tilka,改变你接受我的答案。:)
#2
68
Anders solution worked for me but I wasn't sure how to invert it to get the opposite (when you weren't an admin).
安德斯解决方案为我工作,但我不知道如何反转它来得到相反的结果(当你不是管理员的时候)。
Here's my solution. It has two cases an IF and ELSE case, and some ascii art to ensure people actually read it. :)
这是我的解决方案。它有两个案例,一个IF和ELSE case,以及一些ascii艺术,以确保人们真正读到它。:)
Minimal Version
Rushyo posted this solution here: How to detect if CMD is running as Administrator/has elevated privileges?
Rushyo在这里发布了这个解决方案:如何检测CMD是否以管理员身份运行?
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
ECHO Administrator PRIVILEGES Detected!
) ELSE (
ECHO NOT AN ADMIN!
)
Version which adds an Error Messages, Pauses, and Exits
@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
Works on WinXP --> Win8 (including 32/64 bit versions).
适用于WinXP——> Win8(包括32/64位版本)。
EDIT: 8/28/2012 Updated to support Windows 8. @BenHooper pointed this out in his answer below. Please upvote his answer.
编辑:8/28/2012更新支持Windows 8。@BenHooper在下面的回答中指出了这一点。请upvote他的答案。
#3
32
More issues
As pointed out by @Lectrode, if you try to run the net session
command while the Server service is stopped, you receive the following error message:
如@Lectrode所指出的,如果在停止服务器服务时尝试运行net会话命令,则会收到以下错误消息:
The Server service is not started.
More help is available by typing NET HELPMSG 2114
In this case the %errorLevel%
variable will be set to 2
.
在这种情况下,%errorLevel%变量将被设置为2。
Note The Server service is not started while in Safe Mode (with or without networking).
注意,在安全模式下(有或没有网络),服务器服务不会启动。
Looking for an alternative
Something that:
的东西:
- can be run out of the box on Windows XP and later (32 and 64 bit);
- 可以在Windows XP和之后的(32和64位)上运行。
- doesn't touch the registry or any system file/folder;
- 不触及注册表或任何系统文件/文件夹;
- works regardless of the system locale;
- 不考虑系统区域设置;
- gives correct results even in Safe Mode.
- 即使在安全模式下也能给出正确的结果。
So I booted a vanilla Windows XP virtual machine and I started scrolling through the list of applications in the C:\Windows\System32
folder, trying to get some ideas. After trials and errors, this is the dirty (pun intended) approach I've come up with:
我启动一个香草Windows XP虚拟机和我开始滚动的列表应用程序C:\Windows\System32文件夹,试图得到一些想法。经过试验和错误,这是我提出的肮脏的(双关语)方法:
fsutil dirty query %systemdrive% >nul
The fsutil dirty
command requires admin rights to run, and will fail otherwise. %systemdrive%
is an environment variable which returns the drive letter where the operating system is installed. The output is redirected to nul
, thus ignored. The %errorlevel%
variable will be set to 0
only upon successful execution.
fsutil脏命令需要管理权限才能运行,否则将会失败。%systemdrive%是一个环境变量,它返回安装操作系统的驱动器号。输出被重定向到nul,因此被忽略。只有在成功执行后,%errorlevel%变量将被设置为0。
Here is what the documentation says:
以下是文件的内容:
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.
查询或设置卷的脏位。当设置一个卷的脏位时,autochk将在下一次重新启动计算机时自动检查卷中的错误。
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.
如果在计算机重新启动时设置了脏位,chkdsk将运行验证文件系统的完整性,并尝试修复与卷的任何问题。
Examples
To query the dirty bit on drive C, type:
查询驱动器C上的脏位,键入:
fsutil dirty query C:
Further research
While the solution above works from Windows XP onwards, it's worth adding that Windows 2000 and Windows PE (Preinstalled Environment) don't come with fsutil.exe
, so we have to resort to something else.
虽然上面的解决方案从Windows XP开始,但值得补充的是,Windows 2000和Windows PE(预装环境)不会与fsutil一起出现。exe,所以我们不得不求助于别的东西。
During my previous tests I noticed that running the sfc
command without any parameters would either result in:
在之前的测试中,我注意到没有任何参数运行sfc命令会导致:
- an error, if you didn't have enough privileges;
- 一个错误,如果你没有足够的特权;
- a list of the available parameters and their usage.
- 可用参数的列表及其用法。
That is: no parameters, no party. The idea is that we can parse the output and check if we got anything but an error:
那就是:没有参数,没有聚会。我们的想法是,我们可以解析输出,并检查是否有错误:
sfc 2>&1 | find /i "/SCANNOW" >nul
The error output is first redirected to the standard output, which is then piped to the find
command. At this point we have to look for the only parameter that is supported in all Windows version since Windows 2000: /SCANNOW
. The search is case insensitive, and the output is discarded by redirecting it to nul
.
错误输出首先被重定向到标准输出,然后用管道传输到find命令。此时,我们必须寻找自Windows 2000以来所有Windows版本中唯一支持的参数:/SCANNOW。搜索是不区分大小写的,并且通过将其重定向到nul来丢弃输出。
Here's an excerpt from the documentation:
以下是文件摘录:
Sfc
Scans and verifies the integrity of all protected system files and replaces incorrect versions with correct versions.
扫描并验证所有受保护系统文件的完整性,并使用正确的版本替换错误的版本。
Remarks
You must be logged on as a member of the Administrators group to run sfc.exe.
您必须作为管理员组的成员登录以运行sfc.exe。
Sample Usage
Here are some paste-and-run examples:
这里有一些经过了巴斯德和运行的例子:
Windows XP and later
@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
Applies to
- Windows 2000
- Windows 2000
- Windows XP
- Windows XP
- Windows Vista
- Windows Vista
- Windows 7
- Windows 7
- Windows 8
- Windows 8
- Windows 8.1
---
- Windows 8.1 - - - - - -
- Windows PE
- Windows体育
#4
17
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"&&(
echo admin...
)
#5
15
one more way
多一个方式
fltmc >nul 2>&1 && (
echo has admin permissions
) || (
echo has NOT admin permissions
)
fltmc
command is available on every windows system since XP so this should be pretty portable.
在每个windows系统上都可以使用fltmc命令,因为这应该是非常便携的。
One more solution tested on XP
,8.1
,7
(unfortunately does not work on all win10
machines - see the comments.) - there's one specific variable =::
which is presented only if the console session has no admin privileges.As it is not so easy to create variable that contains =
in it's name this is comparatively reliable way to check for admin permission (and pretty fast as it does not call external executables)
在XP、8.1、7(不幸的是,在所有win10机器上都没有工作)的另一个解决方案——参见注释。)——只有一个特定的变量=::只有在控制台会话没有管理员权限的情况下才会显示。因为创建包含=的变量不是那么容易,所以这是检查管理权限的比较可靠的方法(而且非常快,因为它不调用外部可执行文件)
setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! (
echo has NOT admin permissions
) else (
echo has admin permissions
)
#6
11
alternative solution:
可选择的解决方案:
@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
Not only check but GETTING admin rights automatically
aka Automatic UAC for Win 7/8/8.1 ff.: The following is a really cool one with one more feature: This batch snippet does not only check for admin rights, but gets them automatically! (and tests before, if living on an UAC capable OS.)
不仅可以检查,而且还可以自动地获得管理权限,也就是自动的UAC,获得7/8/8.1 ff。以下是一个非常酷的功能:这批代码片段不仅检查了管理员权限,还自动获取了它们!(如果是在UAC有能力的操作系统上的话,也要测试一下。)
With this trick you don´t need longer to right klick on your batch file "with admin rights". If you have forgotten, to start it with elevated rights, UAC comes up automatically! Moreoever, at first it is tested, if the OS needs/provides UAC, so it behaves correct e.g. for Win 2000/XP until Win 8.1- tested.
有了这个技巧,你就不需要在你的批处理文件“有管理权限”上花更长的时间了。如果你忘记了,用高升的权利启动它,UAC会自动出现!而且,如果OS需要/提供UAC,那么它的行为是正确的,例如,在赢得2000/XP的时候,直到win8.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
)
The snippet merges some good batch patterns together, especially (1) the admin test in this thread by Ben Hooper and (2) the UAC activation read on BatchGotAdmin and cited on the batch site by robvanderwoude (respect). (3) For the OS identificaton by "VER | FINDSTR pattern" I just don't find the reference.)
这段代码合并了一些好的批处理模式,特别是(1)Ben Hooper和(2)在BatchGotAdmin中读取的UAC激活,以及robvanderwoude (respect)在批处理站点上引用的UAC激活。(3)对于“VER | FINDSTR模式”的OS标识,我只是找不到参考。
(Concerning some very minor restrictions, when "NET SESSION" do not work as mentioned in another answer- feel free to insert another of those commands. For me running in Windows safe mode or special standard services down and such are not an important use cases- for some admins maybe they are.)
(关于一些非常小的限制,当“NET会话”不像另一个答案中提到的那样工作时,请随意插入另一个命令。对我来说,运行Windows安全模式或特殊标准服务并不是一个重要的用例——对于一些管理员来说可能是这样。
#8
9
I have two ways of checking for privileged access, both are pretty reliable, and very portable across almost every windows version.
我有两种检查特权访问的方法,它们都非常可靠,而且在几乎所有的windows版本中都非常方便。
1. Method
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!
)
This is one of the most reliable methods, because of its simplicity, and the behavior of this very primitive command is very unlikely to change. That is not the case of other built-in CLI tools like net session that can be disabled by admin/network policies, or commands like fsutils that changed the output on Windows 10.
这是最可靠的方法之一,因为它的简单性,并且这种非常原始的命令的行为不太可能改变。这不是其他内置CLI工具的情况,比如可以通过管理/网络策略禁用的网络会话,或者像fsutils这样的命令,这些命令改变了Windows 10的输出。
* Works on XP and later
*在XP和以后工作。
2. Method
REG ADD HKLM /F>nul 2>&1
IF %ERRORLEVEL%==0 (
ECHO PRIVILEGED!
) ELSE (
ECHO NOT PRIVILEGED!
)
Sometimes you don't like the idea of touching the user disk, even if it is as inoffensive as using fsutils or creating a empty folder, is it unprovable but it can result in a catastrophic failure if something goes wrong. In this scenario you can just check the registry for privileges.
有时您不喜欢触摸用户磁盘,即使它像使用fsutils或创建一个空文件夹一样不令人讨厌,但它是无法证明的,但如果出现问题,它可能导致灾难性的失败。在这个场景中,您可以检查注册表中的特权。
For this you can try to create a key on HKEY_LOCAL_MACHINE using default permissions you'll get Access Denied and the
ERRORLEVEL == 1
, but if you run as Admin, it will print "command executed successfully" andERRORLEVEL == 0
. Since the key already exists it have no effect on the registry. This is probably the fastest way, and the REG is there for a long time.为此,您可以尝试使用默认权限在HKEY_LOCAL_MACHINE上创建一个密钥,您将访问被拒绝的权限和ERRORLEVEL == 1,但是如果您以Admin的身份运行,它将打印“成功执行的命令”和ERRORLEVEL == 0。由于密钥已经存在,所以它对注册表没有影响。这可能是最快的方法,而且雷格在那里已经很长时间了。
* It's not avaliable on pre NT (Win 9X).
在NT (Win 9X)之前是不可用的。
* Works on XP and later
*在XP和以后工作。
Working example
A script that clear the temp folder
清除临时文件夹的脚本。
@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
#9
5
The following tries to create a file in the Windows directory. If it suceeds it will remove it.
下面尝试在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
Note that 06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 is a GUID that was generated today and it is assumed to be improbable to conflict with an existing filename.
注意,06CF2EB6-94E6-4a60-91D8-AB945AE8CF38是今天生成的一个GUID,假定它不可能与现有的文件名发生冲突。
#10
5
The cleanest way to check for admin privileges using a CMD script, that I have found, is something like this:
我发现,使用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
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.
此方法仅使用CMD。exe内置的,所以应该很快。它还检查流程的实际功能,而不是检查SIDs或组成员身份,因此测试了有效的权限。这可以追溯到Windows 2003和XP。正常的用户进程或非提升进程失败了目录探针,在其中,管理或提升过程成功。
#11
3
The whoami /groups doesn't work in one case. If you have UAC totally turned off (not just notification turned off), and you started from an Administrator prompt then issued:
whoami /组在一个例子中不起作用。如果您的UAC完全关闭(不只是通知关闭),并且您从一个管理员提示开始,然后发出:
runas /trustlevel:0x20000 cmd
you will be running non-elevated, but issuing:
您将运行非提升,但发行:
whoami /groups
will say you're elevated. It's wrong. Here's why it's wrong:
会说你升高。这是错误的。这就是为什么它是错误的:
When running in this state, if IsUserAdmin (https://msdn.microsoft.com/en-us/library/windows/desktop/aa376389(v=vs.85).aspx) returns FALSE and UAC is fully disabled, and GetTokenInformation returns TokenElevationTypeDefault (http://blogs.msdn.com/b/cjacks/archive/2006/10/24/modifying-the-mandatory-integrity-level-for-a-securable-object-in-windows-vista.aspx) then the process is not running elevated, but whoami /groups
claims it is.
当在这个状态下运行时,如果IsUserAdmin (https://msdn.microsoft.com/en-us/library/windows/desktop/aa376389(v=vs.85),返回FALSE和UAC是完全禁用的,并且GetTokenInformation返回TokenElevationTypeDefault (http://blogs.msdn.com/b/cjacks/archive/2006/10/24/modifying- on -window -vista.aspx),那么这个过程并没有被提升,但是whoami /组声称它是。
really, the best way to do this from a batch file is:
实际上,从批处理文件中做到这一点的最好方法是:
net session >nul 2>nul
net session >nul 2>nul
echo %errorlevel%
You should do net session
twice because if someone did an at
before hand, you'll get the wrong information.
你应该做两次网络会话,因为如果有人在你之前做了一件事,你会得到错误的信息。
#12
2
whoami /groups | find "S-1-16-12288" > nul
if not errorlevel 1 (
echo ... connected as admin
)
#13
2
Some servers disable services that the command "net session" requires. This results in the admin check always saying you don't have admin rights when you may have.
有些服务器禁用了命令“net会话”所需要的服务。这导致管理员检查总是说,您可能没有管理员权限。
#14
2
Edit: copyitright has pointed out that this is unreliable. Approving read access with UAC will allow dir to succeed. I have a bit more script to offer another possibility, but it's not read-only.
编辑: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
Old answer below
老回答下面
Warning: unreliable
警告:不可靠
Based on a number of other good answers here and points brought up by and31415 I found that I am a fan of the following:
在此基础上,我找到了许多其他的好答案,并指出我是以下几点的粉丝:
dir "%SystemRoot%\System32\config\DRIVERS" 2>nul >nul || echo Not Admin
Few dependencies and fast.
一些依赖项和快速。
#15
1
Note: Checking with cacls for \system32\config\system will ALWAYS fail in WOW64, (for example from %systemroot%\syswow64\cmd.exe / 32 bit Total Commander) so scripts that run in 32bit shell in 64bit system will loop forever... Better would be checking for rights on Prefetch directory:
注意:在WOW64中,用cacls检查\system32\config\系统总是会失败(例如%systemroot%\syswow64\cmd)。exe / 32位总指挥官)所以在64位系统中运行32位shell的脚本将永远循环……更好的方法是检查预取目录的权限:
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\Prefetch\"
Win XP to 7 tested, however it fails in WinPE as in windows 7 install.wim there is no such dir nor cacls.exe
Win XP到7测试,但是它在WinPE失败,就像windows 7安装。没有这样的处所,也没有仙人掌。
Also in winPE AND wow64 fails check with openfiles.exe :
同样在winPE和wow64中,也不能检查openfiles。exe:
OPENFILES > nul
In Windows 7 it will errorlevel with "1" with info that "Target system needs to be 32bit operating system"
在Windows 7中,它将在“1”和“目标系统需要32位操作系统”的信息中出错。
Both check will probably also fail in recovery console.
这两种检查在恢复控制台可能也会失败。
What works in Windows XP - 8 32/64 bit, in WOW64 and in WinPE are: dir creation tests (IF admin didn't carpet bombed Windows directory with permissions for everyone...) and
在Windows XP - 8 32/64位,WOW64和WinPE的工作是:dir创建测试(如果admin没有对每个人都有权限的Windows目录),并且!
net session
and
和
reg add HKLM /F
checks.
检查。
Also one more note in some windows XP (and other versions probably too, depending on admin's tinkering) depending on registry entries directly calling bat/cmd from .vbs script will fail with info that bat/cmd files are not associated with anything...
另外,在一些windows XP(以及其他版本可能也是如此,取决于管理员的修改),取决于注册表项直接调用bat/cmd from .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
Calling cmd.exe with parameter of bat/cmd file on the other hand works OK:
调用cmd。另一方面,exe具有bat/cmd文件的参数,可以:
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
Literally dozens of answers in this and linked questions and elsewhere at SE, all of which are deficient in this way or another, have clearly shown that Windows doesn't provide a reliable built-in console utility. So, it's time to roll out your own.
实际上,在这个问题和其他问题上的几十个答案,所有这些都有缺陷,都清楚地表明Windows并没有提供一个可靠的内置控制台实用程序。所以,是时候推出你自己的了。
The following C code, based on Detect if program is running with full administrator rights, works in Win2k+1, anywhere and in all cases (UAC, domains, transitive groups...) - because it does the same as the system itself when it checks permissions. It signals of the result both with a message (that can be silenced with a switch) and exit code.
下面的C代码基于检测程序是否具有完全的管理员权限,在Win2k+1中工作,在任何地方(UAC、域、传递组…)中,因为它在检查权限时与系统本身相同。它通过一个消息(可以用一个开关来保持沉默)和退出代码来表示结果。
It only needs to be compiled once, then you can just copy the .exe
everywhere - it only depends on kernel32.dll
and advapi32.dll
(I've uploaded a copy).
它只需要编译一次,然后就可以在任何地方复制.exe—它只依赖于kernel32。dll和advapi32。dll(我上传了一个副本)。
chkadmin.c
:
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 claims the APIs are XP+ but this is false. CheckTokenMembership
is 2k+ and the other one is even older. The last link also contains a much more complicated way that would work even in NT.
1MSDN声称api是XP+,但这是错误的。CheckTokenMembership是2k+,另一个甚至更老。最后一个链接也包含了一个更复杂的方法,即使在NT中也是如此。
#17
1
PowerShell anyone?
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
Here is another one to add to the list ;-)
这里是另一个添加到列表中的;-)
(attempt a file creation in system location)
(尝试在系统位置创建文件)
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
)
The MODE CON
reinitializes the screen and surpresses any text/errors when not having the permission to write to the system location.
当没有权限写入系统位置时,模式可以重新初始化屏幕并克服任何文本/错误。
#19
0
Alternative: Use an external utility that is designed for this purpose, e.g., IsAdmin.exe (unrestricted freeware).
备选:使用为这个目的而设计的外部实用程序,例如IsAdmin。exe(无限制免费)。
Exit codes:
退出代码:
0 - Current user not member of Administrators group
0 -当前用户不是管理员组的成员。
1 - Current user member of Administrators and running elevated
1 -当前管理员用户名,运行提升。
2 - Current user member of Administrators, but not running elevated
2 -当前管理员用户,但不运行高架。
#20
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...
#21
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
I will explain the code line by line:
我将逐行解释代码:
@echo off
Users will be annoyed with many more than 1 lines without this.
如果没有这个,用户将会被超过1行代码所困扰。
:start
Point where the program starts.
点,程序启动。
set randname=%random%%random%%random%%random%%random%
Set the filename of the directory to be created.
设置要创建的目录的文件名。
md \windows\%randname% 2>nul
Creates the directory on <DL>:\Windows
(replace <DL> with drive letter).
创建
-
:\Windows(用驱动字母替换
-
)的目录。
if %errorlevel%==0 (echo You're elevated!!!
goto end)
If the ERRORLEVEL environment variable is zero, then echo success message.
Go to the end (don't proceed any further).
如果ERRORLEVEL环境变量为0,则返回成功消息。走到终点(不要再往前走)。
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)
If ERRORLEVEL is one, echo failure message and go to the end.
如果ERRORLEVEL为1,则返回失败消息并进行到末尾。
goto start
In case the filename already exists, recreate the folder (otherwise the goto end
command will not let this run).
如果文件名已经存在,重新创建文件夹(否则goto end命令将不会让此运行)。
:end
Specify the ending point
指定终点
rd \windows\%randname% 2>nul
Remove the created directory.
删除创建的目录。
pause >nul
Pause so the user can see the message.
暂停,这样用户就可以看到消息了。
Note: The >nul
and 2>nul
are filtering the output of these commands.
注意:>nul和2>nul正在过滤这些命令的输出。
#22
0
net user %username% >nul 2>&1 && echo admin || echo not admin
用户的用户名% >nul 2> && & echo admin || echo而不是admin。
#23
0
I think the simplest way is trying to change the system date (that requires admin rights):
我认为最简单的方法是尝试更改系统日期(这需要管理权限):
date %date%
if errorlevel 1 (
echo You have NOT admin rights
) else (
echo You have admin rights
)
If %date%
variable may include the day of week, just get the date from last part of DATE
command:
如果%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 ...
#24
0
I found a user that can use net session
even though they are not admin. I didn't look into why. My workaround is to test if the user can make a folder in the windows folder.
我发现一个用户可以使用net会话,即使他们不是管理员。我没有调查原因。我的工作是测试用户是否可以在windows文件夹中创建一个文件夹。
Here is my code:
这是我的代码:
::::::: :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 ::::::
#25
-1
Here's my 2-pennies worth:
这是我的2便士的价值:
I needed a batch to run within a Domain environment during the user login process, within a 'workroom' environment, seeing users adhere to a "lock-down" policy and restricted view (mainly distributed via GPO sets).
我需要在用户登录过程中在一个域环境中运行一个批处理,在“工作空间”环境中,看到用户坚持“锁定”策略和受限视图(主要通过GPO集合进行分发)。
A Domain GPO set is applied before an AD user linked login script Creating a GPO login script was too per-mature as the users "new" profile hadn't been created/loaded/or ready in time to apply a "remove and/or Pin" taskbar and Start Menu items vbscript + add some local files.
一个域GPO集是在一个AD用户链接的登录脚本创建一个GPO登录脚本之前被应用的,因为用户的“新”配置文件没有被创建/加载/或准备好及时应用一个“删除和/或Pin”任务栏和开始菜单项vbscript +添加一些本地文件。
e.g.: The proposed 'default-user' profile environment requires a ".URL' (.lnk) shortcut placed within the "%ProgramData%\Microsoft\Windows\Start Menu\Programs*MyNewOWA.url*", and the "C:\Users\Public\Desktop\*MyNewOWA.url*" locations, amongst other items
例:提议的“默认用户”配置文件环境需要“。URL' (.lnk)快捷方式放置在“%ProgramData%\Microsoft\Windows\开始菜单\程序*MyNewOWA”中。url *”和“C:\ \公共桌面\ \ * MyNewOWA用户。url*“位置,以及其他项目。
The users have multiple machines within the domain, where only these set 'workroom' PCs require these policies.
用户在域中有多个机器,只有这些设置的“工作区”pc需要这些策略。
These folders require 'Admin' rights to modify, and although the 'Domain User' is part of the local 'Admin' group - UAC was the next challenge.
这些文件夹需要“管理员”权限来修改,尽管“域用户”是本地“Admin”组的一部分,但UAC是下一个挑战。
Found various adaptations and amalgamated here. I do have some users with BYOD devices as well that required other files with perm issues. Have not tested on XP (a little too old an OS), but the code is present, would love feed back.
在这里发现了各种各样的适应和融合。我确实有一些使用BYOD设备的用户,也需要使用perm问题的其他文件。没有在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
Domain PC's should be governed as much as possible by GPO sets. Workgroup/Standalone machines can be governed by this script.
域PC应该尽可能地由GPO集合管理。工作组/独立机器可以受此脚本控制。
Remember, a UAC prompt will pop-up at least once with a BYOD workgroup PC (as soon as the first elevating to 'Admin perms' is required), but as the local security policy is modified for admin use from this point on, the pop-ups will disappear.
请记住,UAC提示符至少有一次会弹出一个BYOD工作组PC(当第一个提升到“Admin perms”时),但是随着本地安全策略从这一点修改为Admin使用,弹出窗口将会消失。
A Domain PC should have the GPO "ConsentPromptBehaviorAdmin" policy set within your 'already' created "Lock-down" policy - as explained in the script 'REFERENCES' section.
域PC应该在您的“已经”创建的“锁定”策略中设置GPO“consentpromptactions”策略,正如在脚本“引用”部分中所解释的那样。
Again, run the secedit.exe import of the default '.inf' file if you are stuck on the whole "To UAC or Not to UAC" debate :-).
再次运行secedit。exe导入默认值。inf' file如果你被困在整个“UAC或不UAC”辩论:-)。
btw: @boileau Do check your failure on the:
@boileau检查你的失败:
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
By running only "%SYSTEMROOT%\system32\cacls.exe" or "%SYSTEMROOT%\system32\config\system" or both from the command prompt - elevated or not, check the result across the board.
只通过运行“% SYSTEMROOT % \ system32系统\ cacls。或者“%SYSTEMROOT%\system32\config\system”,或者从命令提示符(不管是否升高),检查结果是否全面。
#26
-2
Another way to do this.
另一种方法。
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 ...