如何以管理员身份从 Windows 命令行运行命令?

发布于 2024-11-06 05:52:42 字数 227 浏览 0 评论 0 原文

我有一个小脚本,可以在 Windows 上为 Bazaar 执行构建和安装过程我正在管理的存储库。我尝试在 Windows shell (cmd.exe) 中以提升的管理权限运行该脚本 - 就像我右键单击它并选择“以管理员身份运行”一样,但没有使用任何需要使用图形界面的方法。

I have a small script that performs the build and install process on Windows for a Bazaar repository I'm managing. I'm trying to run the script with elevated, administrative privileges from within the Windows shell (cmd.exe)--just as if I'd right-clicked it and chosen Run as Administrator, but without using any method that requires use of the graphical interface.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

め可乐爱微笑 2024-11-13 05:52:42

您所要做的就是使用 runas 命令以管理员身份运行您的程序(有警告)。

runas /user:Administrator "cmdName parameters"

在我的例子中,请

runas /user:Administrator "cmd.exe /C %CD%\installer.cmd %CD%"

注意,您必须使用引号,否则 runas 命令将吞噬 cmd 的 switch 选项。

另请注意,管理 shell (cmd.exe) 在 C:\Windows\System32 文件夹中启动。这不是我想要的,但很容易将当前路径传递给我的安装程序,并使用绝对路径引用它。

注意:启用管理员帐户

以这种方式使用 runas 需要启用管理帐户,这在 Windows 7 或 Vista 上不是默认设置。但是,这里< /a> 是一个关于如何以三种不同方式启用它的很棒的教程:

我自己通过打开管理工具本地安全策略来启用它,然后导航到 >本地策略\安全选项并将帐户:管理帐户状态策略的值更改为“已启用”,这不是链接中显示的三种方法之一。

实现此目的的更简单方法:

C:> net user Administrator /active:yes

All you have to do is use the runas command to run your program as Administrator (with a caveat).

runas /user:Administrator "cmdName parameters"

In my case, this was

runas /user:Administrator "cmd.exe /C %CD%\installer.cmd %CD%"

Note that you must use Quotation marks, else the runas command will gobble up the switch option to cmd.

Also note that the administrative shell (cmd.exe) starts up in the C:\Windows\System32 folder. This isn't what I wanted, but it was easy enough to pass in the current path to my installer, and to reference it using an absolute path.

Caveat: Enable the admin account

Using runas this way requires the administrative account to be enabled, which is not the default on Windows 7 or Vista. However, here is a great tutorial on how to enable it, in three different ways:

I myself enabled it by opening Administrative Tools, Local Security Policy, then navigating to Local Policies\Security Options and changing the value of the Accounts: Administrative Account Status policy to Enabled, which is none of the three ways shown in the link.

An even easier way to accomplish this:

C:> net user Administrator /active:yes
如日中天 2024-11-13 05:52:42

按开始按钮。在搜索框中输入“cmd”,然后按 Ctrl+Shift+Enter

Press the start button. In the search box type "cmd", then press Ctrl+Shift+Enter

流心雨 2024-11-13 05:52:42

批处理/WSH 混合能够调用 ShellExecute 来显示 UAC 提升对话框...

@if (1==1) @if(1==0) @ELSE
@echo off&SETLOCAL ENABLEEXTENSIONS
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"||(
    cscript //E:JScript //nologo "%~f0"
    @goto :EOF
)
echo.Performing admin tasks...
REM call foo.exe
@goto :EOF
@end @ELSE
ShA=new ActiveXObject("Shell.Application")
ShA.ShellExecute("cmd.exe","/c \""+WScript.ScriptFullName+"\"","","runas",5);
@end

A batch/WSH hybrid is able to call ShellExecute to display the UAC elevation dialog...

@if (1==1) @if(1==0) @ELSE
@echo off&SETLOCAL ENABLEEXTENSIONS
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"||(
    cscript //E:JScript //nologo "%~f0"
    @goto :EOF
)
echo.Performing admin tasks...
REM call foo.exe
@goto :EOF
@end @ELSE
ShA=new ActiveXObject("Shell.Application")
ShA.ShellExecute("cmd.exe","/c \""+WScript.ScriptFullName+"\"","","runas",5);
@end
汹涌人海 2024-11-13 05:52:42
@echo off
fsutil dirty query %systemdrive% >nul || (
    echo Requesting administrative privileges...
    set "ELEVATE_CMDLINE=cd /d "%cd%" & call "%~f0" %*"
    findstr "^:::" "%~sf0">"%temp%\getadmin.vbs"
    cscript //nologo "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs" & exit /b
)

