none
VB script to run a batch script as admin

    Question

  • I have batch script the I need to run as an administrator, I created a VBscript wrapper that calls a runas and runs my batch file, however the batch file is not being elevated high enough on Windows 7 and Vista, it works fine on XP.  The batch script needs to create a folder in Program files, and copy the necessary files, install several programs, as well as make several registry key changes.  If I am logged in as a user with admin rights, right click on the batch file and select "Run as Administrator" the batch works fine.  Using the VBscript to elevate the rights, it installs the programs, but when it comes to creating the folder in Program files\Program data and Registry edits, it fails.  Is there any way to script so I can elevate the batch file to the same level as selecting "Run as Administrator?

     

     

    Set objShell = WScript.CreateObject("WScript.Shell")
    objShell.Run("runas /user:domain\user \\unc\location\Install.bat"), 1, True
    WScript.Sleep 100
    oShell.Sendkeys "password~"

     

    Another issue, I am having with the script is that it will not send the password, I have to type it manually to test.

     

    The idea is to have the end user be able to click on a link from a webpage and install the program itself, as opposed for our Helpdesk be required to install the program.  So psexec is no doable as it is not on any of the PCs and user login scripts is not an option either, as we don't want the program install on every PC.

     



    Tuesday, April 05, 2011 6:53 PM

Answers

  • We're fine with UAC prompting, the end user for permission.  The main thing is that despite selecting yes on the prompt when the script tries to merge several registry keys, and create a folder and copy files in C:\Program Files and C:\Program data.  My batch file still reports that access is denied.  When I run the script manually, as an administrator user UAC still prompts, but the script runs fine.

    I also tried manually creating a schedule task to test the batch file, running with an domain account running with Admin rights, selecting Run regardless of end user being logged in, the batch file does not run.

    Also for some reason, it does not like when I try to select run with Highest Privileges.

    Here is a script that forces UAC elevation:

    '---------------------------------------
    'Elevate this script before invoking it.
    '25.2.2011 FNL
    '---------------------------------------
    bElevate = False
    if WScript.Arguments.Count > 0 Then If WScript.Arguments(WScript.Arguments.Count-1) <> "|" then bElevate = True
    if bElevate Or WScript.Arguments.Count = 0 Then ElevateUAC
    '******************
    'Your script goes here
    '******************


    '-----------------------------------------
    'Run this script under elevated privileges
    '-----------------------------------------
    Sub ElevateUAC
        sParms = " |"
        If WScript.Arguments.Count > 0 Then
                For i = WScript.Arguments.Count-1 To 0 Step -1
                sParms = " " & WScript.Arguments(i) & sParms
            Next
        End If
        Set oShell = CreateObject("Shell.Application")
        oShell.ShellExecute "wscript.exe", WScript.ScriptFullName & sParms, , "runas", 1
        WScript.Quit
    End Sub

    Wednesday, April 06, 2011 5:22 PM
  • Hi Mark,

    Remember to use the right tools for the right job.

    Windows 7 is designed to prevent you from doing the exact things you are trying to do.
    Creating folders uner program files
    Creating keys outsode HKCU
    Piping commands past windows password boxes
    This is called privilage isolation. It is to prevent malicious code from penetrating your systems. It we were able to get your script working, it would be flagged to microsoft as a security vulnerability.

    As you are trying to distribute software, I suggest you forget about scripting it but create a software distrubtion package.

    You can create an msi package very easy to distribute your soffware. Try here:

    http://www.advancedinstaller.com/

    Or you could use AutoIT as it has it's own scripting language similar to VB. It can be compiled into an exe.

    There is loads of help for software distrubtion at www.appdeploy.com.

    Good luck

    Tuesday, April 12, 2011 8:39 AM
  • Hi,

    In Windows Vista and later with UAC enabled, running programs that require elevation is what is supposed to happen, and it it supposed to be hard to bypass this: The system is designed that way. Questions like this one (I want to bypass administrator rights, I want to bypass elevation prompts) need to be thought of in terms of malware: If this was easy to do, wouldn't malware do it? Why have administrator permissions and UAC prompts if you can just bypass them? Aaron Margosis wrote a good blog entry about this subject:

    http://blogs.msdn.com/b/aaron_margosis/archive/2007/06/29/faq-why-can-t-i-bypass-the-uac-prompt.aspx

    HTH,

    Bill

    Wednesday, April 06, 2011 2:01 PM
  • Why dont you keep it simple

    ::make runas::
    @echo off
    cls
    set /p adminID=ENTER YOUR ADMINISTRATOR ID:
    echo echo off>> "%USERPROFILE%\DESKTOP\ADMIN_CMD.BAT"
    echo CLS>> "%USERPROFILE%\DESKTOP\ADMIN_CMD.BAT"

    ECHO RUNAS ^/user:%AdminID%@DOMAIN.com "cmd /T:70" >>"%USERPROFILE%\DESKTOP\ADMIN_CMD.BAT"

    ::done

    Then, all you have to do is "drag and drop" any batch files into that command window and they will run as that priveledged user. 
    keep in mind the %cd% defaults to system32




    Wednesday, April 13, 2011 9:16 PM

