简体   繁体   English

如何在Windows中以其他用户身份运行批处理命令而无需输入密码?

[英]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. 我试图在Windows命令提示符下以单行代码的形式运行一个简单的Windows批处理命令,而不必指定密码。 The user is named 'alex', so I am trying: 用户名为“ alex”,因此我正在尝试:

>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. 其中ALEX_NEU是计算机名称。 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. 在运行时将密码提供给runas的唯一方法是使用脚本,而且也不是很完美。 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: 话虽这么说,我过去使用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}');

This is a hack, only a proof of concept, and is largely untested. 这是一个hack,仅是概念的证明,并且未经测试。 I have no idea whether it'll handle "quoted arguments" in the !CMD! 我不知道它是否会处理!CMD!中的“引用参数” !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. 您可能会考虑使用此方法的其他一些修饰

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM