Alex
Alex

Reputation: 44385

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?

Upvotes: 0

Views: 4312

Answers (1)

rojo
rojo

Reputation: 24476

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.

Upvotes: 2

Related Questions