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

问题描述:

我想在windows命令提示符下运行一个简单的windows批处理命令,而不必指定密码。用户名为“亚历克斯”,所以我想:如何在不输入密码的情况下以不同的用户身份在Windows中运行批处理命令?

>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是机器名。用户名和提供的密码是正确的 - 那么为什么我会得到这个错误?如何正确地做到这一点?

+2

你不能。请参阅http://blogs.msdn.com/b/oldnewthing/archive/2004/11/29/271551.aspx。您必须编写自己的程序才能在该博客中提到。有一种[丑陋的黑客](http://techtorials.me/windows/using-runas-with-a-password/),看起来并不怎么样。如果用户的密码在证书管理器中,您可以[也可以这样做](http://serverfault.com/questions/7620/windows-run-as-without-knowing-the-password)。但是,这个问题属于http://superuser.com。 – 2014-11-22 15:58:04

在运行时向密码runas提供密码的唯一方法是使用脚本,而且不会非常优雅。这很丑陋,它很危险,它要求安全方面的麻烦。话虽如此,我已经做了与WScript.Shell.run.SendKeys方法,这样过去的类似的东西:

@if (@[email protected]) @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}'); 

这是一个黑客,只是一个概念证明,并且大部分都未经检验。我不知道它是否会处理!CMD!变量中的“引用参数”。我敢说,如果你想在实际应用中使用它,你将在未来进行大量的修改和调试。

有一些其他embellishments to this method你可能会考虑。