Saturday, March 29, 2008

Finding users on a subnet

For auditing and remote access purposes, identifying the computers and users on specified subnets can be useful. This post documents several methods that I've used in the past, including querying computers through AD, DNS, DHCP, SMS, and then finding the logon information through psloggedon, WMIC, or a custom VBScript.

Step 1 - Find computers on a subnet

There are several methods of finding this information, some more accurate than others depending upon your infrastructure:

SMS - Query SMS to find computers in a specific subnet or AD site:

  • wmic /namespace:\\root\sms\site_%sitecode% /node:"%sms_server%" path SMS_R_System WHERE "IPSubnets='%subnet%' AND Active=1'" get name
  • wmic /namespace:\\root\sms\site_%sitecode% /node:"%sms_server%" path SMS_R_System WHERE "ADSiteName='%AD_SITE_CODE%' AND Active=1'" get name

DNS - Query DNS to find machines on a specific subnet
Windows DNS

  • dnscmd %dns_Server% /enumrecords %zone% @ /additional /continue find /i "%subnet%"

Non-windows DNS - Just cat/grep/find/findstr the zone files.

DHCP - Windows DHCP, use netsh:

  • psexec \\%dhcp_server% cmd /c for %i in (%Subnet1% %Subnet2% %Subnet3%) do netsh dhcp server scope %i show clients 1
  • for /f "tokens=1" %i in ('"netsh dhcp server show scope 1 find /i "%description%""') do netsh dhcp server scope %i show clients 1 find /i "255.255" find /i "%prefix%"

Query AD for computers in an OU, ping the computers and return only those that respond to a ping (and can be resolved)

  • for /f %i in ('"dsquery computer %OU_DN% -o rdn"') do for /f "tokens=3 delims=: " %m in ('"ping -n 1 %i find /i "reply from""') do echo %i

Step 2 - Find who's logged on to those computers

Use psloggedon:

  • for /f %i in (computers.txt) do psloggedon \\%i

Use WMI:

  • for /f %i in (computers.txt) do wmic /node:"%computer%" PROCESS where "caption='explorer.exe'" getowner

Note that the psloggedon and WMI methods will be slow when processing computers that aren't on the network, wrap around a for /f ping command (see the OU query above).

Use the VBScript in this post:

  • cscript LoggedOn.vbs %computer1%,%computer2%,...

The VBScript is more verbose, providing information including human readable dates, and extra information such as whether a screensaver is running.

--- Script follows

Const DELIMITER = ","

If WScript.Arguments.UnNamed.Count > 0 Then
strComputerSet = WScript.Arguments.UnNamed(0)
WScript.Echo "Please supply one or more computers to process, separated by '" & DELIMITER & "'"
End If

For Each strComputer in Split(strComputerSet, DELIMITER) ' For each computer
If VerifyHostPing(strComputer) Then ' Is the computer responding to a ping?
Call FindLoggedOnUserExplorer(strComputer) ' Find the logged on users
End If

Function FindLoggedOnUserExplorer(ByRef strComputer)

Dim objWMI, strQuery, dtmCreationDate, strUser, dtmDifference, strUserInfo
Dim objProcessSet, objProcess, objProcessOwner, intCount

On Error Resume Next
Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
On Error Goto 0
If NOT IsObject(objWMI) Then
wscript.echo strComputer & ", " & "Could not connect to WMI"
Exit Function
End If

strQuery = "select __relpath, CreationDate from win32_process where caption = 'explorer.exe'"
set objProcessSet = objWMI.execQuery(strQuery)

If objProcessSet.Count = 0 then
wscript.echo strComputer & ", " & "No explorer processes found"
strUserInfo = ""
For Each objProcess in objProcessSet
Set objProcessOwner = objProcess.ExecMethod_("GetOwner") ' Execute the method to find the process owner
strUser = objProcessOwner.Domain & "\" & objProcessOwner.User
dtmCreationDate = objProcess.CreationDate ' The creation date of the explorer process
dtmCreationDate = ConvertDMTFToVB(dtmCreationDate, False)

