Solved

vbscript returning null username from AD

Posted on 2009-07-08
22
541 Views
Last Modified: 2012-05-08
I have a vbs logon script that should capture the username, hostname & ip address for a user logging on to a windows 2003 network.  The network has 1200+ users and intermittently a script will return one or more null values for the username or host ip address when interogating AD.  There is no consistency that we can see - just a random occurrence.  Code is posted below but if anyone can shed some light on this I would be gratefull
Const ForReading = 1

Const ForWriting = 2 

Const ForAppending = 8

Const ADS_USE_ENCRYPTION = 2

Const ADS_SECURE_AUTHENTICATION = &H1

Const HKEY_CURRENT_USER = &H80000001

Const HKEY_LOCAL_MACHINE = &H80000002
 

Dim objns, objReg, objNetwork, objSysInfo, objNet, PCLog

strComputer = "."
 

'================ Objects 

Set objNetwork = CreateObject("WScript.Network")

Set objSysInfo = CreateObject("ADSystemInfo")

Set objfso = CreateObject("Scripting.FileSystemObject")

set objShell = CreateObject("WScript.Shell") 

Set objNet = CreateObject("WScript.NetWork") 

Set objns = GetObject("LDAP:")

Set objWMIService = GetObject("winmgmts:")

Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
 

strSysRoot = objShell.Environment("PROCESS").Item("SYSTEMROOT")

strAllUsersDesktop = objShell.SpecialFolders("AllUsersDesktop")

strDesktop = objShell.SpecialFolders("Desktop")

strProgramFiles = objShell.Environment("PROCESS").Item("PROGRAMFILES")
 

'================ Variables 

strPCLogPath = "\\DC\logonreport$\PC_Reports\"

strIPLogPath = "\\DC\logonreport$\IP_Reports\"

strUserLogPath = "\\DC\logonreport$\User_Reports\"
 

' Capture the computer name

strComputerName = objNet.ComputerName
 

' Capture the user logon name

On Error Resume Next

    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)

    For Each objItem in colItems

        strCurrentUser = objItem.UserName

Next

' strip domain and get username for file

strUserName = Mid(strCurrentUser,13)
 

' Open the logon report file or create a new one if it does not exist    

If objFSO.FileExists(strPCLogPath & strComputerName & ".txt") Then

	Set PCLog = objFSO.OpenTextFile(strPCLogPath & strComputerName & ".txt", ForAppending, True)

Else

	Set PCLog = objfso.CreateTextFile(strPCLogPath & strComputerName & ".txt", True)

End if
 

' Obtain machine location field from AD

strLocation = GetObjectLocation
 

' Capture IP Address

strIPAddress = GetIPAddress
 

Function GetIPAddress

Set objWMIService = GetObject("winmgmts:" _

    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set IPConfigSet = objWMIService.ExecQuery _

    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

For Each IPConfig in IPConfigSet

    If Not IsNull(IPConfig.IPAddress) Then 

        For i=LBound(IPConfig.IPAddress) to UBound(IPConfig.IPAddress)

            GetIPAddress = IPConfig.IPAddress(i)

        Next

    End If

Next	

End Function

Open in new window

0
Comment
Question by:cmdown
  • 11
  • 11
22 Comments
 
LVL 65

Accepted Solution

by:
RobSampson earned 250 total points
Comment Utility
Hi, for the username issue, you should be able to change this section:
' Capture the user logon name
On Error Resume Next
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)
    For Each objItem in colItems
        strCurrentUser = objItem.UserName
Next
' strip domain and get username for file
strUserName = Mid(strCurrentUser,13)


to just this
strUserName = objNet.UserName

This avoids having to use WMI, which may possibly have a permissions error when querying the Username.

For the IPAddress function, I've modified it slightly, as you can see below.  Perhaps the issue is because you were returning out of the Function before an actual IP Address was found.

Regards,

Rob.
Const ForReading = 1

Const ForWriting = 2 

Const ForAppending = 8

Const ADS_USE_ENCRYPTION = 2

Const ADS_SECURE_AUTHENTICATION = &H1

Const HKEY_CURRENT_USER = &H80000001

Const HKEY_LOCAL_MACHINE = &H80000002

 

Dim objns, objReg, objNetwork, objSysInfo, objNet, PCLog

strComputer = "."

 

'================ Objects 

Set objNetwork = CreateObject("WScript.Network")

Set objSysInfo = CreateObject("ADSystemInfo")

Set objfso = CreateObject("Scripting.FileSystemObject")

set objShell = CreateObject("WScript.Shell") 

Set objNet = CreateObject("WScript.NetWork") 

Set objns = GetObject("LDAP:")

Set objWMIService = GetObject("winmgmts:")

Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")

 

strSysRoot = objShell.Environment("PROCESS").Item("SYSTEMROOT")

strAllUsersDesktop = objShell.SpecialFolders("AllUsersDesktop")

