More Windows Scripting Workarounds from Nilpo - Implementing Password Masking
(Page 2 of 4 )
Implementing Password Masking
Okay, so you've created a script that requires a user to enter a username and password. Perhaps you're mapping a network drive or accessing a database. For whatever reason, it would be nice to mask the password input. Unfortunately, VBScript's InputBox method doesn't provide a means of accomplishing this.
Thankfully, Microsoft's developers thought of this. There is a little-known COM component capable of masking passwords. It does, however, have one small drawback. It relies on the use of Standard Input and Output streams, so you can only use this method when running scripts under the Cscript engine.
If LCase(Right(Wscript.FullName, 11)) <> "cscript.exe" Then
strPath = Wscript.ScriptFullName
strCommand = "%comspec% /k cscript " & Chr(34) & strPath & chr(34)
CreateObject("WScript.Shell").Run(strCommand)
Wscript.Quit
End If
We'll begin our script with a snippet from volume one of this series. This portion ensures that our script always runs under Cscript.
WScript.StdOut.Write "Enter Username: "
strUser = WScript.StdIn.ReadLine
The next section uses some basic techniques for accessing the standard streams. It first writes a prompt for a username to the StdOut stream and then awaits the user response, which it reads from the StdIn stream.
Set ScriptPW = CreateObject("ScriptPW.Password")
WScript.StdOut.Write "Enter password: "
strPass = ScriptPW.GetPassword()
WScript.StdOut.WriteLine ""
Next, we turn again to the standard streams for the password prompt and response, but this time we do things a little bit differently. Instead of accessing the StdIn stream directly, we're going to access it through the ScriptPW object. This object works with the CMD environment and masks the StdOut stream while it is in use. The ScriptPW's GetPassword method does the magic. It masks the real time output of the StdOut stream and returns the value of the StdIn stream. Thus, it returns a text string containing the characters that were masked on screen.
WScript.Echo ""
WScript.Echo "You entered the password: " & strPass
This simple test demonstrates the validity of the code.
The ScriptPW object is available on Windows XP and Windows Server 2003. You can add the functionality to Windows Vista or older operating systems by copying the scriptpw.dll file from an XP or 2003 machine. You'll need to register the new COM object before use.
Next: Masking Passwords without ScriptPW >>
More Windows Scripting Articles
More By Nilpo