strUserInfo = strUserInfo & vbCRLF & strComputer & ", " & strUser & ", " & dtmCreationDate
If Len(strUserInfo) >= Len(vbCRLF) Then strUserInfo = Right(strUserInfo, Len(strUserInfo) - Len(vbCRLF)) ' Strip the leading CRLF

strQuery = "select __relpath, CreationDate, ExecutablePath from win32_process where ExecutablePath like '%.scr'"
On Error Resume Next
set objProcessSet = objWMI.execQuery(strQuery)
intCount = -1
intCount = objProcessSet.Count
On Error Goto 0
If NOT IsObject(objProcessSet) OR intCount = -1 Then
wscript.echo strComputer & ", " & "Could not check for screensaver"
If intCount > 0 then ' Is there a screensaver running?
For Each objProcess in objProcessSet ' Yes
dtmCreationDate = objProcess.CreationDate ' Get the creation date of the process
dtmCreationDate = ConvertDMTFToVB(dtmCreationDate, False) ' Convert to VB datetime
dtmDifference = DateDiff("h", dtmCreationDate, Now) ' Different between now and then
strUserInfo = strUserInfo & ", " & "Screensaver is running: " & objProcess.ExecutablePath & " and has been for " & dtmDifference & " hours"
strUserInfo = strUserInfo & ", " & "Screensaver is not running"
End If
End If

End If
If strUserInfo <> "" Then wscript.echo struserinfo

End Function

Function VerifyHostPing(ByRef strComputer)
Dim objWMI, strQuery, i, objPings, objStatus

Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\root\cimv2")

VerifyHostPing = False
strQuery = "Select * From Win32_PingStatus where Address = '" & strComputer & "' AND BufferSize = 32 and Timeout = 300"

Set objPings = objWMI.ExecQuery(strQuery)

For Each objStatus in objPings
If IsNull(objStatus.StatusCode) OR objStatus.StatusCode <> ERROR_SUCCESS Then
wscript.echo "Warning: " & strComputer & " not contactable."
VerifyHostPing = False
wscript.echo "Successfully pinged " & strComputer
VerifyHostPing = True
End If

Set objPings = Nothing
Set objStatus = Nothing
Set objWMI = Nothing
End Function

Function ConvertDMTFToVB(dtmDate, blnTimeZone)
Dim strTemp, intTemp, strNow, strNowDate

strTemp = Left(dtmDate,4) & "/" & Mid(dtmDate,5,2) & "/" & Mid(dtmDate,7,2) & " " & Mid(dtmDate,9,2) & ":" & Mid(dtmDate,11,2) & ":" & Mid(dtmDate,13,2)
If Left(strTemp, 10) = "****/**/**" Then ' Ugly hack for schedule task times returned by WBEM that only contain time information
strNow = Now
strNowDate = DatePart("yyyy", strNow)
strNowDate = strNowDate & "/" & String(2 - Len(DatePart("m", strNow)),"0") & DatePart("m", strNow)
strNowDate = strNowDate & "/" & String(2 - Len(DatePart("d", strNow)),"0") & DatePart("d", strNow)
strTemp = strNowDate & " " & Right(strTemp, Len(strTemp)- 11)
End If
If IsDate(strTemp) Then
If blnTimeZone Then
strTemp = DateAdd ("h", Right(dtmDate,4)/60, strTemp) 'Add GMT offset
End If
ConvertDMTFToVB = FormatDateTime(strTemp,2) & " " & FormatDateTime(strTemp,4)
End If
End Function

Wayne's World of IT (WWoIT), Copyright 2008 Wayne Martin.


Anonymous said...

Thanks for this wayne, do you know any easy way to export the results from the command "for /f %i in (wslist.txt) do psloggedon \\%i" to a text file as such?

uraken said...

if you need to pipe these results to a txt file simple use >c:\results.txt
or to append use >>

All Posts

