Solved

VBScript find remote username

Posted on 2007-11-29
16
7,030 Views
Last Modified: 2008-07-25
Hi all.

I have a VBScript that lists all online computers in our domain and then finds their IP Address, MAC Address and Serial Number, which gets organized into an Excel File

I would like to be able to find out the main user of the desktop/laptop. There will be multiple user profiles on most PC's, so I would consider the largest profile (in MB) to be the default one. If I had a variable called 'HostName', could you write a vbs function to tell me the default user of that machine?

Thanks in advance.
0
Comment
Question by:Ryan_R
16 Comments
 
LVL 10

Expert Comment

by:dis1931
ID: 20379303
Hello Ryan_R,

Yes, you could use WMI To get the last logged in user...but that may not really be the owner it will just be the last person who used it.  You could use WMI to loop through the documents and settings folder and check size of the folders...and take the largest one and pass it back....


Regards,

dis1931
0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20379564
That's great - can you provide an example - I'm no expert at vb scripting unfortunately (or at WMI)
0
 
LVL 17

Expert Comment

by:wobbled
ID: 20380669
I'd be a little hesitant to assume the largest profile as that PC's main user.  Many users seem to think their desktop is an ideal storage spot for all their files and if they log onto other PC's then this can ruin the accuracy of your data.

To get the current user using the winmgts here is a function.  What you could do is create a VB script that runs on a users startup.  Include in it their username, PC name etc.  Each time this runs it could deposit this data as line in a database or spreadsheet.  Allow this to run for a couple of weeks and then group your data by username.  You should then be able to effectively locate that user A uses PC x most of the time etc

Public Function NTUser() As String  
Dim objWMISvc As Object, colItems As Object
Dim objItem As Object

    Set objWMISvc = GetObject("winmgmts:\\.\root\cimv2")
    Set colItems = objWMISvc.ExecQuery("Select * from Win32_ComputerSystem", , 48)
    For Each objItem In colItems
        Debug.Print "User Name: " & objItem.UserName
        NTUser = objItem.UserName
    Next

End Function

0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20380697
I'll try that out after the weekend.

Perhaps there is a way to see how many times each user has logged in to a specific PC during the past 2 weeks?

Hope you guys like challenges, because this is already over my head  :o)
0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20432230

Do any of you know of some script code that I could try out?
0
 
LVL 3

Expert Comment

by:chunkDJ
ID: 20469772
Hi Ryan
Which angle are you wanting to try out?  The script to record details at login, or something to check user profiles, for example, taking the most recent 'last accessed' date.  I can give you a hand with either.

Cheers
chunkDJ
0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20469806
I think the best method would be to check the size of \\computer\c$\Documents and Settings\username and assume that the largest folder is primary user. However, it would probably also be a good idea to check the last user acces date as well - and have two collumns - one for each check. If the last user who accessed a PC is one of the IT staff, then they can be dismissed as not being the main users.

Thanks
0
 
LVL 3

Expert Comment

by:chunkDJ
ID: 20469909
Ok.  How are you going to run the script?  Via a login script or from a PC?
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 15

Author Comment

by:Ryan_R
ID: 20469927
From my laptop - I will run a script that creates an Excel file and fills it with 4 collumns - Computer Name, IP Address, MAC Address, and Serial Number. I am hoping to modify the script and add 2 functions that will populate 2 more collumns - on for the last user who logged on and one for who has the largest profile on each machine.
0
 
LVL 3

Accepted Solution

by:
chunkDJ earned 500 total points
ID: 20469952
OK, here is some code which will get the last modified date/time for each profile in documents and settings.  Obviously you'll just need the bits to compliment what you already have.

As for the largest profile, that will require a bit more work, as you can't get this from WMI.  Do you have access to all the PCs via an admin share?  i.e. \\computer01\c$
Option Explicit
 

' This is the CSV file that will contain the conputer name, user profiles and last modified date.

Const OutputFile = "c:\ComputersUsers.csv"
 

Const wbemFlagReturnImmediately = &h10

Const wbemFlagForwardOnly = &h20
 

Const ForWriting = 2

Const ForAppending = 8
 

Dim fso : set fso = CreateObject("Scripting.FileSystemObject")

Dim flhOutput, strOutput
 

Dim arrComputers, computer

Dim objWMIService, colSubFolders, folder
 

' Place code here to compile an array of computer names on your network
 

arrComputers = Array("computer_name")
 

For Each computer In arrComputers
 

	Set flhOutput = fso.opentextfile(OutputFile,ForWriting,true)

	If IsAlive(computer) Then

		
 

		Set objWMIService = GetObject("winmgmts:\\" & computer & "\root\CIMV2")

		Set colSubfolders = objWMIService.ExecQuery ("Associators of {Win32_Directory.Name='c:\Documents and Settings'} " _

		 & "Where AssocClass = Win32_Subdirectory ResultRole = PartComponent")
 

		For Each folder In colSubfolders

			strOutput = computer & "," & folder.Name & "," & WMIDateStringToDate(folder.LastModified)

			flhOutput.Writeline strOutput

		Next

	

	End If

	

Next
 

Function IsAlive(target)

	Dim PingResults    

	Dim PingResult     

	Dim return_value

	Dim strComputer

	strComputer = "."

	Set PingResults = GetObject(_

		"winmgmts://" & strComputer & "/root/cimv2"). ExecQuery("SELECT StatusCode, ProtocolAddress FROM Win32_PingStatus " & _

			"WHERE Address = '" & target & "'")

	For Each PingResult In PingResults

		If PingResult.StatusCode = 0 Then

			If LCase(Target) = PingResult.ProtocolAddress Then

				return_value = True

			Else

				return_value = True

			End If

		Else

			return_value = False

		End If

		IsAlive = return_value

	Next

End Function
 

Function WMIDateStringToDate(dtmDate)

	WMIDateStringToDate = CDate(Mid(dtmDate, 5, 2) & "/" & _

	Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _

	& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))

End Function

Open in new window

0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20469958
Thanks - I'm just on my wa out (Friday night) so you'll have to wait until I get back to work for all the feedback.
0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20470294
Just reading the code from home (can't really test it now) - but is that script only just telling me when the date when the 'Docs & Settings' folder was last modified instead of the Name of the subfolder in Docs and Settings that was last modified?

Also do you have a function that returns the name of the largest subfolder in Docs and Settings?

If you want me to post my current script - let me know.
0
 
LVL 3

Expert Comment

by:chunkDJ
ID: 20470341
The script writes the computer name, profile folder name, and date last modified.  
If you can post what you have I'll combine the two over the weekend.  
Haven't done the folder size yet, see my last post re questions regarding that.

Cheers
chunkDJ
0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20503488
Hi again - here's the current vbscript
Option Explicit

Dim Row, XL, WshShell, FileSystem, RegularExpression, Dummy, TheNVFile, TheLine

Dim Whacks, WhacksFound, WhacksPattern,  Flag, HostName, NBTable, PingReport, PingPattern

Dim IPAddress, MACPattern, MACAddress, Matches, TheMatch, Match, NBCommand, TheNBTFile

Dim IPCommand, TheIPFile, FileName, TheDate, Suggestion, Book, SerialNo
 

Const ForReading = 1

Row = 2
 

Set XL = WScript.CreateObject("Excel.Application")

Set WshShell = WScript.CreateObject("WScript.Shell")

Set FileSystem = CreateObject("Scripting.FileSystemObject")

Set RegularExpression = New RegExp
 

Dummy = WshShell.Popup ("Compiling Network Address Inventory.  Please Wait...",1,"PC Inventory Utility",64)
 

Call BuildSpreadSheet()
 

WshShell.Run "Cmd.exe /c Net View > C:\Windows\Temp\NetViewList.txt", 2,True

Set TheNVFile = FileSystem.OpenTextFile("C:\Windows\Temp\NetViewList.txt", ForReading, True)
 

Do While TheNVFile.AtEndOfStream <> True

	TheLine = TheNVFile.ReadLine

	Whacks = "\\"

	WhacksFound = FindPattern(TheLine, Whacks)

	If WhacksFound Then

		XL.Cells(Row, 1).Value = "Gathering Information..."

		WhacksPattern = "\\\\\S*"

		Flag = "1"

		HostName = GetPattern(TheLine, WhacksPattern, Flag )

		NBTable = GetNBTable(HostName)

		MACPattern = "MAC Address = \S*"

		Flag = "2"

		MACAddress = GetPattern(NBTable, MACPattern, Flag )

		PingReport = GetIPAddress(HostName)

		PingPattern = "Reply from \S*"

		Flag = "3"

		IPAddress = GetPattern(PingReport, PingPattern, Flag )

		IPAddress = Replace(IPAddress, ":", "") 

		SerialNo = GetSerial(HostName)

		Call AddToSpreadSheet(HostName, IPAddress, MACAddress, SerialNo)

	End If

Loop    
 

TheNVFile.Close

FileSystem.DeleteFile("C:\Windows\Temp\NetViewList.txt")
 

Row = Row + 1

XL.Cells(Row, 1).Value = "Created " & WeekdayName(Weekday(Date), False, vbSunday) & " " & Day(Date) & " " & MonthName(Month(Date)) & " " & Year(Date)

XL.Cells(Row, 1).Font.Italic = True

'Dummy = WshShell.Popup ("Network Address Inventory Operation Complete",5,"PC Inventory Utility",64 )

Call SaveSpreadSheet()

Wscript.Quit
 

Sub BuildSpreadSheet()

	XL.Visible = True

	Set Book = XL.WorkBooks.Add

	XL.Columns(1).ColumnWidth = 20

	XL.Columns(2).ColumnWidth = 20

	XL.Columns(3).ColumnWidth = 20

	XL.Columns(4).ColumnWidth = 30

	XL.Cells(1, 1).Value = "Host Name"

	XL.Cells(1, 2).Value = "IP Address"

	XL.Cells(1, 3).Value = "MAC Address"

	XL.Cells(1, 4).Value = "Serial No."

	XL.Range("A1:D1").Select

	XL.Selection.Font.Bold = True

	XL.Selection.Font.Size = 12

End Sub
 

Sub AddToSpreadSheet(HostName, IPAddress, MACAddress, SerialNo)

	XL.Cells(Row, 1).Value = HostName

	If IPAddress <> HostName Then XL.Cells(Row, 2).Value = IPAddress

	If MACAddress <> HostName Then XL.Cells(Row, 3).Value = MACAddress

	XL.Cells(Row, 4).Value = SerialNo
 

	Row = Row + 1

	XL.Cells(Row, 1).Select

End Sub
 

Sub SaveSpreadSheet()

	TheDate = Date

	TheDate = Replace(TheDate, "/", "-")

	Suggestion = "PC Inventory " & TheDate & ".xls"

	FileName = XL.GetSaveAsFilename(Suggestion)

	If FileName <> False Then

		Book.SaveAs(FileName)

	End If

End Sub  
 

Function FindPattern(TheText, ThePattern)

	RegularExpression.Pattern = ThePattern

	If RegularExpression.Test(TheText) Then

		FindPattern = "True"

	Else

		FindPattern = "False"

	End If

End Function
 

Function GetPattern(TheText, ThePattern, Flag)

	RegularExpression.Pattern = ThePattern

	Set Matches = RegularExpression.Execute(TheText) 

	For Each Match in Matches

		TheMatch = Match.Value 

		If Flag = "1" Then TheMatch = Mid(TheMatch, 3)

		If Flag = "2" Then TheMatch = Mid(TheMatch, 14)

		If Flag = "3" Then TheMatch = Mid(TheMatch, 11)

	Next

	GetPattern = TheMatch

End Function
 

Function GetNBTable(HostName)

	NBCommand = "nbtstat -a " & HostName

	WshShell.Run "Cmd.exe /c " & NBCommand &" > C:\Windows\Temp\NBTList.txt", 2,True

	Set TheNBTFile = FileSystem.OpenTextFile("C:\Windows\Temp\NBTList.txt", ForReading, True)

	GetNBTable = TheNBTFile.ReadAll

	TheNBTFile.Close

	FileSystem.DeleteFile("C:\Windows\Temp\NBTList.txt")

End Function
 

Function GetIPAddress(HostName)

	IPCommand = "ping -n 1 " & HostName

	WshShell.Run "Cmd.exe /c " & IPCommand &" > C:\Windows\Temp\IPList.txt", 2,True

	Set TheIPFile = FileSystem.OpenTextFile("C:\Windows\Temp\IPList.txt", ForReading, True)

	GetIPAddress = TheIPFile.ReadAll

	TheIPFile.Close

	FileSystem.DeleteFile("C:\Windows\Temp\IPList.txt")

End Function
 

Function GetSerial(strComputer)

	Dim objWMIService, colItems, objItem ',strComputer

    On Error Resume Next

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

    If Err.Number = 0 Then

		On Error GoTo 0

		Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_BIOS",,48)

        For Each objItem In colItems

            If Trim(objItem.SerialNumber) <> "" Then

				GetSerial = UCase(objItem.SerialNumber)

            End If

        Next

	Else

		'Dim strError

		'strError = "ERROR: " & Err.Number & " - " & Err.Description

		'If Err.Number = 462 Then strError = ""

		GetSerial = ""

		Err.Clear

        On Error GoTo 0

    End If   

End Function

Open in new window

0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20503498
As you can see, all I really need are 2 functions to add to the end of it that return the username for 1) the last user to logon a computer, and 2) the user with the largest profile on a copmuter. Then I just have to change the top of the script to make 2 more collumns and place the returned data in there.
0
 
LVL 15

Author Comment

by:Ryan_R
ID: 20538323
Any ideas???
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 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

11 Experts available now in Live!

Get 1:1 Help Now