rem ------- getadmin.vbs ----------------------------------
::: Set objShell = CreateObject("Shell.Application")
::: Set objWshShell = WScript.CreateObject("WScript.Shell")
::: Set objWshProcessEnv = objWshShell.Environment("PROCESS")
::: strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
::: objShell.ShellExecute "cmd", "/c " & strCommandLine, "", "runas"
rem -------------------------------------------------------

echo Running script as admin.
echo Script file : %~f0
echo Arguments   : %*
echo Working dir : %cd%
echo.
:: administrator commands here
:: e.g., run shell as admin
cmd /k

它还允许将命令行参数传递给批处理脚本。

对于演示: self-elevating.bat“带空格的路径”arg2 3 4“另一个长参数”

这是另一个不需要创建临时文件的版本。

@echo off
<!-- : --- self-elevating_no_temp.bat ---------------------
fsutil dirty query %systemdrive% >nul && goto :gotAdmin
echo Requesting administrative privileges...
set "ELEVATE_CMDLINE=cd /d "%cd%" & call "%~f0" %*"
cscript //nologo "%~f0?.wsf" //job:Elevate
exit /b

-->
<job id="Elevate"><script language="VBScript">
  Set objShell = CreateObject("Shell.Application")
  Set objWshShell = WScript.CreateObject("WScript.Shell")
  Set objWshProcessEnv = objWshShell.Environment("PROCESS")
  strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
  objShell.ShellExecute "cmd", "/c " & strCommandLine, "", "runas"
</script></job>
:gotAdmin -------------------------------------------------

echo Running script as admin.
echo Script file : %~f0
echo Arguments   : %*
echo Working dir : %cd%
echo.
:: administrator commands here
:: e.g., run shell as admin
cmd /k

11/2023 编辑:
将当前工作目录更正为“%CD%”而不是“%~dp0”
更可靠的命令来检测脚本是否以管理员身份运行。

@echo off
fsutil dirty query %systemdrive% >nul || (
    echo Requesting administrative privileges...
    set "ELEVATE_CMDLINE=cd /d "%cd%" & call "%~f0" %*"
    findstr "^:::" "%~sf0">"%temp%\getadmin.vbs"
    cscript //nologo "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs" & exit /b
)

rem ------- getadmin.vbs ----------------------------------
::: Set objShell = CreateObject("Shell.Application")
::: Set objWshShell = WScript.CreateObject("WScript.Shell")
::: Set objWshProcessEnv = objWshShell.Environment("PROCESS")
::: strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
::: objShell.ShellExecute "cmd", "/c " & strCommandLine, "", "runas"
rem -------------------------------------------------------

echo Running script as admin.
echo Script file : %~f0
echo Arguments   : %*
echo Working dir : %cd%
echo.
:: administrator commands here
:: e.g., run shell as admin
cmd /k

It also allows passing command line parameters to the batch script.

For a demo: self-elevating.bat "path with spaces" arg2 3 4 "another long argument"

And this is another version that does not require creating a temp file.

@echo off
<!-- : --- self-elevating_no_temp.bat ---------------------
fsutil dirty query %systemdrive% >nul && goto :gotAdmin
echo Requesting administrative privileges...
set "ELEVATE_CMDLINE=cd /d "%cd%" & call "%~f0" %*"
cscript //nologo "%~f0?.wsf" //job:Elevate
exit /b

-->
<job id="Elevate"><script language="VBScript">
  Set objShell = CreateObject("Shell.Application")
  Set objWshShell = WScript.CreateObject("WScript.Shell")
  Set objWshProcessEnv = objWshShell.Environment("PROCESS")
  strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
  objShell.ShellExecute "cmd", "/c " & strCommandLine, "", "runas"
</script></job>
:gotAdmin -------------------------------------------------

echo Running script as admin.
echo Script file : %~f0
echo Arguments   : %*
echo Working dir : %cd%
echo.
:: administrator commands here
:: e.g., run shell as admin
cmd /k

Edited 11/2023:
Corrected the current working directory to "%CD%" instead of "%~dp0"
More reliable command to detect if script is run as admin.