printQueue AD objects for 2003 ClusterVirtualCenter Physical to VirtualVirtual 2003 MSCS Cluster in ESX VI3
Finding duplicate DNS recordsCommand-line automation – Echo and macrosCommand-line automation – set
Command-line automation - errorlevels and ifCommand-line automation - find and findstrBuilding blocks of command-line automation - FOR
Useful PowerShell command-line operationsMSCS 2003 Cluster Virtual Server ComponentsServer-side process for simple file access
OpsMgr 2007 performance script - VMware datastores...Enumerating URLs in Internet ExplorerNTLM Trusts between 2003 and NT4
2003 Servers with Hibernation enabledReading Shortcuts with PowerShell and VBSModifying DLL Resources
Automatically mapping printersSimple string encryption with PowerShellUseful NTFS and security command-line operations
Useful Windows Printer command-line operationsUseful Windows MSCS Cluster command-line operation...Useful VMware ESX and VC command-line operations
Useful general command-line operationsUseful DNS, DHCP and WINS command-line operationsUseful Active Directory command-line operations
Useful command-linesCreating secedit templates with PowerShellFixing Permissions with NTFS intra-volume moves
Converting filetime with vbs and PowerShellDifference between bat and cmdReplica Domain for Authentication
Troubleshooting Windows PrintingRenaming a user account in ADOpsMgr 2007 Reports - Sorting, Filtering, Charting...
WMIC XSL CSV output formattingEnumerating File Server ResourcesWMIC Custom Alias and Format
AD site discoveryPassing Parameters between OpsMgr and SSRSAnalyzing Windows Kernel Dumps
Process list with command-line argumentsOpsMgr 2007 Customized Reporting - SQL QueriesPreventing accidental NTFS data moves
FSRM and NTFS Quotas in 2003 R2PowerShell Deleting NTFS Alternate Data StreamsNTFS links - reparse, symbolic, hard, junction
IE Warnings when files are executedPowerShell Low-level keyboard hookCross-forest authentication and GP processing
Deleting Invalid SMS 2003 Distribution PointsCross-forest authentication and site synchronizati...Determining AD attribute replication
AD Security vs Distribution GroupsTroubleshooting cross-forest trust secure channels...RIS cross-domain access
Large SMS Web Reports return Error 500Troubleshooting SMS 2003 MP and SLPRemotely determine physical memory
VMware SDK with PowershellSpinning Excel Pie ChartPoke-Info PowerShell script
Reading web content with PowerShellAutomated Cluster File Security and PurgingManaging printers at the command-line
File System Filters and minifiltersOpsMgr 2007 SSRS Reports using SQL 2005 XMLAccess Based Enumeration in 2003 and MSCS
Find VM snapshots in ESX/VCComparing MSCS/VMware/DFS File & PrintModifying Exchange mailbox permissions
Nested 'for /f' catch-allPowerShell FindFirstFileW bypassing MAX_PATHRunning PowerSell Scripts from ASP.Net
Binary <-> Hex String files with PowershellOpsMgr 2007 Current Performance InstancesImpersonating a user without passwords
Running a process in the secure winlogon desktopShadow an XP Terminal Services sessionFind where a user is logged on from
Active Directory _msdcs DNS zonesUnlocking XP/2003 without passwords2003 Cluster-enabled scheduled tasks
Purging aged files from the filesystemFinding customised ADM templates in ADDomain local security groups for cross-forest secu...
Account Management eventlog auditingVMware cluster/Virtual Center StatisticsRunning scheduled tasks as a non-administrator
Audit Windows 2003 print server usageActive Directory DiagnosticsViewing NTFS information with nfi and diskedit
Performance Tuning for 2003 File ServersChecking ESX/VC VMs for snapshotsShowing non-persistent devices in device manager
Implementing an MSCS 2003 server clusterFinding users on a subnetWMI filter for subnet filtered Group Policy
Testing DNS records for scavengingRefreshing Computer Account AD Group MembershipTesting Network Ports from Windows
Using Recovery Console with RISPAE Boot.ini Switch for DEP or 4GB+ memoryUsing 32-bit COM objects on x64 platforms
Active Directory Organizational Unit (OU) DesignTroubleshooting computer accounts in an Active Dir...260+ character MAX_PATH limitations in filenames
Create or modify a security template for NTFS perm...Find where a user is connecting from through WMISDDL syntax in secedit security templates

About Me

I’ve worked in IT for over 20 years, and I know just about enough to realise that I don’t know very much.