strDesktop = objShell.SpecialFolders("Desktop")

strProgramFiles = objShell.Environment("PROCESS").Item("PROGRAMFILES")

 

'================ Variables 

strPCLogPath = "\\DC\logonreport$\PC_Reports\"

strIPLogPath = "\\DC\logonreport$\IP_Reports\"

strUserLogPath = "\\DC\logonreport$\User_Reports\"

 

' Capture the computer name

strComputerName = objNet.ComputerName

 

' Capture the user logon name

'On Error Resume Next

'    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)

'    For Each objItem in colItems

'        strCurrentUser = objItem.UserName

'Next

' strip domain and get username for file

'strUserName = Mid(strCurrentUser,13)

strUserName = objNet.UserName
 

' Open the logon report file or create a new one if it does not exist    

If objFSO.FileExists(strPCLogPath & strComputerName & ".txt") Then

	Set PCLog = objFSO.OpenTextFile(strPCLogPath & strComputerName & ".txt", ForAppending, True)

Else

	Set PCLog = objfso.CreateTextFile(strPCLogPath & strComputerName & ".txt", True)

End if

 

' Obtain machine location field from AD

strLocation = GetObjectLocation

 

' Capture IP Address

strIPAddress = GetIPAddress

 

Function GetIPAddress

	Set objWMIService = GetObject("winmgmts:" _

	    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

	Set IPConfig = objWMIService.ExecQuery _

	    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

	strIPAddress = ""

	For Each IPConfig in colComputerIP

		If Not IsNull(IPConfig.IPAddress) Then 

			For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)

				If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" Then strIPAddress = IPConfig.IPAddress(intIPCount)

			Next

		End If

	Next

	GetIPAddress = strIPAddress

End Function

Open in new window

0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
Hi Rob

Thanks for the reply.  The revised IP code returns an error - object not a collection for line
For Each IPConfig in colComputerIP
How should the collection be defined ? - Dim colComputerIP As New Collection.  Is anything else required ?
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Oh whoops, copy and paste error from some of my other code....This:
      Set IPConfig = objWMIService.ExecQuery _

should have been:
      Set colComputerIP = objWMIService.ExecQuery _

Regards,

Rob.
Const ForReading = 1

Const ForWriting = 2 

Const ForAppending = 8

Const ADS_USE_ENCRYPTION = 2

Const ADS_SECURE_AUTHENTICATION = &H1

Const HKEY_CURRENT_USER = &H80000001

Const HKEY_LOCAL_MACHINE = &H80000002

 

Dim objns, objReg, objNetwork, objSysInfo, objNet, PCLog

strComputer = "."

 

'================ Objects 

Set objNetwork = CreateObject("WScript.Network")

Set objSysInfo = CreateObject("ADSystemInfo")

Set objfso = CreateObject("Scripting.FileSystemObject")

set objShell = CreateObject("WScript.Shell") 

Set objNet = CreateObject("WScript.NetWork") 

Set objns = GetObject("LDAP:")

Set objWMIService = GetObject("winmgmts:")

Set objReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")

 

strSysRoot = objShell.Environment("PROCESS").Item("SYSTEMROOT")

strAllUsersDesktop = objShell.SpecialFolders("AllUsersDesktop")

strDesktop = objShell.SpecialFolders("Desktop")

strProgramFiles = objShell.Environment("PROCESS").Item("PROGRAMFILES")

 

'================ Variables 

strPCLogPath = "\\DC\logonreport$\PC_Reports\"

strIPLogPath = "\\DC\logonreport$\IP_Reports\"

strUserLogPath = "\\DC\logonreport$\User_Reports\"

 

' Capture the computer name

strComputerName = objNet.ComputerName

 

' Capture the user logon name

'On Error Resume Next

'    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'    Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem",,48)

'    For Each objItem in colItems

'        strCurrentUser = objItem.UserName

'Next

' strip domain and get username for file

'strUserName = Mid(strCurrentUser,13)

strUserName = objNet.UserName

 

' Open the logon report file or create a new one if it does not exist    

If objFSO.FileExists(strPCLogPath & strComputerName & ".txt") Then

	Set PCLog = objFSO.OpenTextFile(strPCLogPath & strComputerName & ".txt", ForAppending, True)

Else

	Set PCLog = objfso.CreateTextFile(strPCLogPath & strComputerName & ".txt", True)

End if

 

' Obtain machine location field from AD

strLocation = GetObjectLocation

 

' Capture IP Address

strIPAddress = GetIPAddress

 

Function GetIPAddress

	Set objWMIService = GetObject("winmgmts:" _

	    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

	Set colComputerIP = objWMIService.ExecQuery _

	    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

	strIPAddress = ""

	For Each IPConfig in colComputerIP

		If Not IsNull(IPConfig.IPAddress) Then 

			For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)

				If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" Then strIPAddress = IPConfig.IPAddress(intIPCount)

			Next

		End If

	Next

	GetIPAddress = strIPAddress

End Function

Open in new window

0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
Thanks Rob
That's going through.  Should find out in next 24 hours if it has resolved the problem.
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
No problem. Hopefully it's OK.

Rob.
0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
hi Rob
Sorry to say that I'm still getting null values returned - IP as 0.0.0.0 and username as "".  These values are set when the variables are declared at the start of the script but the respective functions clear these values before searching the AD records.  Could the function fail to call for any reason ?
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Hey wait a second....Am I missing some code?  I'm missing a GetObjectLocation function, and also missing any code that writes output to the file......

Did I miss that?  Are you able to post the code for me to look at?

Regards,

Rob.
0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
Hi Rob
Sorry for the delay - been away on holiday.  I'll upload the full script when I'm back in the office tomorrow.
Regards, Chris
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Hi Chris, any update on this?

Regards,

Rob.
0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
Hi Rob
Sorry - been off until today.  Full script attached - anonymised.
Could I be very cheeky and ask you if youy would mind also having a look at a question I've posted today (Q_24624505) as this also requires a vbscript solution.
Regards
Chris
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Hi, I can't seem to find the script.....

Hopefully I'm not going blind....

Rob.
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 1

Author Comment

by:cmdown
Comment Utility
Right ... EE is looking inside the zip and not allowing vbs upload  - I must have missed the warning message yesterday!  Renamed to .txt and attached herewith.
 
 

EElogon.vbs.txt.zip
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
OK, I'll test this out tomorrow....
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Hmmm, maybe we'll have to break it down a bit.  Try just this code, and type in one of those machines that is reporting a 0.0.0.0

The script should retrieve all valid IPs assigned to a machine.

Regards,

Rob.
Dim strComputer

strComputer = InputBox("Enter computer name to retrieve IP Address:", "Computer Name")

MsgBox GetIPAddress
 

' revised GetIPAddress Function

Function GetIPAddress

	Set objWMIService = GetObject("winmgmts:" _

	    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

	'Set IPConfig = objWMIService.ExecQuery _

	Set colComputerIP = objWMIService.ExecQuery _

	    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

	strIPAddress = ""

	For Each IPConfig in colComputerIP

		If Not IsNull(IPConfig.IPAddress) Then 

			For intIPCount = LBound(IPConfig.IPAddress) To UBound(IPConfig.IPAddress)

				If IPConfig.IPAddress(intIPCount) <> "0.0.0.0" Then

					If strIPAddress = "" Then

						strIPAddress = IPConfig.IPAddress(intIPCount)

					Else

						strIPAddress = strIPAddress & VbCrLf & IPConfig.IPAddress(intIPCount)

					End If

				End If

			Next

		End If

	Next

	GetIPAddress = strIPAddress

End Function

Open in new window

0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
Hi Rob
Thanks for this. Needless to say the ones that regularly report this issue are turned off at the moment. As these machines are in a school that is mostly closed for the summer holidays it may be a while until I can locate or get access to them.  Can we put this Q on hold until I get back in touch ?
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
We can't really put it on hold, as the cleanup process will probably close it after a month or so with no activity, but if we let it close out, you can still post comments on it, at which time you can post a new question, and post the link to it here, so that I see it.

No hurry, see how you go.

Regards,

Rob.
0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
hi Rob
I'm still looking into this - although I've been off for a few days and come back to a conficker infestation - so much for wsus !
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Oh bugger!  Good luck with that....wsus won't do the full job, you'll need some anti-virus protection too, but I'm sure you have that...

No problem. Take your time.

Regards,

Rob.
0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
Hi Rob
I think we're on top of the outbreak now.  I'll try and have another look at this tomorrow.
Regards
Chris
 
0
 
LVL 65

Expert Comment

by:RobSampson
Comment Utility
Sure, no worries. Thanks for the update.

Rob.
0
 
LVL 1

Author Comment

by:cmdown
Comment Utility
Hi Rob
I think the null IP issue is sorted now thanks to your fix.  Just checking on the null usernames.
0
 
LVL 1

Author Closing Comment

by:cmdown
Comment Utility
Thanks Rob.  I've been off unwell but I'm please to say that having incorporated your script modification into our logoff script as well we've not had any null username or IP details returned since 2nd Nov.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Installing a printer using group policy preferences is not that hard let’s take a look at it. First lets open up your group policy console and edit the policy you want to add it to. I recommend creating a new policy for each printer makes it a l…
This article is the result of a quest to better understand Task Scheduler 2.0 and all the newer objects available in vbscript in this version over  the limited options we had scripting in Task Scheduler 1.0.  As I started my journey of knowledge I f…
This tutorial will walk an individual through the steps necessary to join and promote the first Windows Server 2012 domain controller into an Active Directory environment running on Windows Server 2008. Determine the location of the FSMO roles by lo…
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now