Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run batch as Admin (auto-elevate) and then de-elevate

I have a script that runs in 2 parts. The first part requires admin access (updates HOSTS file and does some copying/overwriting). After that part finishes, I need to map a drive using the hostname alias the first part of the script updated.

I have figured out how to get the elevated privileges by using this SO Question. But mapping a drive (while in admin) maps a drive into the admin's session. I need to "de-elevate" back into user mode to run my second script.

This is a script I run at least once every day, and possibly multiple times per day. I am trying to create a solution that is just 1 .bat file, if possible. For reasons, the scripts are written in perl.

Things I have tried:

  1. Using the runas /user:regular_user command (this does not work)
  2. 1 bat file Using CALL for the 2 batch files (This "works" but for some reason both run at the same time)
  3. Running 2 bat files separately, and manually.
  4. Searching SO, but I could not find admin->user instead only user->admin

TLDR: How do I de-elevate to user mode from admin mode in a batch file?

like image 473
Ishikawa91 Avatar asked Jul 16 '13 14:07

Ishikawa91


People also ask

Is it possible to automatically run a batch file as administrator?

Yes, you're able to run a batch file with administrative rights. Unfortunately, you can't do this directly from the batch file it self. You would need to first create a shortcut of that batch file and change the properties for that shortcut in order to make this work.

What does @echo off do in a batch file?

To prevent echoing a particular command in a batch file, insert an @ sign in front of the command. To prevent echoing all commands in a batch file, include the echo off command at the beginning of the file.


2 Answers

Your best bet is to use the best third party remote/local execution tool : Windows Sysinternals PSEXEC. You can supply credentials and accomplish what you need using PSEXEC! You can put PSEXEC commands into your batch file or vbs and have them run without a hitch. You can also call one command with PSEXEC elevated permission and the next without any elevation, while mixing credentials in a single unique batch file.

http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx

like image 86
apollosoftware.org Avatar answered Oct 26 '22 15:10

apollosoftware.org


If you're using 2 batch files, call the batch ElevatedBatch.cmd with elevation by using Main.cmd (which continues doing unelevated things):

@ECHO OFF
START /WAIT ElevatedBatch.cmd %1 %2 %3 %4 %5 %6 %7 %8 %9
REM here you can do unelevated stuff:
ECHO Running unelevated now

The parameter /WAIT ensures that the script will wait until ElevatedBatch.cmd has ended. For ElevatedBatch.cmd you can use a template like this one to elevate it.

like image 37
Matt Avatar answered Oct 26 '22 16:10

Matt