All replies

  • Would it be possible to use psexec and not have it being on each PC.  Having it on the server share where the application is, and calling it remotely?
    Tuesday, April 05, 2011 8:34 PM
  • I can't really answer your first question, other than in the way you have attempted to do it - with RunAs. 

    The problem with your attempt is that the value of TRUE for the third argument in the Run statement is halting script execution until the RunAs part finishes - which is obviously useless.  Change that argument to FALSE.  Then to have any real hope of directing the keystrokes to the right window and at the right time use an AppActivate statement to control the flow of the script, something like this ...

    sPassword = InputBox("Password")
    with CreateObject("WScript.Shell")
      .Run "runas /user:domain\user \\unc\location\Install.bat", 1, False
      Do Until .AppActivate("runas.exe") : WSH.Sleep 100 : Loop
      .Sendkeys sPassword& "~"
    end with

    I added the InputBox because it's a security hole to hard code a password into a script that anyone can read.


    Tom Lavedas
    Tuesday, April 05, 2011 8:41 PM
  • Tom:

    I tried the script you provided, however it is doing the same thing, once it initiates the run as, it a cmd prompt window sits there till i enter the password for my domain user.

     

    And unfortunately it is still not fully elevating the user to full admin rights.

    Tuesday, April 05, 2011 9:27 PM
  • I think you need to be aware of a couple of things:

    • Runas.exe is designed not to accept a password that you might pipe into it or supply as a switch. Wrapping it into a VB Script file will not change this behaviour. You would need to use some third-party tool to get around this restriction.
    • Attempting to create a subfolder in a System Folder under Windows 7 will almost always get you a UAC challenge, which prevents you from fully automating your installation process.

    I said "almost" because there is a method to avoid it. Since it is complex, it is not really suitable for software distribution. It relies on you creating a scheduled task under an admin account on the target machine. When you launch this task with schtasks.exe, again under an admin account, then no UAC  challenge will result.

    I suggest you review your approach to your installation process with the above restrictions in mind. Only after you have mapped out a workable approach should you start your coding effort.

    Tuesday, April 05, 2011 10:07 PM
  • OK, I tested with XP (which does not have the same permissions requirements) and you are working in Win 7.  As Pegasus has said, RunAs is designed to frustrate automation - which only makes sense.  However, I am wondering if it is really the difference between XP and Win7 or if there is something else in the way.  On my XP machine, the routine I posted worked as advertised - at least it issued the password into the RunAs password request.  One other thing that could be a problem is that the AppActivate must find the command window title it expected to find or it will hang.  Does the window that opens end in "runas.exe"  if not, that could be the problem with what I posted.  If it does match, then Pegasus is absolutely correct and this approach cannot be made to work.  In any case, his advice is clearly good and some other approach to installing necessary registry setting, etc. should be found.
    Tom Lavedas
    Wednesday, April 06, 2011 12:14 PM
  • Can a schedule task be created across XP, Vista and 7, using a single VBscript?  Or are the commands different?
    Wednesday, April 06, 2011 1:42 PM
  • Hi,

    In Windows Vista and later with UAC enabled, running programs that require elevation is what is supposed to happen, and it it supposed to be hard to bypass this: The system is designed that way. Questions like this one (I want to bypass administrator rights, I want to bypass elevation prompts) need to be thought of in terms of malware: If this was easy to do, wouldn't malware do it? Why have administrator permissions and UAC prompts if you can just bypass them? Aaron Margosis wrote a good blog entry about this subject:

    http://blogs.msdn.com/b/aaron_margosis/archive/2007/06/29/faq-why-can-t-i-bypass-the-uac-prompt.aspx

    HTH,

    Bill

    Wednesday, April 06, 2011 2:01 PM
  • We're fine with UAC prompting, the end user for permission.  The main thing is that despite selecting yes on the prompt when the script tries to merge several registry keys, and create a folder and copy files in C:\Program Files and C:\Program data.  My batch file still reports that access is denied.  When I run the script manually, as an administrator user UAC still prompts, but the script runs fine.

    I also tried manually creating a schedule task to test the batch file, running with an domain account running with Admin rights, selecting Run regardless of end user being logged in, the batch file does not run.

    Also for some reason, it does not like when I try to select run with Highest Privileges.
    Wednesday, April 06, 2011 2:59 PM
  • We're fine with UAC prompting, the end user for permission.  The main thing is that despite selecting yes on the prompt when the script tries to merge several registry keys, and create a folder and copy files in C:\Program Files and C:\Program data.  My batch file still reports that access is denied.  When I run the script manually, as an administrator user UAC still prompts, but the script runs fine.

    I also tried manually creating a schedule task to test the batch file, running with an domain account running with Admin rights, selecting Run regardless of end user being logged in, the batch file does not run.

    Also for some reason, it does not like when I try to select run with Highest Privileges.

    Here is a script that forces UAC elevation:

    '---------------------------------------
    'Elevate this script before invoking it.
    '25.2.2011 FNL
    '---------------------------------------
    bElevate = False
    if WScript.Arguments.Count > 0 Then If WScript.Arguments(WScript.Arguments.Count-1) <> "|" then bElevate = True
    if bElevate Or WScript.Arguments.Count = 0 Then ElevateUAC
    '******************
    'Your script goes here
    '******************


    '-----------------------------------------
    'Run this script under elevated privileges
    '-----------------------------------------
    Sub ElevateUAC
        sParms = " |"
        If WScript.Arguments.Count > 0 Then
                For i = WScript.Arguments.Count-1 To 0 Step -1
                sParms = " " & WScript.Arguments(i) & sParms
            Next
        End If
        Set oShell = CreateObject("Shell.Application")
        oShell.ShellExecute "wscript.exe", WScript.ScriptFullName & sParms, , "runas", 1
        WScript.Quit
    End Sub

    Wednesday, April 06, 2011 5:22 PM
  • Would using the Impersonationlevel or Authenticationlevel work better/easier to call a batch file as apposed to using the Run as command?  Or are these restricted to WMI calls?

    Monday, April 11, 2011 7:29 PM
  • Hi,

    Tell exactly what you want to accomplish. Describe the goal, not the steps.

    Bill

    Monday, April 11, 2011 8:05 PM
  • Hi Mark,

    Remember to use the right tools for the right job.

    Windows 7 is designed to prevent you from doing the exact things you are trying to do.
    Creating folders uner program files
    Creating keys outsode HKCU
    Piping commands past windows password boxes
    This is called privilage isolation. It is to prevent malicious code from penetrating your systems. It we were able to get your script working, it would be flagged to microsoft as a security vulnerability.

    As you are trying to distribute software, I suggest you forget about scripting it but create a software distrubtion package.

    You can create an msi package very easy to distribute your soffware. Try here:

    http://www.advancedinstaller.com/

    Or you could use AutoIT as it has it's own scripting language similar to VB. It can be compiled into an exe.

    There is loads of help for software distrubtion at www.appdeploy.com.

    Good luck

    Tuesday, April 12, 2011 8:39 AM
  • Why dont you keep it simple

    ::make runas::
    @echo off
    cls
    set /p adminID=ENTER YOUR ADMINISTRATOR ID:
    echo echo off>> "%USERPROFILE%\DESKTOP\ADMIN_CMD.BAT"
    echo CLS>> "%USERPROFILE%\DESKTOP\ADMIN_CMD.BAT"

    ECHO RUNAS ^/user:%AdminID%@DOMAIN.com "cmd /T:70" >>"%USERPROFILE%\DESKTOP\ADMIN_CMD.BAT"

    ::done

    Then, all you have to do is "drag and drop" any batch files into that command window and they will run as that priveledged user. 
    keep in mind the %cd% defaults to system32




    Wednesday, April 13, 2011 9:16 PM
  • Evers_Mark,

    Here is a VB Script Vall Script that will get around the Password Prompt when "RunAs" is called...

    'Start

    '-----------------------------------------------------------------------------------

    ' To Run other VB Scripts or even Batch Files with Admin Priviliges'

    '----------------------------------------------------------------------------------

    Dim WshShell, objFSO

    suser = "YourAdminAccount@YourDomain.com"

    sPass = "YourPassWord"

    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    'Put your Domain Account and Password in between the qoutes, REMEMBER! the Password will be clear text. If this is a standalone just take off the @YourDomain.com

    '-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    sCommand = "wscript \\UNCServerName\ShareFolder\YourScript.vbs"

    '--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    'This will be the path were the scripted you want called will be at. Please note you can substitute the ablove for a local directory (Example: C:\Folder\YourScript.vbs)

    '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Set objComputer = CreateObject("Shell.LocalMachine")

    Set WshNetwork = CreateObject("WScript.Network")

    Set WshShell = CreatObject("WScript.Shell")

    Set WshEnv = wshShell.Environment("Process")

    WinPath = WshEnv("SystemRoot")&"\System32\runas.exe"

    rc = WshShell.Run ("runas /noprofile /user:" & suser & " " $ Chr(34) & sCommand & Chr(34))

    WScript.Sleep 900

    WshShell. AppActivate(WinPath)

    WScript.quit

    'End

    I've used this myself to call up scripts with admin rights however I've not tested it with the UAC on in either Vista or 7, However works like a peach with 2000 & XP. From this point you can add in the script into Peagus's disabling the UAC Script as mentioned below. The usual warnings apply on the security, passwords are sent in plain text.


    John M. Keller MCP (XP & 2003) | Security + E-Mail : itbeast@msn.com

    • Proposed as answer by ITBeast Thursday, February 23, 2012 11:58 PM
    • Unproposed as answer by Bill_StewartModerator Friday, February 24, 2012 12:13 AM
    Thursday, February 23, 2012 11:56 PM
  • Hi,

    Doing what you are suggesting--embedding the password in plain-text in the script and then trying to bypass the fact that runas doesn't accept a password on its command line (which is by design)--is not secure, and because it uses SendKeys, is not robust. Not recommended.

    Also, this thread has already been marked answered. If you have a question, please start a new thread; thanks.

    Bill

    Friday, February 24, 2012 12:13 AM
  • Evers_Mark,

    Here is a VB Script Vall Script that will get around the Password Prompt when "RunAs" is called...

    'Start

    '-----------------------------------------------------------------------------------

    ' To Run other VB Scripts or even Batch Files with Admin Priviliges'

    '----------------------------------------------------------------------------------

    Dim WshShell, objFSO

    suser = "YourAdminAccount@YourDomain.com"

    sPass = "YourPassWord"

    '------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    'Put your Domain Account and Password in between the qoutes, REMEMBER! the Password will be clear text. If this is a standalone just take off the @YourDomain.com

    '-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    sCommand = "wscript \\UNCServerName\ShareFolder\YourScript.vbs"

    '--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    'This will be the path were the scripted you want called will be at. Please note you can substitute the ablove for a local directory (Example: C:\Folder\YourScript.vbs)

    '-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Set objComputer = CreateObject("Shell.LocalMachine")

    Set WshNetwork = CreateObject("WScript.Network")

    Set WshShell = CreatObject("WScript.Shell")

    Set WshEnv = wshShell.Environment("Process")

    WinPath = WshEnv("SystemRoot")&"\System32\runas.exe"

    rc = WshShell.Run ("runas /noprofile /user:" & suser & " " $ Chr(34) & sCommand & Chr(34))

    WScript.Sleep 900

    WshShell. AppActivate(WinPath)

    WScript.quit

    'End

    I've used this myself to call up scripts with admin rights however I've not tested it with the UAC on in either Vista or 7, However works like a peach with 2000 & XP. From this point you can add in the script into Peagus's disabling the UAC Script as mentioned below. The usual warnings apply on the security, passwords are sent in plain text.


    John M. Keller MCP (XP & 2003) | Security + E-Mail : itbeast@msn.com

    Sorry but this topic has been closed for almost a year.

    If you have a script to share feel free to put it in the repository. (link above).

    If you have a new question then please start a new topic.


    ¯\_(ツ)_/¯

    Friday, February 24, 2012 12:14 AM
  • Great!
    Wednesday, February 26, 2014 8:48 PM