森林很绿却致人迷途 2024-11-13 05:52:42

虽然 @amr ali 的 代码很棒,但我有一个实例,其中我的 bat 文件包含 > < code>< 标志,不知为何被它们噎住了。

我找到了这个。只需将其全部放在代码之前,它就可以完美运行。

REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
    "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

Although @amr ali's code was great, I had an instance where my bat file contained > < signs, and it choked on them for some reason.

I found this instead. Just put it all before your code, and it works perfectly.

REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
    "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------
野却迷人 2024-11-13 05:52:42

简单的管道技巧,||,在批处理顶部使用一些 .vbs。它将正常退出并以管理员身份重新启动。

@AT>NUL||echo set shell=CreateObject("Shell.Application"):shell.ShellExecute "%~dpnx0",,"%CD%", "runas", 1:set shell=nothing>%~n0.vbs&start %~n0.vbs /realtime& timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit

当使用完 temp.vbs 后,它还会 del /Q temp.vbs。

Simple pipe trick, ||, with some .vbs used at top of your batch. It will exit regular and restart as administrator.

@AT>NUL||echo set shell=CreateObject("Shell.Application"):shell.ShellExecute "%~dpnx0",,"%CD%", "runas", 1:set shell=nothing>%~n0.vbs&start %~n0.vbs /realtime& timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit

It also del /Q the temp.vbs when it's done using it.

吃颗糖壮壮胆 2024-11-13 05:52:42

我会设置一个快捷方式,无论是 CMD 还是您想要运行的东西,然后将快捷方式的属性设置为需要管理员,然后从批处理文件运行快捷方式。我还没有测试来确认它会尊重这些属性,但我认为它更优雅,并且不需要激活管理员帐户。

此外,如果您将其作为计划任务(可以从代码设置)执行,则可以选择在此处提升运行它。

I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.

Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.

素年丶 2024-11-13 05:52:42

我刚刚在桌面上创建了一个快捷方式,并在目标中添加了这一行:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command Start-Process -verb RunAs wt

并在任务栏中固定后:)

i just created an shortcut in my desktop with this line in target:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command Start-Process -verb RunAs wt

and after pinned in taskbar :)

饮惑 2024-11-13 05:52:42

您可以通过 CLI 调用 PowerShellpowershell.exe,以便调用其Start-Process cmdlet,支持以提升方式启动进程;这样做有两个优点:

  • 您不需要一个混合批处理文件,该文件使用巧妙但晦涩的技巧将两种不同环境的语言组合在一个文件中。

  • 您可以将 -Wait 放在 -Verb RunAs 之前(见下文),以使提升的重新调用同步,即等待它退出并将其退出代码传达给调用者。

以下内容借鉴了Amr Ali 有用的 WSH 辅助答案中的技术;保存并运行为 run-elevated.cmd,例如:

@echo off & setlocal

:: Check if the current session is already elevated.
:: `net session` only succeeds in elevated sessions.
net session >NUL 2>&1 && goto :ELEVATED

:: Getting here means that we must reinvoke with elevation.
:: Add -Wait before -Verb RunAs to wait for the reinvocation to exit.
set ELEVATE_CMDLINE=cd /d "%~dp0" ^& "%~f0" %*
powershell.exe -noprofile -c Start-Process -Verb RunAs cmd.exe \"/k $env:ELEVATE_CMDLINE\"
exit /b %ERRORLEVEL%

:: Getting here means that we are (now) running with elevation.
:ELEVATED

echo === Running in elevated session:
echo Script file : %~f0
echo Arguments   : %*
echo Working dir : %cd%

谈到 Amr Ali 的 WSH 辅助答案;这里有一个重新表述,可以使参数传递更加稳健,以便可以传递诸如“a & b”之类的参数,并防止在中重复“^”字符通过避免使用 call 来传递参数 - 请参阅行 set ELEVATE_CMDLINE=...;此外,除了一些可读性格式之外,还确保不会意外回显任何原始批处理语句:

<!-- : (":" is required)
@echo off & setlocal
net session >NUL 2>&1 && goto :ELEVATED
set ELEVATE_CMDLINE=cd /d "%~dp0" ^& "%~f0" %*
cscript.exe //nologo "%~f0?.wsf" //job:Elevate & exit /b
-->

