No announcement yet.

Script to trace user currently login computers

  • Filter
  • Time
  • Show
Clear All
new posts

  • Script to trace user currently login computers

    Is their a vbscript to check the user what pc he/she currently logs-in?


  • #2
    Re: Script to trace user currently login computers

    Yes, it is possible to create a vbscript that is using the information from the login-logs per computer you have on your network ( detail about the log writing: ).

    - The vbscript merges the logs
    - Search for the username
    - For every line on where username if found the script tries to ping the computer that is found on the same line
    - If that computer is on line, the script connects to the computer to confirm the current user
    - Finally the script returns a list containing the computername(s) where on the user currently is logged-in via the console.

    How does that sound?


    This posting is provided "AS IS" with no warranties, and confers no rights.


    ** Remember to give credit where credit's due **
    and leave Reputation Points for meaningful posts


    • #3
      Re: Script to trace user currently login computers

      Your right Mod Rems!

      I can use the logs that I gather to check the current logon users's



      • #4
        Re: Script to trace user currently login computers

        The VBscript relies on information created by a logonscript.

        Batch =logonscript (Note, the username will be written in the log like userdomain\username, as required by the vbscript that will search for the user)
        :: source:
        :: This logonbatch, writes info about user and computer to a logfile on a share.
        :: Where only the most recent log is kept per computer,
        ::     but if you'd prefer to keep every logon log made by the computer,
        ::     then change the redirection notation to  >>"%exportfile%" (...
        ::    (tip, if you then add the yyyy and the nr. of the month to the name
        ::     of the log-file, it'll automatically start new logs monthly)
        :: note,
        ::       unresolvable sids can slowdown the run,
        ::       unresolved sids are not showed in the list
        @echo off
        Set "LogsFolder=\\uncpath\folder"
        Set "exportfile=%LogsFolder%\%computername%-log.csv"
        :: Get IP address
        For /f "tokens=2 delims=[]" %%* in ('ping.exe %computername% -n 1 -w 1') Do set strIP=%%*
        :: Get date stamp
        for /f "tokens=2-4 skip=1 delims=(-./)" %%i in ('echo.^|date') do (
           for /f "tokens=1-4 delims=-./ " %%m in ('date /t') do (
              (set dow=%%m)&(set %%i=%%n)&(set %%j=%%o)&(set YYYY=%%p)
        :: Devide the Current Time in timeparts, HH, NN, SS and Sd
        For /F "tokens=1-4 delims=:., " %%i in ('echo.%time%') Do (
           (Set HH=0%%i)&(set NN=%%j)&(set SS=%%k)&(Set Sd=%%l)
           Set "HH=!HH:~-2!"
        :: Determine local Admins
        For /f "delims=" %%* in ('Net.exe localgroup Administrators') Do (
         If NOT [!catch!]==[] (
           If NOT [!Member!]==[] (
             Set ListAdmins=!ListAdmins!,!Member!)
           Set "Member=%%*"
         ) ELSE (echo.%%* | find "------ ">nul &&Set catch=nowdefined)
        (Set ListAdmins="%ListAdmins:~1%")
        :: Membership local Administrators
        Set "IsAdmin=Yes" & Set "NotAdmin=%temp%.\tst"
        >"%NotAdmin%",2>&1 (WMIC.exe quit)
        (Set/p IsAdmin=<"%NotAdmin%")&(Del/f "%NotAdmin%")
        If /i Not "%IsAdmin%"=="Yes" (Set "IsAdmin=No")
        :: export to csv format, in order,
        :: "date","time","computername","user","isAdmin-y/n","list members locAdmins"
        >"%exportfile%" (

        VBScript (is searching the last line of each logfile for the username you have enterded, then connect to the computer that wote the logfile and retrieve the currently logged on username from it - and compare the name with the name that was in the log).
        Option Explicit
        '# This vbscript will show the computer(s) where 
        '# the entered user is currently logged-in to the console.
        '# important: The script get the information from special
        '# logfiles created by logonscript!
        '# (more details about those logfiles:
        '# )
        Dim sInputUsername
        Dim LogsFolder, UserInLog, Computername, IsAdmin
        Dim sUser, list
        sInputUsername = InputBox(vbNewLine & "Find computer(s) where" & vbNewLine _
                & "this user is currently logged-on to", _
                "Enter Username", "SAM-Account-Name")
        LogsFolder = "\\uncpath\folder"
        ' (search for files ending with: -log.csv
        '  import csv format, the values must exist in this order,
        '  "date","time","computername","user","isAdmin-y/n","list members locAdmins" )
        sInputUsername = Replace(sInputUsername, "/", "\")
        If Instr(sInputUsername, "\") Then
          sInputUsername = split(sInputUsername, "\")(1)
        ElseIf Instr(sInputUsername, "@") Then
          sInputUsername = split(sInputUsername, "@")(0)
        End If
        sInputUsername = Trim(LCase(sInputUsername))
        ' Regular Expression, Searching log-files
        Dim SearchPattern, objRegExp 
        SearchPattern = "-log\.csv$" ' (where "\" = an escape for the dot. And "$" = at end of string)
        Set objRegExp = New RegExp
        objRegExp.Pattern = searchpattern
        objRegExp.Global = True
        objRegExp.IgnoreCase = True
        ' Read log-Files
        Const ForReading = 1
        Dim objFSO, FileCollection
        Dim objFile, sFilePath
        Dim stream, line, lastLine, arrParam
        Dim arrComputers(), intSize : intSize=0
        Dim i
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        Set FileCollection = objFSO.GetFolder(LogsFolder & "\")
        For Each objFile In FileCollection.Files
            sFilepath = objFile.Path
            If objRegExp.test(sFilepath) = True Then
              With objFSO.GetFile(sFilepath)
                set stream = .OpenAsTextStream(ForReading)
                ' Read just the last line of each logfile
                ' to find the username.
                Do While not stream.AtEndOfStream
                  line = stream.readline
                  If Len(line) >0 Then lastLine = line
              End With
              If not IsEmpty(lastLine) Then
                arrParam      = Split(lastLine, ",")
                Computername  = Trim(arrParam(2))        '<= computername
                UserInLog     = Trim(LCase(arrParam(4))) '<= username
                If Trim(LCase(arrParam(5))) = "yes" Then '<= admin? yes-no
                     IsAdmin  = " (is local Admin!)"
                Else IsAdmin  = Empty
                End If
                If sInputUsername = Split(UserInLog, "\")(1) Then
                  '*** populate an array with found computer names
                  ReDim Preserve arrComputers(intSize)
                  arrComputers(intSize) = Computername
                  intSize = intSize + 1
                  ReDim Preserve arrComputers(intSize)
                  arrComputers(intSize) = UserInLog
                  intSize = intSize + 1
                  ReDim Preserve arrComputers(intSize)
                  arrComputers(intSize) = IsAdmin
                  intSize = intSize + 1
                End If
                lastLine = Empty
              End If
              sFilePath = Empty
            End If
        Set objRegExp = Nothing
        ' -----------------------------------------------
        ' loop through the array containing the found computername(s), and
        ' connect (to each of them) to obtain the name of the current user.
        list = BeginCap(sInputUsername) & " is currently found on..." & vbNewLine & vbNewLine
        intSize = 0
        If Len(join(arrComputers)) > 0 then
          For i = 0 to UBound(arrComputers) step 3
            Computername = arrComputers(i)
            UserInLog    = arrComputers(i+1)
            sUser = GetUser(Computername)
            If sUser = UserInLog Then
               list = list _
                  & BeginCap(Computername & " - " & sUser _
                  & arrComputers(i+2)) & vbNewLine
               intSize = intSize + 1
            End If
        End If
        If intSize < 1 Then list = list & "logon not found"
        msgBox list
        Function GetUser(ByVal strHost)
          ' Name of a user that is logged on currently. This
          ' property must have a value. In a terminal services
          ' session, UserName returns the name of the user
          ' that is logged on to the consoleónot the user
          ' logged on during the terminal service session.
          Dim objComputer
          If (IsConnectible(strHost) = True) Then
            With GetObject("winmgmts:" _
              & "{impersonationLevel=impersonate}!\\" _ 
              & strHost & "\root\cimv2")
              For Each objComputer in .ExecQuery _
                 ("Select UserName from Win32_ComputerSystem")
                 GetUser = LCase(objComputer.UserName)
            End with
             GetUser = "\"
          End If
        End Function
        Function IsConnectible(ByVal strHost)
            ' function returns False (0) or True (-1)
            Dim lngResult, nPings
            nPings = 2
            With CreateObject("WScript.Shell")
            Do While nPings > 0
              nPings = nPings - 1
              lngResult = .Run("%comspec% /c" _
                  & " ping.exe -n 1 -w 750 " & strHost _
                  & " | find/i ""TTL="" > nul 2>&1", 0, True)
              Select Case lngResult
                 Case 0
                    IsConnectible = True
                    exit Function
                 Case Else
                    IsConnectible = False
              End Select
            End With
        End Function
        Function BeginCap(strText)
          Dim p, capNext, capNextChars
          BeginCap = ""
          capNextChars = ". \" & Chr(9) & Chr(10) '9=tab; 10=linefeed
          capNext = True
          For p = 1 To Len(strText)
            If capNext Then
              BeginCap = BeginCap & UCase(Mid(strText,p,1))
              BeginCap = BeginCap & Mid(LCase(strText),p,1)
            End If
            capNext = Instr(capNextChars,Mid(strText,p,1))
        End Function
        Last edited by Rems; 13th October 2008, 10:04.

        This posting is provided "AS IS" with no warranties, and confers no rights.


        ** Remember to give credit where credit's due **
        and leave Reputation Points for meaningful posts


        • #5
          Re: Script to trace user currently login computers

          Ok Mod Rems
          I will give it a try