Example of prompting for admin access in Windows CMD file - windows

I'm writing a command file (.cmd) to add a user to a local group. I would like to have the CMD file prompt for admin access if the call fails.
I imagine it would ne something like this:
#echo off
net localgroup administrators domain\user /add
rem The Net command doesn't prompt for privilege escalation, it just fails.
if "%errorlevel%" neq "0" RequireAdministrator "cmd.exe /c net localgroup administrators domain\user /add"
if "%errorlevel%" neq "0" echo Could not add user to administrators group
Does this make sense?

There is a well known script published by Microsoft known as elevate. It comes in the form of the Elevation PowerToys. You can down load it from here.
The two files you need are elevate.vbs and elevate.cmd. Put those in the same directory as your .cmd file, or perhaps somewhere on your system path. Then your .cmd file should just read:
elevate cmd.exe /c net localgroup administrators domain\user /add

Related

How to set full control permission for file and folder on Windows with cmd?

I'm trying this below. Than read, write & execute permission can stop, but file rename I can't stop with this command.
CACLS files /e /p {USERNAME}:{PERMISSION}
Where,
/p : Set new permission
/e : Edit permission and kept old permission as it is i.e. edit ACL instead of replacing it.
{USERNAME} : Name of user
{PERMISSION} : Permission can be:
R - Read
W - Write
C - Change (write)
F - Full control
For example grant Rocky Full (F) control with following command (type at Windows command prompt):
C:> CACLS files /e /p rocky:f
Read complete help by typing the following command:
C:> cacls /?
below is a working sample that i use
ICACLS *.* /setowner "authenticated users" /T /C
now use the command ICALS
/grant or /deny the permission
then username

Batch script access denied even with admin privileges

I have a batch script in Windows7 to update the hosts file that fails.
I am logged as a user with administrative rights.
Even if I run the script with the "Run as administrator" option I get Access denied. 0 files copied when executing this part of the script:
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
REM create changing part of hosts file...
if exist %temp%\temp.txt del %temp%\temp.txt
echo %ip% myproxy >> %temp%\temp.txt
REM check this...
set hostpath=C:\WINDOWS\system32\drivers\etc
REM add static part of hosts file
type "%hostpath%\hosts-static" >> %temp%\temp.txt
REM replace hosts file
copy /y %temp%\temp.txt "%hostpath%\hosts"
ipconfig /flushdns
netsh interface IP delete arpcache
pause
I also tried to create a shortcut and set the "Advanced -> Run as Administrator" option but no luck.
If I open a cmd shell as Administrator and then run the script from there everything works fine, but no way of running it directly double-clicking on the file (or its link).
Any idea?
EDIT:
added the whole script.
I tried creating a shortcut for the following command to execute as Administrator
C:\Windows\System32\cmd.exe /c script.bat
and it is also failing.
From the same shortcut (without arguments) I can open a window where I can execute the batch correctly. I really cannot see why.
Obviously a late response, but just solved this issue with a very straightforward solution so I thought I'd share:
Using ICACLS you can modify access control lists (ACLs) to bypass access denied errors.
Run the following command:
ICACLS C:\path\to\batch\file\directory\* /C
the parameter /C tells the batch file to bypass access denied errors. Cheers.
Try attrib -r -s -h -a "%hostpath%\hosts" before your copy command. If any file is attributed +r, +s, or +h, you'll get "Access is denied" if you try to overwrite it using copy.

How To Write A Bat File That Will Open CMD And Perform Multiple Commands

I am trying to write a bat file command that will run cmd and for example, make a new user and elevate the user to administrator privileges.
Or Even Better! Write a bat command to open run (Win+R), write a command to open cmd and then type out the command, net user --- --- /add etc....
Many thanks to whoever can help, this is where I am so far:
start cmd.exe /k "net user smith admin /add" pause 0.5 /c "net user administrators smith /add"
starting run did work, but I could not use /c or /k to write a command, I tried write but I had no clue what it actually did.
Try creating batch file named AddUser.cmd with following:
#echo off
net user %1 admin /add
net user Administrators %1 /add
Then run it like this:
AddUser smith
The %1 in your batch file is replaced by the first parameter you call it with.
You can verify first parameter is provided like this:
#echo off
if "%1"=="" goto :Syntax
net user %1 admin /add
net user Administrators %1 /add
goto :End
:Syntax
echo Syntax: AddUser [userid]
goto :End
:End

batch file will not run as administrator

I am trying to run this code in a windows batch (.bat) file
#echo off
echo Adding New User - LogMeInRemoteUser
net user | find /i "LogMeInRemoteUser" || Net user LogMeInRemoteUser password /add /fullname:"LogMeInRemoteUser"
pause
echo Adding User to Administrators Group
NET LOCALGROUP Administrators "LogMeInRemoteUser" /ADD
pause
echo Creating Registry Keys to remove the new user from the login page
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon\SpecialAccounts\UserList" /v "LogMeInRemoteUser" /t REG_DWORD /d 0
pause
echo Finished
if i run the file normally, i get an Access Denied error so I try to run as Administrator but the cmd windows opens and instantly closes, what have i done wrong?
When you run as administrator the current directory is changed under you. To prove that (and fix it) enter these 3 lines under your #echo off
echo(%cd%
pushd %~dp0
echo(%cd%
You can remove both of the echo( statements after you see what is happening.

How to code a BAT file to always run as admin mode?

I have this line inside my BAT file:
"Example1Server.exe"
I would like to execute this in Administrator mode. How to modify the bat code to run this as admin?
Is this correct? Do I need to put the quotes?
runas /user:Administrator invis.vbs Example1Server.exe
The other answer requires that you enter the Administrator account password. Also, running under an account in the Administrator Group is not the same as run as administrator see: UAC on Wikipedia
Windows 7 Instructions
In order to run as an Administrator, create a shortcut for the batch file.
Right click the batch file and click copy
Navigate to where you want the shortcut
Right click the background of the directory
Select Paste Shortcut
Then you can set the shortcut to run as administrator:
Right click the shortcut
Choose Properties
In the Shortcut tab, click Advanced
Select the checkbox "Run as administrator"
Click OK, OK
Now when you double click the shortcut it will prompt you for UAC confirmation and then Run as administrator (which as I said above is different than running under an account in the Administrator Group)
Check the screenshot below
Note:
When you do so to Run As Administrator, the current directory (path) will not be same as the bat file. This can cause some problems in many cases that the bat file refer to relative files beside it. For example, in my Windows 7 the cur dir will be SYSTEM32 instead of bat file location!
To workaround it, you should use
cd "%~dp0"
or better
pushd "%~dp0"
to ensure cur dir is at the same path where the bat file is.
You use runas to launch a program as a specific user:
runas /user:Administrator Example1Server.exe
Just add this to the top of your bat file:
set "params=%*"
cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || ( echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/k cd ""%~sdp0"" && %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B )
It will elevate to admin and also stay in the correct directory. Tested on Windows 10.
If you can use a third party utility, here is an elevate command line utility.
The source and binaries are available on GitHub.
This is the usage description:
Usage: Elevate [-?|-wait|-k] prog [args]
-? - Shows this help
-wait - Waits until prog terminates
-k - Starts the the %COMSPEC% environment variable value and
executes prog in it (CMD.EXE, 4NT.EXE, etc.)
prog - The program to execute
args - Optional command line arguments to prog
You can use nircmd.exe's elevate command
NirCmd Command Reference - elevate
elevate [Program] {Command-Line Parameters}
For Windows Vista/7/2008 only: Run a program with administrator rights. When the [Program] contains one or more space characters, you must put it in quotes.
Examples:
elevate notepad.exe
elevate notepad.exe C:\Windows\System32\Drivers\etc\HOSTS
elevate "c:\program files\my software\abc.exe"
PS: I use it on win 10 and it works
go get github.com/mattn/sudo
Then
sudo Example1Server.exe
convert your batch file into .exe with this tool: http://www.battoexeconverter.com/ then you can run it as administrator
My experimenting indicates that the runas command must include the admin user's domain (at least it does in my organization's environmental setup):
runas /user:AdminDomain\AdminUserName ExampleScript.bat
If you don’t already know the admin user's domain, run an instance of Command Prompt as the admin user, and enter the following command:
echo %userdomain%
The answers provided by both Kerrek SB and Ed Greaves will execute the target file under the admin user but, if the file is a Command script (.bat file) or VB script (.vbs file) which attempts to operate on the normal-login user’s environment (such as changing registry entries), you may not get the desired results because the environment under which the script actually runs will be that of the admin user, not the normal-login user! For example, if the file is a script that operates on the registry’s HKEY_CURRENT_USER hive, the affected “current-user” will be the admin user, not the normal-login user.
When you use the /savecred argument, it asks for the password once, and than never asks for it again. Even if you put it onto another program, it will not ask for the password. Example for your question:
runas /user:Administrator /savecred Example1Server.exe
I Tested #Sire's answer on Windows 11, and it works like a charm. It's worth mentioning that using cmd /k - as #Sire has used - will keep the Administrator CMD open after it finishes running. Using cmd /c instead will close the window when it's over with the batch file.
set "params=%*"
cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || ( echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/c cd ""%~sdp0"" && %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B )
I found there is possible to use powershell. The powershell will show the default Windows UAC Dialog.
powershell Start -File Example1Server.exe -Verb RunAs
For execute BAT file with admin rights, the content of the BAT file can look as this:
#echo off
if "%1"=="runas" (
cd %~dp0
echo Hello from admin mode
pause
) else (
powershell Start -File "cmd '/K %~f0 runas'" -Verb RunAs
)
where:
%1 First input argument assigned to BAT file.
%~f0 expands to full path to the executed BAT file
%~dp0 expands to full directory path from where the BAT file is executed
cmd -C <commands> Execute command in terminal and close
Use the complete physical drive\path to your Target batch file in the shortcut Properties.
This does not work in Windows 10 if you use subst drives like I tried to do at first...

Resources