如何在不键入密码的情况下以不同的用户身份在Windows中运行批处理命令?

时间:2014-11-22 15:54:27

标签: windows batch-file

我试图在Windows命令提示符下运行一个简单的Windows批处理命令,而不必指定密码。用户名为' alex',所以我正在尝试:

>cmd /C echo PASSWD | runas /profile /user:alex "cmd /c dir"

但是我收到以下错误:

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.

其中ALEX_NEU是机器名称。用户名和提供的密码是正确的 - 那么为什么我会收到此错误?如何正确地做到这一点?

1 个答案:

答案 0 :(得分:1)

在运行时向runas提供密码的唯一方法是使用脚本,也不是非常优雅。它很丑陋,它是黑客,它要求安全问题。话虽如此,我过去使用WScript.Shell .run.SendKeys这样的方法做了类似的事情:

@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}');

这是一个黑客,只是一个概念证明,并且很大程度上未经测试。我不知道它是否会处理&#34;引用的参数&#34;在!CMD!变量中。我敢说如果你想将它用于实际应用,你将来会进行大量的修改和调试。

您可能会考虑其他几个embellishments to this method

相关问题