We help IT Professionals succeed at work.

Vbscript needs to accept alternate username and password

2,508 Views
Last Modified: 2013-12-25
I have the following code I'd like to execute using alternate credentials given as agumanets on the command line. I could use PsExec, runas or other such program, however that is not what I desire, ease of use be damned ;)
I currently have it accepting arguments for ip address or dns name, but I'd like it to accept user and password arguments as well, possibly across domains, so I may also need a domain argument as well, unless domain\username will work just as well.

so far, all you need is "cscript inventory.vbs 10.1.1.3" or cscript inventory.vbs 10.1.1.3 10.1.1.4 if running against more than one PC. I'd like it to be more like: cscript inventory -s ip.ip.ip.ip -u admin -p superduper password
I found the prncnfg.vbs on XP to be very close to what I want, but I couldn't make it suit, let me know if you have any questions.
Wscript.Echo "<?xml version=" & Chr(34) & "1.0" & Chr(34) & "?>"
Wscript.Echo "<Inventory>"
Wscript.Echo 	"<Win32_Drives>"
Wscript.Echo 		"<HardDrive>"
On Error Resume Next
If Wscript.Arguments.Count = 0 Then
    arrComputers = Array(".")
Else
    Dim arrComputers()
    For i = 0 to Wscript.Arguments.Count - 1
        Redim Preserve arrComputers(i)
        arrComputers(i) = Wscript.Arguments(i)
    Next
End If
 
For Each strComputer in arrComputers
    Set objWMIService = GetObject _
        ("winmgmts:\\" & strComputer & "\root\cimv2")
 
Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk Where Description = 'Local Fixed Disk'")
	For Each objItem in colItems
	    WScript.Echo "<HD_VolumeName>" & objItem.VolumeName & "</HD_VolumeName>"
	    WScript.Echo "<HD_Description>" & objItem.Description & "</HD_Description>"
	    WScript.Echo "<HD_name>" & objItem.Name & "</HD_name>"
	    WScript.Echo "<HD_DeviceID>" & objItem.DeviceID & "</HD_DeviceID>"
	    WScript.Echo "<HD_Size>" & objItem.Size & "</HD_Size>"
	    Wscript.Echo "<HD_FreeSpace>" & objItem.FreeSpace & "</HD_FreeSpace>"
	    Wscript.Echo "<HD_FileSystem>" & objItem.FileSystem & "</HD_FileSystem>"
	    Wscript.Echo "<HD_SerialNumber>" & objItem.VolumeSerialNumber & "</HD_SerialNumber>"
	    Wscript.Echo "</HardDrive>"
	Next
    Wscript.Echo "</Win32_Drives>"
    Wscript.Echo "<PC_info>"
'	Get Local Login Information
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
	For Each objItem in colItems
	    Wscript.Echo "<Caption>" & objItem.Caption & "</Caption>"
	    Wscript.Echo "<CurrentTimeZone>" & objItem.CurrentTimeZone & "</CurrentTimeZone>"
	    Wscript.Echo "<Description>" & objItem.Description & "</Description>"
	    Wscript.Echo "<Domain>" & objItem.Domain & "</Domain>"
	    Wscript.Echo "<Manufacturer>" & objItem.Manufacturer & "</Manufacturer>"
	    Wscript.Echo "<Model>" & objItem.Model & "</Model>"
	    Wscript.Echo "<Machine_Name>" & objItem.Name & "</Machine_Name>"
	    Wscript.Echo "<UserName>" & objItem.UserName & "</UserName>"
	Next
    Wscript.Echo "</PC_info>"
    Wscript.Echo "<BIOS_Info>"
