Search code examples
windowsbatch-fileauthenticationrunas

Command Batch Credential Authentication not working


Currently, I have a batch file in which I have a user input their username and password, but I want to authenticate that they're correct credentials before proceeding. Here's the relevant excerpt:

SET /p USERID="Enter user id: "
SET /p USERPASSWORD="Enter password: "
ECHO %USERPASSWORD% | RUNAS /noprofile /user:%userid% "notepad"

This returns an error stating that the username is unknown or the password is incorrect, even when the credentials offered are correct. Running the RUNAS command without the automated input and providing a password to its prompt works. Why is this failing? Is there a trailing space being inserted or something? Is there a better way to authenticate the Windows credentials, or another program that will do nothing and close immediately that I could run instead of Notepad?

Edit: The "user id" should also contain whatever domain you're on at the beginning. I also found that running "cmd.exe /C" was a better option, as it autocloses immediately, so that part of the question has been answered.

Double edit: According to this question here, runas has command line input disabled. This is odd, because it actually worked at first until I changed my password, and then failed. Therefore, what is a better way to authenticate the user's credentials?


Solution

  • I have found a solution.

    NET USE \\localhost\c$ %USERPASSWORD% /user:%USERID%
    NET USE /delete \\localhost\c$
    

    This attempts to add the local C drive as a network location, without specifying a destination drive. That avoids the problem of having a network drive already mapped to that location. After, it unlinks the mapped location, so it's ready to use again afterwards.

    To check if it was successful, simply check %errorlevel% with something similar to the following:

    IF %errorlevel% == 0 GOTO authenticationgood
    GOTO authenticationbad