Freigeben über


Scripting Elevation on Vista

[Added 2007-07-02, 16:41 Eastern Time: I was thoroughly and inexcusably remiss in failing to include a reference to Michael Murgolo's excellent TechNet Magazine article, Script Elevation PowerToys for Windows Vista . I'm rectifying that now.]

As I mentioned recently, although the RunAs.exe console utility still exists on Windows Vista and will let you run a program as another user, it will not run that program with elevated privileges. So if you use RunAs.exe to start a program with an administrator account, the program will run with that account's profile and settings, but with standard user privileges only, not with the power to do computer administration. You can't get an application to run with elevated privileges unless you go through the UAC elevation prompt. And RunAs.exe on Windows Vista (RTM, anyway) will not invoke that prompt.

What if you have batch files for XP or Server 2003 that called RunAs when administrative tasks needed to be performed? E.g., say there's a line in your batch file to start CMD.EXE with elevated permissions that looks like this:

runas /u:Administrator "cmd.exe /t:fc /k cd /d c:\ && title *** Admin console *** "

Is there another way to script the "run this program with elevated permissions" that RunAs gave you on XP/2003? Yes. First, create a small script file called "elevate.js" and put it in a folder in your PATH. (*) The contents of elevate.js should look like this:

 // elevate.js -- runs target command line elevated
if (WScript.Arguments.Length >= 1) {
    Application = WScript.Arguments(0);
    Arguments = "";
    for (Index = 1; Index < WScript.Arguments.Length; Index += 1) {
        if (Index > 1) {
            Arguments += " ";
        }
        Arguments += WScript.Arguments(Index);
    }
    new ActiveXObject("Shell.Application").ShellExecute(Application, Arguments, "", "runas");
} else {
    WScript.Echo("Usage:");
    WScript.Echo("elevate Application Arguments");
}

Then replace "runas /u:Administrator" with "elevate": (**)

elevate cmd.exe "/t:fc /k cd /d c:\ && title *** Admin console *** "

Important note: the elevate.js script invokes the UAC prompt, but it will not let you bypass it. User interaction is still required.

With the default settings, the elevation prompt will prompt you for simple consent (click "continue") if you are a member of the Administrators group, and prompt you for admin credentials if you are running as a standard user. If you are a member of the Administrators group, but would like to use a different account for the elevated task, you can change the computer's security policy for the behavior of the elevation prompt for admins to "Prompt for credentials". When the prompt appears, you can enter the credentials of a different administrative account.

Thanks to John Stephens of the Windows team for this script.

(*)  I highly recommend that scripts and other programs that may be used by elevated apps or are part of elevation sequences be kept in a folder that standard users cannot write to. I have a Utilities folder under %ProgramFiles% for this purpose.

(**)  Note that the quoting in this case needed to be rearranged a little as well: the first item passed to the script is the application to elevate; everything after that forms the rest of the command line for that application. If the quoting had been kept as-is, Windows would have tried to elevate an application called "cmd.exe /t:fc /k …", which doesn't exist. The quotes are still needed here so that the "&&" and everything after it remain on the command line to the elevated application. Otherwise the current command shell will parse it as part of the command it is running.

Comments

  • Anonymous
    June 30, 2007
    Um, OK. So why does my clean install of Vista Business allow me to do a RunAs /user:Administrator cmd.exe that then can delete/write files into the system folders? @Chris:&nbsp; Interesting -- I'll have to check that out.  Did you 1) disable UAC, or 2) enable the built-in Administrator account, which is disabled by default? -- Aaron [2007-07-02] @Chris:  I think I've identified the issue here.  By default, "Admin Approval Mode" is disabled for the built-in Administrator account, so any logons for that account run with full admin privileges.  So if you enable that account and then use RunAs.exe to start process using that account, it will run elevated and without a UAC elevation prompt.  Administrator is disabled by default; I think its primary purpose is for system recovery (e.g., in Safe Mode).  If you enable that account, you should also change the security option to enable Admin Approval Mode for that account. -- Aaron

  • Anonymous
    July 01, 2007
    I do the same as Chris Knight (hey, ex-Beatnik?). I have not disabled UAC and I don't think I did anything special to the admin account.  My account is a standard user but I leave an admin console open and can do anything in it without UAC prompts (aside from the initial one when first opening the console).  Running vista ultimate.

  • Anonymous
    July 01, 2007
    Did a little checking... I don't have an account named Administrator, but do have one by another name - so I must have either created it or renamed and enabled the default one. Just noticed that I don't explicitly use runas to open my prompt either.  I have a shortcut whose properties I modified to run as administrator (properties | shortcut | advanced - it must invoke a runas behind the scenes). @sean e:  You're certainly getting an elevation prompt when you do that, right?  (Unless you've changed the security policy to elevate without prompting, which is very risky and strongly discouraged.) -- Aaron

  • Anonymous
    July 01, 2007
    Here is another example(.vbs file) VBScripts and UAC elevation: http://www.winhelponline.com/articles/185/1/

  • Anonymous
    July 01, 2007
    The comment has been removed

  • Anonymous
    July 02, 2007
    >@sean e:  You're certainly getting an elevation >prompt when you do that, right? Yes, I get the prompt when I open the console.  After that initial one, I'm good for doing anything without further prompts. @sean e:  As expected.  If an elevated program starts another program, the new program will also run elevated. BTW, what you're doing is not invoking RUNAS.EXE, the console utility program. -- Aaron

  • Anonymous
    July 02, 2007
    http://blogs.msdn.com/aaron_margosis/archive/2007/07/01/scripting-elevation-on-vista.aspx

  • Anonymous
    July 02, 2007
    If you need to run command with full administrator permissions in Windows Vista, you could use the elevated

  • Anonymous
    July 02, 2007
    > Administrator is disabled by default [...] > If you enable that account, you should also > change the security option to enable Admin > Approval Mode for that account. I think that's a good idea.  But you have a better idea: [For other administrative accounts] > (Unless you've changed the security policy to > elevate without prompting, which is very risky > and strongly discouraged.) I think that's a very good idea.  I think it should apply to the built-in Administrator account too, for exactly the same reason.  There should not be a default which changes the built-in Administrator account to elevate without prompting.  The default should put the same Admin Approval Mode on that account as it does on other administrative accounts, because any deviation is risky and strongly discouraged. [Aaron Margosis] The default is that admin-approval mode (AAM) is disabled for the built-in Administrator account, but that the built-in Administrator account itself is also disabled.  Its purpose (as I understand it) is to serve in emergencies such as system recovery, at which point you presumably wouldn't want AAM to be in the way.  If you intend to use the built-in Administrator account for other purposes and enable the account, you should probably change its AAM setting at the same time. > We have found that most forms of "partial > administrative capabilities" such as "Power > Users" usually end up including an inexorable > path to full administrative capabilities. Yes.  Any administrator who wants to be administrator and intentionally sets out to be administrator should be allowed to be administrator.  But some of us peasants occasionally make typos or (more commonly for some of us) accidentally hit a mouse button while moving the mouse, causing unwanted operations to occur.  So some of us would be glad to be administrators only when we want to be, and be power users the rest of the time.  The prompts do help a bit, but I think that was no reason to get rid of power users. In old days, I used to set tape reels to r--r--r-- except when intending to write to them.  I still sometimes set floppy disks to r-xr-xr-x except when intending to write to them.  I wish I could mount disk partitions as r-xr-xr-x.[]  Sure, as a power user I have the power to change the settings at will, but at least I won't usually do that accidentally, and at least it means I'd have to make at least two accidental mistakes in a row before doing serious damage.  Power users are useful. [Aaron Margosis] I'm not sure that we're talking about the same thing.  I'm referring to Power Users, the "admin-lite" group that's been present since NT 3.1.  It was intended as a middle ground, more powerful than Users, but less so than Administrators.  However, that ground proved to be untenable, as the access that was granted to Power Users allowed it to elevate to full system control.  That's why it's been deprecated.  For reference, see this KB article, Jesper's blog post, and Mark Russinovich's blog post [ Even in Linux I wish I could mount disk partitions as r-xr-xr-x.  Drivers disobey that setting when replaying journals, and I wish I could stop them.  But this is off-topic, sorry.]

  • Anonymous
    July 04, 2007
    I made a PowerShell version of the JS script. See http://msgoodies.blogspot.com/2007/07/powershell-start-elevatedprocess.html [Aaron Margosis]  As I said here, Windows PowerShell is the coolest and most revolutionary technology we have shipped in a very long time.  Thanks for providing more evidence, Per! :-)

  • Anonymous
    July 04, 2007
    "Administrator" account > Its purpose (as I understand it) is to serve > in emergencies such as system recovery, at > which point you presumably wouldn't want AAM > to be in the way. OK, I see the point. "Power users" (admin-capable but not by default) > I'm not sure that we're talking about the > same thing.  I'm referring to Power Users, We are.  We agree that power users have the capability to become admins.  You think there's no purpose in letting admin-capable people run as power users until they deliberately decide to be admins.  I think there is a purpose, and I tried to explain why.  Vista's prompts provide some of the same protections, because sometimes someone who fat-fingers a mouse key or keyboard key might get a second chance to avoid doing what they didn't intend to so.  The power users group was a more powerful way to provide the same protections.  It's like having the SETPRIV bit or knowing the root password, you deliberately enable privileges when you need them but you don't enable them otherwise.  Oops sorry, s/you/I/. [Aaron Margosis]  Power Users (as it existed on XP and earlier) provides no such protections.  Running as Power User was tantamount to running as admin.  There were tons of things you could do to damage the system and/or other users.  More importantly, malware that runs in your session could immediately take over the entire system.  The whole idea of UAC is for end users (including people who administer their own systems) to have only the power they typically need for computer use -- in which the system and other users cannot be touched.

  • Anonymous
    July 05, 2007
    > Running as Power User was tantamount to > running as admin. Already known and agreed. > More importantly, malware that runs in your > session could immediately take over the > entire system. OK, you mean that vulnerabilities in the capabilities of Power Users made it possible for malware to enable itself to do the same things without any further interaction with the user.  OK, that's dangerous. I thought the idea behind power users (the ability to be admin when desired but not automatically being admin when not desired) was a good idea.  But now this reminds me of our other discussion: Now I notice that if Vista had a real MakeMeAdmin then there wouldn't be much difference between standard users and power users.  The ability to temporarily add their own account to the administrators group would work for standard users as well as for power users.  So theoretically maybe there's no need for power users, we just need MakeMeAdmin.

  • Anonymous
    July 07, 2007
    The comment has been removed

  • Anonymous
    July 09, 2007
    > Running as Power User was tantamount to > running as admin. Already known and agreed, and now being revisited. Running as Power User was tantamount to running as Local System.  Running as Admin was tantamount to running as Local System.  Under Vista, running as Admin is still tantamount to running as Local System. Now please bear with me.  Sometimes I'm an Admin, therefore sometimes I'm an Idiot (already known and agreed).  Now I've just verified that even in Vista I can sometimes be Local System, and therefore Local System is sometimes an Idiot.  So please patiently explain this to me: Why didn't Administrators disappear along with Power Users?  Why aren't we running as Local System with UAC? [Aaron Margosis]  What would be the value of that?  Note that with Administrators you still have your own account, your own settings, preferences, etc.  LocalSystem was never designed to be used as an interactive logon. (Off-topic tangent:  why is cron setuid to Administrator instead of setuid to Local System?) [Aaron Margosis]  Is that how "cron" is default-configured in the Vista Subsystem for UNIX-based applications?

  • Anonymous
    August 01, 2007
    The comment has been removed

  • Anonymous
    August 02, 2007
    The comment has been removed

  • Anonymous
    August 02, 2007
    Is there a way to detect for a machine that has been upgraded from XP to Vista -  the exceptional case in which Admin Approval Mode for the Built-in Administrator is enabled by default. Is it possible to get the effective setting for this UAC policy - if it has not been explicitly configured ?

  • Anonymous
    August 06, 2007
    Gayle:  I chatted with Aaron about the question on this policy and he suggested that I reply to the post.  That policy is picked up dynamically, so you could technically just look at this reg value: HKLMSoftwareMicrosoftWindowsCurrentVersionPoliciesFilterAdministratorToken to see if it's set to non-zero (i.e., turned on); if it's 0 or missing, it's turned off. That said, all the major caveats apply here that this is an implementation detail that's certain to change or be removed in the future. In theory, you shouldn't even need to check for it, since things will "just work" if your code is already running as a standard user and handling "over the shoulder" elevation (i.e., starting from a standard user account and elevating with a different user). --Jonathan

  • Anonymous
    August 08, 2007
    In current Editions of Vista , are the UAC registry values present by default ? i.e. when it shows as Not Configured in the Group Policy Editor

  • Anonymous
    August 10, 2007
    With the exception of FilterAdministratorToken, I'd expect them all to be present by default.

  • Anonymous
    October 03, 2007
    The comment has been removed

  • Anonymous
    December 12, 2007
    Aaron: have you ever tested the script with pathnames and arguments containing blanks? Replace '= WScript.Arguments()' with '= """ + WScript.Arguments() + """' when this should work right!

  • Anonymous
    December 13, 2007
    When you are on Microsoft Windows Vista Platform. It is hard to create a script that use privilage command. One way is by use the command &quot;Runas&quot; as followC:&gt; Runas /user:Administrator cmdHowever, the above command will ask for Administrato

  • Anonymous
    January 29, 2008
    My application sets a value in HKLMSoftwareMicrosoftWindowsCurrentVersionRun to add it to the startup.  In Vista, I receive access is denied.  What is the easiest way to correct this issue?  My application does not require admin priviledges except for this option (user can turn this feature on/off), but I do not want to prompt for elevation if it is not required.  Is this possible and if so what would you recommend to solve this?  Any help would be greatly appreciated.  Thanks ahead of time. [Aaron Margosis]  Does it need to be in HKLM?  If you put it in the equivalent key under HKCU, then it will launch every time that user logs on, and you won't get access denied when you set or clear the value.

  • Anonymous
    January 30, 2008
    Thanks for the quick response.  I would really like to make the changes to the HKLM b/c the application will run in a classroom setting and students will be logging on/off.  Any ideas? Thanks again. [Aaron Margosis]  Generally speaking, non-admin users shouldn't be able to make configuration changes that affect other users.  Giving users the ability to change that key, in particular, is very dangerous.  I'd recommend just allowing individual users to change the settings for themselves, or just add it to HKLM as part of installation and don't give the users the option to turn it off.

  • Anonymous
    February 25, 2008
    I am elevating a windows installer setup.exe. The script runs fine on vista. On XP I either get '<full path>setup.ini' not found or, in a directory with a shorter path I get "The windows installer service could not be accessed...."

  • Anonymous
    March 06, 2008
    In my environment, all the admins are set to 'Prompt for Consent'. The leads to 740 errors with the RunAs command. To work around it, I created a shortcut to always run as admin and used the runas /netonly switch: C:WindowsSystem32runas.exe /netonly /user:domainusername "mmc c:windowssystem32dsa.msc" This works with the netonly switch, but not without.

  • Anonymous
    March 15, 2008
    The comment has been removed

  • Anonymous
    March 17, 2008
    I'm logged in as a local admin but I run MMC windows (AD users and computers, WSUS management etc) as a separate user.  This method is fine for non admin users but the only way I can find so far to run as a different user is to change User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode to prompt for credentials which some what defeats the point of being a local admin. Thoughts?    

  • Anonymous
    October 18, 2008
    The comment has been removed

  • Anonymous
    October 24, 2008
    The comment has been removed

  • Anonymous
    April 05, 2010
    Aaron, I have put together a couple scripts (VBS and CMD) that use a passive method to detect admin rights (rather than writing stuff to test rights) and works on XP through Windows 7.  It is based on whether the user can get a directory of the system profile folder.  Would love to hear if you can think of scenarios where it would not work: Function CSI_IsAdmin()  'For information and updates see http://CSI-Windows.com/toolkit/CSI_IsAdmin  'For more comprehensive script see http://CSI-Windows.com/toolkit/ifuserperms  Dim oShell : Set oShell = createobject("wscript.shell")  Dim oExec : Set oExec = oShell.Exec("%comspec% /c dir """ & oShell.RegRead("HKLMSOFTWAREMicrosoftWindows NTCurrentVersionProfileListS-1-5-18ProfileImagePath") & """  2>&1 | findstr /I /C:""Not Found""")  Do While oExec.Status = 0    WScript.Sleep 100  Loop  If oExec.ExitCode <> 0 Then CSI_IsAdmin = True End Function It is downloadable here: http://csi-windows.com/toolkit/csi-isadmin The above script does not do any advanced detections like whether a user Could elevate.   So I have also put together a very comprehensive vbscript to snoop token information and determine admin rights on XP through Windows 7.  Also reports whether UAC is turned on or off and whether it is set to silent. It is here: http://csi-windows.com/toolkit/csi-issessionvbs

  • Anonymous
    May 11, 2010
    My 'Elevation Toolkit' is like elevate.js except that it uses the ShellExecuteEx and thus has some features some might find useful, such as waiting for the elevated program to complete and configuring its window state. You can get it from here: http://www.westmesatech.com/misctools.html