<job id="Elevate">
  <script language="VBScript">
    Set objShell = CreateObject("Shell.Application")
    Set objWshShell = WScript.CreateObject("WScript.Shell")
    Set objWshProcessEnv = objWshShell.Environment("PROCESS")
    strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
    objShell.ShellExecute "cmd", "/k " & strCommandLine, "", "runas"
  </script>
</job>

:ELEVATED

echo === Running in elevated session:
echo Script file: %~f0
echo Arguments  : %*
echo Working dir: %cd%

You can call PowerShell via its CLI, powershell.exe, in order to call its Start-Process cmdlet, which supports starting processes with elevation; doing so has two advantages:

  • You don't need a hybrid batch file that uses clever, but obscure tricks to combine the languages of two distinct environments in a single file.

  • You may place -Wait before -Verb RunAs (see below) in order to make the elevated reinvocation synchronous, i.e. to wait for it to exit and communicate its exit code to the caller.

The following borrows techniques from Amr Ali's helpful WSH-assisted answer; save and run as run-elevated.cmd, for instance:

@echo off & setlocal

:: Check if the current session is already elevated.
:: `net session` only succeeds in elevated sessions.
net session >NUL 2>&1 && goto :ELEVATED

:: Getting here means that we must reinvoke with elevation.
:: Add -Wait before -Verb RunAs to wait for the reinvocation to exit.
set ELEVATE_CMDLINE=cd /d "%~dp0" ^& "%~f0" %*
powershell.exe -noprofile -c Start-Process -Verb RunAs cmd.exe \"/k $env:ELEVATE_CMDLINE\"
exit /b %ERRORLEVEL%

:: Getting here means that we are (now) running with elevation.
:ELEVATED

echo === Running in elevated session:
echo Script file : %~f0
echo Arguments   : %*
echo Working dir : %cd%

Speaking of Amr Ali's WSH-assisted answer; here is a reformulation that makes passing the arguments through more robust, so that arguments such as "a & b" may be passed, and prevents duplicating "^" characters in arguments by avoiding the use of call - see line set ELEVATE_CMDLINE=...; also, apart from some formatting for readability, it is ensured that none of the original batch statements are accidentally echoed:

<!-- : (":" is required)
@echo off & setlocal
net session >NUL 2>&1 && goto :ELEVATED
set ELEVATE_CMDLINE=cd /d "%~dp0" ^& "%~f0" %*
cscript.exe //nologo "%~f0?.wsf" //job:Elevate & exit /b
-->

<job id="Elevate">
  <script language="VBScript">
    Set objShell = CreateObject("Shell.Application")
    Set objWshShell = WScript.CreateObject("WScript.Shell")
    Set objWshProcessEnv = objWshShell.Environment("PROCESS")
    strCommandLine = Trim(objWshProcessEnv("ELEVATE_CMDLINE"))
    objShell.ShellExecute "cmd", "/k " & strCommandLine, "", "runas"
  </script>
</job>

:ELEVATED

echo === Running in elevated session:
echo Script file: %~f0
echo Arguments  : %*
echo Working dir: %cd%
束缚m 2024-11-13 05:52:42

NirCmd www.nirsoft.net 提供提升
使用 nircmdc

NirCmd www.nirsoft.net offers elevated
Use nircmdc

烟燃烟灭 2024-11-13 05:52:42

浏览到 C:\windows\System32 并右键单击 cmd.exe 并以管理员身份运行。在 Windows 7 上为我工作。

如果您尝试以提升的权限运行脚本,您可以对脚本文件执行相同的操作,或者使用调度程序的作为不同用户运行选项来运行脚本。

Browse to C:\windows\System32 and right click on cmd.exe and run as Administrator. Worked for me on Windows 7.

If you are trying to run a script with elevated privileges you could do the same for the script file or use the scheduler's run as a different user option to run the script.

伤感在游骋 2024-11-13 05:52:42

我个人对任何建议的解决方案都不满意,因此我追踪并找出微软本身如何以管理员身份运行某些命令而无需任何确认。

这是我最终从 Windows 注册表中找到的:

*RunAs "D:\Path\To\app.exe"
*RunAs "D:\Path\To\app.exe" [YourCommandArgs]

I personally did not satisfied with any of suggested solutions so I traced and find out how microsoft itself is running some commands as administrator without any confirmations.

Here is what I finally found from windows registry:

*RunAs "D:\Path\To\app.exe"
*RunAs "D:\Path\To\app.exe" [YourCommandArgs]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文