Announcement

Collapse
No announcement yet.

logon script need to check for dups

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • logon script need to check for dups

    HI I am running 2003 server, and all XP machines. Right now I have a log on script collecting user name, date/time, computer name and IP address. I would like for the script to check IP address and user name and if they are already in the log then to not write the entry. - script written by Richard Mueller.

    If someone could just point me in the right direction if not outright help it would be appreciated.


    Code:
    ' Logon5.vbs
    ' VBScript Logon script.
    ' This program demonstrates how to log information to a log file.
    '
    ' ----------------------------------------------------------------------
    ' Copyright (c) 2003 Richard L. Mueller
    ' Hilltop Lab web site - http://www.rlmueller.net
    ' Version 1 - March 26, 2003
    ' Version 1.1 - January 25, 2004 - Modify error trapping.
    '
    ' You have a royalty-free right to use, modify, reproduce, and
    ' distribute this script file in any way you find useful, provided that
    ' you agree that the copyright owner above has no warranty, obligations,
    ' or liability for such use.
    
    Option Explicit
    
    Dim objFSO, objLogFile, objNetwork, objShell, strText, intAns
    Dim intConstants, intTimeout, strTitle, intCount, blnLog
    Dim strUserName, strComputerName, strIP, strShare, strLogFile
    
    strShare = "\\Wisconsin\LogFile"
    strLogFile = "TestW2k.log"
    intTimeout = 20
    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objNetwork = CreateObject("Wscript.Network")
    Set objShell = CreateObject("Wscript.Shell")
    
    strUserName = objNetwork.UserName
    strComputerName = objNetwork.ComputerName
    strIP = Join(GetIPAddresses())
    
    ' Log date/time, user name, computer name, and IP address.
    If (objFSO.FolderExists(strShare) = True) Then
        On Error Resume Next
        Set objLogFile = objFSO.OpenTextFile(strShare & "\" _
            & strLogFile, 8, True, 0)
        If (Err.Number = 0) Then
            ' Make three attempts to write to log file.
            intCount = 1
            blnLog = False
            Do Until intCount = 3
                objLogFile.WriteLine "Logon ; "  & Now & " ; " _
                    & strComputerName & " ; " & strUserName & " ; " & strIP
                If (Err.Number = 0) Then
                    intCount = 3
                    blnLog = True
                Else
                    Err.Clear
                    intCount = intCount + 1
                    If (Wscript.Version > 5) Then
                        Wscript.Sleep 200
                    End If
                End If
            Loop
            On Error GoTo 0
            If (blnLog = False) Then
                strTitle = "Logon Error"
                strText = "Log cannot be written."
                strText = strText & vbCrlf _
                    & "Another process may have log file open."
                intConstants = vbOKOnly + vbExclamation
                intAns = objShell.Popup(strText, intTimeout, strTitle, _
                    intConstants)
            End If
            objLogFile.Close
        Else
            On Error GoTo 0
            strTitle = "Logon Error"
            strText = "Log cannot be written."
            strText = strText & vbCrLf & "User may not have permissions,"
            strText = strText & vbCrLf & "or log folder may not be shared."
            intConstants = vbOKOnly + vbExclamation
            intAns = objShell.Popup(strText, intTimeout, strTitle, intConstants)
        End If
        Set objLogFile = Nothing
    End If
    
    ' Clean up and exit.
    Set objFSO = Nothing
    Set objNetwork = Nothing
    Set objShell = Nothing
    
    Wscript.Quit
    
    Function GetIPAddresses()
        ' Based on a Michael Harris script, modified by Torgeir Bakken
        '
        ' Returns array of IP Addresses as output
        ' by IPConfig or WinIPCfg...
        '
        ' Win98/WinNT have IPConfig (Win95 doesn't)
        ' Win98/Win95 have WinIPCfg (WinNt doesn't)
        '
        ' Note: The PPP Adapter (Dial Up Adapter) is
        ' excluded if not connected (IP address will be 0.0.0.0)
        ' and included if it is connected.
    
        Dim objShell, objFSO, objEnv, strWorkFile, objFile
        Dim arrData, intIndex, n, arrIPAddresses, arrParts
    
        Set objShell = CreateObject("wscript.shell")
        Set objFSO = CreateObject("scripting.filesystemobject")
        Set objEnv = objShell.Environment("PROCESS")
        If (objEnv("OS") = "Windows_NT") Then
            strWorkFile = objEnv("TEMP") & "\" & objFSO.GetTempName
            objShell.Run "%comspec% /c IPConfig >" & Chr(34) _
                & strWorkFile & Chr(34), 0, True
        Else
            ' WinIPCfg in batch mode sends output to
            ' filename WinIPCfg.out
            strWorkFile = "WinIPCfg.out"
            objShell.Run "WinIPCfg /batch", 0, True
        End If
        Set objShell = Nothing
        Set objFile = objFSO.OpenTextFile(strWorkFile)
        arrData = Split(objFile. ReadAll, vbCrLf)
        objFile.Close
        Set objFile = Nothing
        objFSO.DeleteFile strWorkFile
        Set objFSO = Nothing
        arrIPAddresses = Array()
        intIndex = -1
        For n = 0 To UBound(arrData)
            If (InStr(arrData(n), "IP Address") > 0) Then
                arrParts = Split(arrData(n), ":")
                If (InStr(Trim(arrParts(1)), "0.0.0.0") = 0) Then
                    intIndex = intIndex + 1
                    ReDim Preserve arrIPAddresses(intIndex)
                    arrIPAddresses(intIndex)= Trim(CStr(arrParts(1)))
                End If
            End If
        Next
        GetIPAddresses = arrIPAddresses
    End Function
    Last edited by Ossian; 4th January 2008, 19:01. Reason: Added Code Tags around script

  • #2
    Re: logon script need to check for dups

    Instead of just appending to a log file,
    The new script should first Read all (ForReading = 1) the existing log file in to a string.
    - Determine the IPaddress, then,
    - use the Instr() function to look for the username + ipaddres in the string.
    - If this text combination is not found, then open the the log file for appending (ForAppending = 8) and add a new line to the log.
    - close the file

    It is important that the time the logfile is open for writing/appending is as short as possible, because the file is shared with the logon of other users.


    Does all the XP machines assigned their IP address by DHCP?


    \Rems
    Last edited by Rems; 7th January 2008, 23:37. Reason: disabled auto smilies

    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

    Comment


    • #3
      Re: logon script need to check for dups

      yes they are assigned by DHCP but the IP address seem fairly static for a dynamic system, the reason I am wanting to check IP is I have users that VPN in and I want them on the log also, I can live with dups of the VPN people.

      Thanks for the help, I know I am asking for much but any chance I could get a sample script, I am teaching myself on the fly to do these things.

      Again thanks

      Comment


      • #4
        Re: logon script need to check for dups

        This script below checks whether there is already a central logfile. Otherwise it will create one on the next step.
        The existing central logfile will first be opened for Reading, and the current content is loaded into memory. Next the logfile will be opened for Writing (this will destroy the all the present content).
        The script seaches for the Computer name in the old content of the logfile (which was loaded into memory before the file was cleared).
        - If the Computername was found, the script compare the ipaddresses, if the current ipaddress is different, the old line will be updated.
        - If the Computername was not found in the logfile, a new line will be added to the logfile.

        Before the updated content will be written back to the central logfile, the lines are sorted alphabetically first.

        Code:
        '  "User Log-on Script" 
        ' This script update a list of computernames with the IP-address assigned by DHCP
        '
        ' Author: Remco Simons [NL] 2008
        ' ( http://forums.petri.com/showthread.php?t=20625 )
        '
        ' The script checks whether there is already a central logfile. Otherwise it will create one on the next step.
        ' The existing central logfile will first be opened for Reading, and the current content is loaded into memory. 
        ' Next the logfile will be opened for Writing (this will destroy the all the present content). 
        ' The script seaches for the Computer name in the old content of the logfile (which was loaded into memory before the file was cleared). 
        ' - If the Computername was found, the script compare the ipaddresses, if the current ipaddress is different, the old line will be updated.
        ' - If the Computername was not found in the logfile, a new line will be added to the logfile.
        ' Before the updated content will be written back to the central logfile, the lines are sorted alphabetically first. 
        
        Option Explicit
        
        Const ForReading = 1, ForWriting = 2
        Const Column_X = 16
        
        Dim strShare, strLogFile, strPath
        Dim strComputerName, strIP, strUserName
        Dim objFSO, objReadLogFile, objWriteLogFile
        Dim strLog
        
        strShare = "\\server\share"
        strLogFile = "Computers & IPaddress.txt"
        
        With CreateObject("Wscript.Network")
          strComputerName = .ComputerName
          strIP = ActiveDHCPIPAddress(strComputerName)
          strUserName = .UserName
        End With
        
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        strPath = strShare & "\" & strLogFile
        
        ' columns
        Dim intSpaces1, intSpaces2, strOut
        intSpaces1 = Column_X - Len(strComputerName)
              If intSpaces1 < 1 then intSpaces1 = 1
        intSpaces2 = Column_X - Len(strIP)
              If intSpaces2 < 1 then intSpaces2 = 1
        strOut = strComputerName & Space(intSpaces1) & strIP & Space(intSpaces2)
        
        Dim intCount : intCount = 1
        Do Until intCount = 5
        
          'datestamp
           Dim dt, yyyymmdd, hhmmss
           dt = Now()
           yyyymmdd = Year(dt)*1e4 + Month(dt)*1e2 + Day(dt)
           hhmmss = Right(1e6 + Hour(dt)*1e4 + Minute(dt)*1e2 + Second(dt),6)
           dt = yyyymmdd & "-" & hhmmss
        
          If (objFSO.FileExists(strPath) = True) Then
              If objFSO.GetFile(strPath).Size > 0 Then
                 Set objReadLogFile = objFSO.OpenTextFile(strPath, ForReading)
                 strLog = objReadLogFile.ReadAll
              End If
          End If
          If (objFSO.FolderExists(strShare) = True) Then
             On Error Resume Next
             Set objWriteLogFile = objFSO.OpenTextFile(strPath, _
                ForWriting, True)
             If IsObject(objReadLogFile) Then objReadLogFile.close
        
             If (Err.Number = 0) Then
                Dim arrLog, EDITLINE, CHANGES, Lines, i
                arrLog = split(strLog, vbNewLine)
                EDITLINE = -2
                Lines = UBOUND(arrLog)
                For i = 0 To Lines
                   If _
                    (InStr(arrLog(i), _
                     strComputerName & Space(intSpaces1)) <> 0) _
                      Then
                       EDITLINE = -1
                       If (InStr(arrLog(i), strOut) = 0) Then EDITLINE = i
                   End If
                Next
        
                strOut = strOut & " / entry added: " & dt & "-" & strUserName
                If EDITLINE > -1 Then
                   arrLog(EDITLINE) = strOut
                   CHANGES = True
                ElseIf EDITLINE = -2 Then
                   ReDim Preserve arrLog(lINES+1)
                   arrLog(lINES+1) = strOut
                   CHANGES = TRUE
                Else CHANGES = False
                End If
        
                If CHANGES = True Then
                  ' Sort;
                    Dim j, k, l, tmp
                    For j = UBound(arrLog) - 1 To 0 Step -1
                      For k= 0 to j
                        If arrLog(k) > arrLog(k+1) Then
                          tmp = arrLog(k+1)
                          arrLog(k+1) = arrLog(k)
                          arrLog(k) = tmp
                        End if
                      Next
                    Next
                END IF
                objWriteLogFile.Write JOIN(arrLog, vbNewLine)
                objWriteLogFile.Close
                Exit Do
             Else
                intCount = intCount + 1
                wsh.sleep 250
             End If
             On Error GoTo 0
          End If
        Loop
        Set objFSO = Nothing
        
        Wscript.Quit
        
        
        
        Function ActiveDHCPIPAddress(strHost)
           'Get current IP Address assigned by DHCP 
           '(Assumes that there is only ONE active NIC !!! )
           On Error Resume Next
        
           Const HKEY_LOCAL_MACHINE = &H80000002
        
           Dim strKeyPath, oReg, arrSubKeys, subkey, DHCPAddress
           Dim WSHShell
        
           strKeyPath = "SYSTEM\CurrentControlSet\Services\Tcpip" _
              & "\Parameters\Interfaces\"
        
           Set oReg=GetObject("winmgmts:" _
              & "{impersonationLevel=impersonate}!\\" _
              & strHost & "\root\default:StdRegProv")
        
           oReg.EnumKey HKEY_LOCAL_MACHINE, strKeyPath, arrSubKeys
        
           Set WSHShell = CreateObject("Wscript.Shell")
           ActiveDHCPIPAddress = "<no dhcp-address>"
           For Each subkey In arrSubKeys
               DHCPAddress = WSHShell.RegRead("HKLM\" _
                   & strKeyPath & subkey & "\DhcpIPAddress")
          
               If DHCPAddress <> "0.0.0.0" And _
                  Left(DHCPAddress,3) <> "169" Then 
                    ActiveDHCPIPAddress = DHCPAddress    
               End If
           Next
           'If the value of "IPAddress" contains a valid address 
           'or list of addresses (to replace 0.0.0.0), it takes 
           'precedence over the value of DhcpIPAddress.
           'http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/regentry/33598.mspx?mfr=true
        End Function
        This script use a different method to retrieve the IP address Assigned by DHCP. There are several methods, you can also use the Function GetIPAddresses()
        from you sample script, if you liked that better.


        \Rems


        Originally posted by "JustThisAdmin"
        I am teaching myself on the fly to do these things
        That is great!
        And feel free to ask questions about this script.
        Last edited by Rems; 10th January 2008, 16:49.

        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

        Comment

        Working...
        X