Automatically respond to runas from batch file - windows

I'm trying to get a batch file to automatically enter the password into the "runas" program, but I can't get it to work. Here's my batch file so far:
echo password | runas /user:testuser c:/path/to/my/program.exe
However, I get an error saying "unknown user name or bad password". I have also tried:
runas /user:testuser c:/path/to/my/program.exe < c:/path/to/file/containing/password.txt
This comes back with the same error. Does anyone know a way to do this? What I'm trying to do eventually is get the batch file to read a username and password from a config file, and then start "program.exe" as that user.

The Batch-JScript hybrid script below do what you want. Save it with .bat extension.
#if (#CodeSection == #Batch) #then
#echo off
start "" runas /user:testuser c:/path/to/my/program.exe
CScript //nologo //E:JScript "%~F0"
goto :EOF
#end
WScript.CreateObject("WScript.Shell").SendKeys("password{ENTER}");
For further details, see this post

Related

Convert Batch file to Exe with administrator privileges

I have created a code in batch, which works perfectly only when I run it as administrator. If not, some of the main functions of the code does not work.
On top of that, I would like to convert it to exe, so that I can put an icon on.
Can anyone tell me please, how can I convert a batch file to exe with administrator privileges? If it is possible without uac prompt?
By the way: I am administrator on my PC.
I have tried with some software:
Iexpress -> Temp-file was not found.
Bat to Exe Converter -> After starting the .exe file it does not run as administrator, although I run it as.
That's the code:
#echo off
start "" "C:\Users\Viktor\Documents\FreeFileSync Auftraege\RealTimeSync Auftraege\RealTime_(.minecraft-GoogleDrive)_[Mirror].ffs_real"
start "" "C:\Users\Viktor\Documents\FreeFileSync Auftraege\RealTimeSync Auftraege\RealTime_(.minecraft-Backupfolder)_[Mirror].ffs_real"
start "" "C:\Program Files (x86)\Minecraft\MinecraftLauncher.exe"
:Anfang
tasklist /v | find "MinecraftLauncher.exe"
if %errorlevel% == 1 goto Dead
tasklist /FI "IMAGENAME eq javaw.exe" 2>NUL | find /I /N "javaw.exe">NUL
if %errorlevel% == 0 goto Active
goto Anfang
:Active
tasklist /v | find "javaw.exe"
if %errorlevel% == 1 goto Dead
goto Active
:Dead
timeout 5
taskkill /F /IM "RealTimeSync_x64.exe"
exit
It works only with "run as administrator". Without, some functions like taskkill or tasklist does not work.
I succeeded with Bat to Exe Converter available here : https://www.majorgeeks.com/files/details/bat_to_exe_converter.html
Simple GUI to transform batch to exe with administrator privileges.
Here is how you can make your .bat to .exe file require administrator privileges to run:
Download Bat To Exe Converter from Softpedia.com:
https://www.softpedia.com/get/System/File-Management/Batch-To-Exe-Converter.shtml (Version 3.2 seems to be a good option due to it's easy layout/interface.)
Once downloaded, go through the install the application and run said application.
Input code into the IDE window, ensuring that you check the box (under the options tab) that says "Request Administrator Privileges"
Now click convert, and continue through the prompts and you will have your .exe file ready for use!

Batch script to open command prompt but not execute the command

Can anyone pls suggest me how to create a batch file that would open up the command window but just type the command I have specified. It should get executed only when I hit enter manually. eg., I created the below .bat file:
test.bat
cmd.exe /K "cd D:\Code_Home && D: && cls && dir"
Now the problem is that it opens up the command window and lists the directory contents, whereas I just want the dir command to stay there and not list me the directory contents until I manually hit enter. Pls suggest if there is a way to do that
I copied the accepted answer at How can I run cmd from batch file and add text to line without executing? and slightly adjust it in order to solve this question:
#if (#CodeSection == #Batch) #then
#echo off
rem Enter the prefill value in the keyboard buffer
CScript //nologo //E:JScript "%~F0" "cd D:\Code_Home & D: & cls & dir"
cmd.exe
goto :EOF
#end
WScript.CreateObject("WScript.Shell").SendKeys(WScript.Arguments(0));
Further details at the given link.