'	Get Bios info, includng Dell Tag, Bios Revision and Manufacturer
Set colItems = objWMIService.ExecQuery("Select * from Win32_BIOS",,48)
	For Each objItem in colItems
	    Wscript.Echo "<BIOS_Version>" & objItem.BIOSVersion & "</BIOS_Version>"
	    Wscript.Echo "<BIOS_Build_num>" & objItem.BuildNumber & "</BIOS_Build_num>"
	    Wscript.Echo "<BIOS_Description>" & objItem.Description & "</BIOS_Description>"
	    Wscript.Echo "<BIOS_Manufacturer>" & objItem.Manufacturer & "</BIOS_Manufacturer>"
	    Wscript.Echo "<BIOS_Name>" & objItem.Name & "</BIOS_Name>"
	    Wscript.Echo "<Dell_Tag>" & objItem.SerialNumber & "</Dell_Tag>"
	    Wscript.Echo "<BIOS_Status>" & objItem.Status & "</BIOS_Status>"
	    Wscript.Echo "<BIOS_Version>" & objItem.Version & "</BIOS_Version>"
	Next
	    Wscript.Echo "</BIOS_Info>"
	    Wscript.Echo "</Inventory>"
Next

Open in new window

Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014

Commented:
Hi, as far as I know, you're going to have to use PSExec, and things are going to get a bit complicated.  See the code below for an example of using parameters for credentials, then having the script use PSExec to relaunch the script, which would then be running as another user.

Also though, because you need extra parameters, I would use named arguments, so that you identify the purpose of each argument better:

http://www.microsoft.com/technet/scriptcenter/resources/qanda/may06/hey0505.mspx

Regards,

Rob.
Option Explicit
 
' Declare variables to store values and act as objects
Dim strArgs, strAdminUser, strAdminPass, strPSExecPath
Dim objFSO, wshNetwork, strComputer, objShell, strCommand, objTextFile
Const ForReading = 1
 
' Set up a File System Object for any required File manipulations
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
' Set up a Network object for any required Network operations, like determining host name or user name
Set wshNetwork = WScript.CreateObject("WScript.Network")
' Set up a Shell object to perform shell commands, like running an external program
Set objShell = WScript.CreateObject("WScript.Shell")
 
' This checks if THIS script was run using a parameter as an argument.
' You see later an argument of "AsAdmin" is passed to this script
' so that it branches off to execute different code.
If WScript.Arguments.Count < 1 Then
	MsgBox "No Username and Password was supplied as script parameters. Please check."
ElseIf WScript.Arguments.Count = 2 Then
	' If there are two arguments, assume these are the username and password
	strAdminUser = WScript.Arguments.Item(0)
	strAdminPass = WScript.Arguments.Item(1)
    Call Normal_User_Commands(strAdminUser, strAdminPass)
ElseIf WScript.Arguments(0) = "AsAdmin" Then
    ' If there is an argument of "AsAdmin" then assume it has been
    ' re-run by this script, under the Administrative credentials
    ' supplied previously, using PSExec
    Call Admin_User_Commands
Else
    MsgBox "Unknown Argument received"
End If
 
' These commands are run is there are no arguments to the script
' ie. when it is initially run by a normal user at logon
Sub Normal_User_Commands(strAdminUser, strAdminPass)
    MsgBox "Running as initiating user"
    strComputer = wshNetwork.ComputerName
    strPSExecPath = "\\server\share\psexec_185.exe"
    strPSExecPath = objFSO.GetFile(strPSExecPath).ShortPath
    ' This command assumes that PSExec.exe (available from Microsoft) is stored on the shared folder
    ' below.  It runs PSExec as the Admin user, on a remote machine, or the current machine if it is a
    ' logon script.  It re-runs this file again, this time passing the "AsAdmin" argument, so the script
    ' knows it has been run under an Admin account, and can safely execute the Admin_User_Commands Sub.
    strCommand = strPSExecPath & " \\" & strComputer & " -accepteula -e -i -u " & strAdminUser & " -p " & strAdminPass & " wscript.exe " & objFSO.GetFile(WScript.ScriptFullName).ShortPath & " ""AsAdmin"""
    'MsgBox strCommand
    objShell.Run strCommand, 0, False
    ' NOTE: In the above two lines, you can change the cmd /c to cmd /k and the strCommand, 0, True to strCommand, 1, True
    ' if you wish to see some output for debugging / testing purposes.
End Sub
 
