Login auditing is an extremely important factor to be considered, especially in larger environments where you may have hundreds of PCs and different users logging into them frequently.
One such good example of a use case for a login log solution is a school and in fact the script I am going to reference below has successfully been deployed in a 200 workstation busy school network with numerous different users logging into each machine everyday.
First, lets start by working out what information we want to collect.
- Date the login took place.
- Time the login took place.
- Username at login.
- Computer name at login.
- IP address of machine at login.
The first four are simple to collect and we do so by using system variables:
set "val1=%DATE%"
set "val2=%TIME%"
set "val3=%USERNAME%"
set "val4=%COMPUTERNAME%"
However getting the IP address is a little more involved and we have to extract the IP from the output of an ipconfig
command:
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip%
So now we have all the data we want saved to variables where do we store it? The answer, a .csv file stored in an accessible network share.
The challenge here is allowing the users ONLY append access to the single .csv file. Meaning they cannot read / delete or modify the log in any way, which obviously would be undesirable! This can be done via NTFS permissions on the single .csv log file, allowing only the “Create folders / append data” on the .csv file ONLY.
Once all of the above is setup we only need to add some simple commands to format our above variables into a comma separated list and append to our shared .csv:
set "str=%val1%,%val2%,%val3%,%val4%,%ip%"
echo %str% >> //server/LogShare/userlog.csv
And if we put all of the above together we should get:
REM Gathering information to later use and save into the log
set "val1=%DATE%"
set "val2=%TIME%"
set "val3=%USERNAME%"
set "val4=%COMPUTERNAME%"
REM Getting the IP address of the machine
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%
echo %ip%
REM Making a string and then appending it to a csv file stored in a shared area
set "str=%val1%,%val2%,%val3%,%val4%,%ip%"
echo %str% >> //server/LogShare/userlog.csv
Then all that is left is deploying this to users so we can start to see some log data.
To do this I added the above script to the NETLOGON script that runs on user login and as we have given the user append permissions over the log file they can successfully get the data and write to it.
Happy logging!