How do I execute a batch file in administrator mod

2019-04-16 05:09发布

问题:

I am trying to write a batch file to share a folder across my network using net share but it needs administrator privileges. I dont know how to execute this command in admin mode.

When you right click cmd.exe in Windows search and select "Run as administrator" it doesn't ask me the password, but when I write a batch code using runas command, it ask for a password. Why is it so?

I used following commands

runas.exe /profile /user:administrator "cmd.exe"

start /wait cmd.exe /k "net share Inputs=Folder_Path /GRANT:Everyone,FULL"

and didnt work.

I am using Win 7 32-bit

Also, somewhere I saw that the following will also to be executed after the folder is shared

Icacls Folder_Path /grant Everyone:F /inheritance:e /T

Is this required?

Please help

回答1:

If you want your batch script to ask for elevation if needed, this page might help you. I adapted it to use in a batch script I serve from the web like this:

REM  --> Check for permissions
"%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system">nul 2>NUL

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    if exist "%temp%\getadmin.vbs" (
        del "%temp%\getadmin.vbs"
        echo Failed to acquire elevated privilege.  Try saving this script and running it from your Desktop.
        echo;
        echo Press any key to exit.
        pause>NUL
        goto :EOF
    )
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    echo UAC.ShellExecute "%~s0", "%*", "", "runas", 1 >> "%temp%\getadmin.vbs"

    cscript /nologo "%temp%\getadmin.vbs"
    goto :EOF

:gotAdmin
    if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
:--------------------------------------

:: The rest of the script goes here...

Regarding the "Try saving this script" message, if the user attempts to open the batch script directly from the web browser, browser security might block the elevation. I had to include that to remind my users to save the script first, then run it independently outside the web browser.

Anyway, salt to taste.