Sub Admin_User_Commands
      ' Now the script has detected that "AsAdmin" was passed to it, and will run these commands.
      'Now running as Administrator on the target macchine
      MsgBox "Running as Admin"
      ' In this command, the /ga flag sets the printer for all users, and the /in flag tells it to connect a network printer.
      strCommand = "cmd /c \\server\share\winzip\setup.exe"
      'objShell.Run strCommand, 0, True
    ' NOTE: In the above two lines, you can change the cmd /c to cmd /k and the strCommand, 0, True to strCommand, 1, True
    ' if you wish to see some output for debugging / testing purposes.
End Sub

Open in new window

Rich RumbleSecurity Samurai
CERTIFIED EXPERT
Top Expert 2006

Author

Commented:
No, I know it can be done, I guess I should of specified I'm connecting to WMI
Also if you look at xcacls.exe
http://www.microsoft.com/downloads/details.aspx?familyid=0ad33a24-0616-473c-b103-c35bc2820bda&displaylang=en
 or c:\windows\system32\prncnfg.vbs (on XP) you can see examples of these kinds of arguments being passed to the vbs. The printer config vbs is a better example I think. (look around line 997)

http://msdn.microsoft.com/en-us/library/aa389290(VS.85).aspx#connecting_to_remote_computers

These are basically ready to go, but I don't want the wscript prompts:Wscript.StdOut.Write "Please enter your password:"

let me know what you think
-rich
Rich RumbleSecurity Samurai
CERTIFIED EXPERT
Top Expert 2006

Author

Commented:
I meant xcacls.vbs rather than exe.
-rich
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014

Commented:
Oh yeah, I should have looked more closely.

Because you are using WMI to pull all of the information, and not actually running other programs, you should be able to use the approach taken here:

http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1213.mspx

So you can just continue to take the parameters as you have done, and use them in the "objwbemLocator.ConnectServer" method.

Regards,

Rob.
Rich RumbleSecurity Samurai
CERTIFIED EXPERT
Top Expert 2006

Author

Commented:
Correct, however, I've been struggling with writing the code to do that, at least merging it with the code snipit above in my question. As the scripting guys say at the very end of the article "One thing we should add is that we dont recommend you hardcodepasswords (especially Administrator passwords) in your scripts.Instead, you should make allowances to enter the password as acommand-line argument or via an Input box or whatever works best foryou."

Their examples don't allow for the command line arguments, and again I don't want the "pop-up" wscript input boxes. I would like cscript script.vbs -u user -p pass -s ip/or_dns_name(s)

And I couldn't get the "hardcoded" username and password to work, so I turned to scripts like c:\windows\system32\prncnfg.vbs and I'm no programmer, so I started to mess up my own code pretty quick ;) The script should work on win2k and above if you can try to merge the methods used in the print script or from the msdn article I linked to last.
-rich
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Rich RumbleSecurity Samurai
CERTIFIED EXPERT
Top Expert 2006

Author

Commented:
Worked perfectly! Thanks!
-rich
Rich RumbleSecurity Samurai
CERTIFIED EXPERT
Top Expert 2006

Author

Commented:
Very nice, works just as I expected it should. I may post another question soon, thanks for hanging in there!
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014

Commented:
Thanks for the grade.

Regards,

Rob.
Rich RumbleSecurity Samurai
CERTIFIED EXPERT
Top Expert 2006

Author

Commented:
What about if a password contains some non-alpha numeric characters... I had an issue when I tried to use a password like 18*nineteen and it errored with:
'*nineteen' is not recognized as an internal or external command,
operable program or batch file.
-rich
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014

Commented:
Try enclosing the password in quotes:
cscript script.vbs /s:192.168.21.231 /u:anadminuser /p:"yourpassword"

Regards,

Rob.
Rich RumbleSecurity Samurai
CERTIFIED EXPERT
Top Expert 2006

Author

Commented:
That does indeed work. Is there anything to be done if a password contains a quote (single or double).
I'm moving the script to an HTA and other Admin's passwords could contain such char's, I'm not certain if they do or don't. Just curious if there was something simple that could be done. Thanks again for your time!
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2014

Commented:
If you're moving it to a HTA, and getting the password via a text box (or a password box, to be more precise), then the ConnectServer method should be able to handle those characters, as far as I'm aware.  It's only parsing it through DOS that would have a problem with those characters.

Regards,

Rob.

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.