Saturday, June 20, 2020

Finding where a user is logging on from

For years I’ve been using a doskey macro I created to Find a User.

In an enterprise environment, the logic is:

  • Every normal user account has their home server mapped automatically, establishing a persistent SMB session with the home server from their workstation 
  • Find the home server and query it to find the where the user is connecting from 
  • Resolve the address and report who is connecting from where.

A few limitations:

  1. This will only work if the home server is a Windows box 
  2. You will need permissions to query win32_serversession of the home remotely (typically admin) 
  3. If the person is connecting over Citrix or DirectAccess or another jump box, it will resolve to that source, instead of (or sometimes as well as) a workstation.

A quick PowerShell equivalent (with zero error checking):

function Find-User ($username) {
  $homeserver = ((get-aduser -id $username -prop homedirectory).Homedirectory -split "\\")[2]
  $query = "SELECT UserName,ComputerName,ActiveTime,IdleTime from win32_serversession WHERE UserName like '$username'"
  $results = Get-WmiObject -Namespace root\cimv2 -computer $homeServer -Query $query | Select UserName,ComputerName,ActiveTime,IdleTime
  foreach ($result in $results) {
    $hostname = ""
    $hostname = [System.net.Dns]::GetHostEntry($result.ComputerName).hostname
    $result | Add-Member -Type NoteProperty -Name HostName -Value $hostname -force
    $result | Add-Member -Type NoteProperty -Name HomeServer -Value $homeServer -force
  }
  $results
}

# Find one or more users
$users = "user1", "user2", "user3"
$users | % {Find-User $_} | ft -wrap -auto

# Find the members of a group
get-adgroupmember -id SG-Group1 | % {Find-User $_.samaccountname} | ft -wrap -auto

The original (and still the best) doskey macro:

FU=for %g in ($1 $2 $3 $4 $5 $6 $7 $8 $9) do @for /f "tokens=2 delims=\" %i in ('"dsquery user -samid %g | dsget user -hmdir | find /i "%g""') do @for /f "skip=1 tokens=1-3" %m in ('"wmic /node:"%i" path win32_serversession WHERE "UserName Like '%g'" Get ComputerName,ActiveTime,IdleTime"') do @for /f "tokens=2" %q in ('"ping -a %n -n 1 | find /i "pinging""') do @echo %q %g %n %i %m %o

Create the macro above with doskey:

doskey /listsize=1000 /macrofile=c:\util\macros.txt
FU user1


Wayne's World of IT (WWoIT). 

No comments:

Post a Comment