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

前端 未结 1 465
忘掉有多难
忘掉有多难 2021-01-28 00:08

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:

相关标签:
1条回答
  • 2021-01-28 00:57

    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.

    0 讨论(0)
提交回复
热议问题