How to run a batch command in Windows as a different user without typing the password?

I am trying to run a simple windows batch command as a one-liner on a windows command prompt, without having to specify the password. The user is named 'alex', so I am trying:
>cmd /C echo PASSWD | runas /profile /user:alex "cmd /c dir"
but I get the following error:
Enter the password for alex:
Attempting to start cmd /c dir as user "ALEX-NEU\alex" ..
RUNAS ERROR: Unable to run - cmd /c dir
1326: Logon failure: unknown user name or bad password.
where ALEX_NEU is the machine name. The user name and the provided password are correct - so why do I get this error? How to do it correctly?
The only way to supply the password to runas at runtime is with a script, and not terribly gracefully either. It's ugly, it's hackish, and it's asking for security troubles. Having said that, I've done something similar in the past with WScript.Shell's .run and .SendKeys methods like this:
#if (#a==#b) #end /* multiline JScript comment
:: runas.bat
:: runas with automated password entry
#echo off
setlocal enabledelayedexpansion
set "USER=username"
set "PASS=password"
set "CMD=cmd /c dir && pause"
:: delayed expansion prevents special characters from being evaluated
cscript /nologo /e:JScript "%~f0" !USER! !PASS! !CMD!
goto :EOF
:: end batch portion / begin JScript portion */
for (var i=0, args=[]; i<WSH.Arguments.length; i++)
args.push(WSH.Arguments(i).replace(/"/g, '^"')); // escape all quotes
var user = args[0],
pass = args[1],
cmd = ' "' + args.slice(2).join(' ') + '"',
oShell = new ActiveXObject("Wscript.Shell");
oShell.run('runas /noprofile /netonly /user:' + user + cmd);
WSH.Sleep(500);
oShell.SendKeys(pass + '{ENTER}');
This is a hack, only a proof of concept, and is largely untested. I have no idea whether it'll handle "quoted arguments" in the !CMD! variable. I daresay if you want to use it for practical applications, you'll have a great deal of revising and debugging in your future.
There are a couple of other embellishments to this method you might consider.

Run BAT as admin (w/o shortcut)

So, I am trying to create a .bat to taskkill a specific program in Win7.
I am using the command:
taskkill /f /im "LCore.exe"
The .bat needs to be run as admin in order to work it seems so I have created a shortcut to it to run automatically in admin mode as specified in another thread (How to code a BAT file to always run as admin mode?).
However, when using the Microsoft Mouse and Keyboard Center to map one of my additional keys to run the shortcut it automatically runs the target of the shortcut rather than the shortcut itself which doesn't have the admin privileges needed (when selecting to map the shortcut it automatically changes the path to the target, manually setting the path returns a 'not found' error).
So basically I was wondering if there is another way that doesn't involve creating a shortcut to automatically run a .bat with elevated privileges.
#ECHO OFF
OPENFILES>NUL 2>&1
IF "%ERRORLEVEL%"=="0" GOTO :YouAreAdmin
GOTO :GetAdmin
:GetAdmin
ECHO.Set UAC = CreateObject^("Shell.Application"^) > "StartAsAdmin.vbs"
ECHO.UAC.ShellExecute "%~fs0", "", "", "runas", 1 >> "StartAsAdmin.vbs"
StartAsAdmin.vbs
DEL "StartAsAdmin.vbs"
EXIT /B
:OK
REM Your code starts here!
ECHO.
ECHO. If you see this, you have started as admin this bat file.
PAUSE>NUL
EXIT
Sorry, but I am new! :)
So first, OPENFILES command checks if you have runned program as administrator, like any command that needs administrator privileges. If you type >NUL 2>&1 after a command, CMD will hide any message from that command and will redirect error. So if you have troubles running a simple command action like OPENFILES, the only error that you can have is that batch file doesen't have administrator privileges. And if %ErrorLevel% is 0 (you have no errors running that command), it seems that you started application as administrator, so it steps to :OK label. But if %ErrorLevel% is not 0 (there is a problem), it seems that application doesen't have administrator privileges. So it will start automatly as administrator from a temporary VBScript generated by that batch file, then is started, and then deleted.
In Windows 7 you don't need to write additional scripts, because it has built-in "PowerShell" instrument. Try the following :
powershell.exe start-process taskkill.exe -verb runas -argumentlist '/f /im "LCore.exe"'

>> Login screen : From Batch to VBscript and again to Batch <<

I am running a batch script and somewhere the user has to access a database.
At this moment, a window made in vbscript would prompt asking the user to type in the login and password. (OK, Cancel buttons)
If the credentials are correct after the OK, the batch would continue according to planA, otherwise the batch would do something else going to planB. If (Cancel), it would return to the batch and the menu above.
#echo off
:Ini
echo [1] Access database
echo [2] Main menu
echo:
set /p Quest= What do you prefer (1 / 2)?
if not '%Quest%'=='' set Quest=%Quest:~0,1%
if '%Quest%'=='1' goto VBS
if '%Quest%'=='2' goto BATCH
echo Invalid option, please try again
cls
goto Ini
:BATCH
echo Heading for main menu ...
goto Main
:VBS
cscript login.vbs
(...)
-- How to continue and make the vbs?
-- How to capture the user information, validate it and go back to the batch for the planA or planB ...
-- How to mask that password with ** ** ?
Help will be greatly appreciated !
Better switch to vbscript entirely (or since you seem new to vbscript another language more recent and powerfull while keeping it easy like Ruby). Everything you start from the batch can also be done in Vbscript, you can use prompt for the menu and inputbox for the password and if it has to be masked use a the browser as UI like the script from Rob Vanderwoude here http://www.robvanderwoude.com/vbstech_ui_password.php
Using this technique you can do all the UI/GUI in Internet Explorer and the logic in Vbscript.
If you decide to keep the batch approach, you can exit a vbs script with Wscript.Quit X, where x is the errorlevel you pass to windows when the script finishes, you can then trap that errorlevel in the batch. Alternative is to set or change an environment variable to do the trasfer of data, and last you can write data to textfiles easily in script and batch but the parsing of this in batch is more difficult.
I have found an intersting alternative as described below
http://www.computerhope.com/forum/index.php?topic=103686.0
VBSscript embeded in BATCH
#echo off
:wscript.echo InputBox("Enter your password","VBScript-Batch")
findstr "^:" "%~sf0" | findstr /i /v ":Label" >temp.vbs
for /f "delims=" %%N in ('cscript //nologo temp.vbs') do set pass=%%N
del temp.vbs
echo You entered %pass%
:Label1
echo continue from here
If %pass%=="ok" echo Valid Password ! & goto EOF
If %pass%=="ok" echo Invalid Password !! & goto EOF
:EOF
pause
As you see, if we eliminate the "& goto EOF" the script works well. It sends the VBS input "pass" to the batch and the batch echoes "continue from here", from where the rest of your code goes.
However, it is not working as it should. Any help to make this really work ?
Another alternative is ....
I have added in the existing VBSscript for "Internet Explorer version" the code :
VBS SCRIPT - named Password.vbs (see full script in the above link from Peter)
strPw = GetPassword( "Please, type your password:" )
WScript.Echo "Your password is: " & strPw
Sub Submit_OnClick
dim filesys, filetxt, FormContent
Set FormContent = document.getElementById("strPw")
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.OpenTextFile("C:\\temp.txt", 8, True)
filetxt.WriteLine(FormContent.value)
filetxt.Close
End Sub
BATCH SCRIPT
#echo off
cscript Password.vbs
findstr /B /E /M %strPw% temp.txt
If %ERRORLEVEL% EQU 0 echo Password matched! & goto EOF
If not %ERRORLEVEL% EQU 0 echo Invalid Password !! & goto EOF
:eof
pause
The file temp.TXT should be sent to the c:\ with the information the user typed on the inputbox. The batch would read this input and compare to a set password and continue the coding...
How can I make this work?? the temp.TXT is not generated an so forth ...
BATCH and VBS gurus out there, any help to solve these problems is really welcomed !

Resources