Solved

Script to monitor the logged in user. If a different person found then email.

Posted on 2010-08-21
37
293 Views
Last Modified: 2012-05-10
Hi,

Script to monitor the logged in user. If a different person found then email.
I have a txt file that has the machine name and the user name. to whome the machine is allotted.
Machine name;username

I want a script to scan all machines in this txt file every 4 hrs. If there is a mismatch then email.

powershell or vbs script.

regards
Sharath
0
Comment
Question by:bsharath
  • 19
  • 16
  • +1
37 Comments
 
LVL 1

Expert Comment

by:ldap389
ID: 33492991
If you want to achieve this, you can use WMI and adapt this script (http://www.tek-tips.com/viewthread.cfm?qid=1259771&page=1)

Another way, if you want to restrict users tu use specific workstations is to set up the user account in Active Directory, using the "allowed workstations" parameter, you can script that with PowerShell.
Using Quest AD CMDlets for example:

http://www.powergui.org/thread.jspa?threadID=9312

0
 

Expert Comment

by:shrimantpatel
ID: 33494080
Private Function getLoggedUserName() As String
    Dim strBufferString As String
    Dim lngResult As Long
    Dim uname
    strBufferString = String(MAX_BUFFER_LENGTH, "X")
    lngResult = getUserName(strBufferString, MAX_BUFFER_LENGTH)
    uname = Mid(strBufferString, 1, MAX_BUFFER_LENGTH)
    getLoggedUserName = Mid(uname, 1, InStr(1, uname, Chr(0)) - 1)
End Function

Public Function CheckLogin() As Boolean
    Select Case LCase(getLoggedUserName)
        Case "bwilson"
            CheckLogin = True
        Case Else
            CheckLogin = False
    End Select
End Function

Call checklogin function above and replace "bwilson" with your required logon id..., and run the vB script as a batch...

There are tonnes of example on how to send an email using vbscript using CDO and below is one I just picked from
http://www.paulsadowski.com/WSH/cdo.htm

Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Example CDO Message"
objMessage.From = "me@my.com"
objMessage.To = "test@paulsadowski.com"
objMessage.TextBody = "This is some sample message text."
objMessage.Send

Hope this helps
0
 
LVL 11

Author Comment

by:bsharath
ID: 33494419
Thanks i will need the emailing way from Outlook. has to use the currently logged in user email address to send
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33500439
Hi, Sharath.

I can help with the Outlook side.  What is it that you want to send and who do you want to send it to?
0
 
LVL 11

Author Comment

by:bsharath
ID: 33500503
Hi David,

I will have the txt file with machine name and user name
Say like this

machine1;sharath

And when scanned the machine and it finds paul logged in then an email has to be sent to xyz email that i have hard-coded.
Stating machine1 has paul logged in.

0
 
LVL 76

Expert Comment

by:David Lee
ID: 33500875
The code below should do what you've described.  Here's how to use this

1.  Open Notepad
2.  Copy the code below and paste it into Notepad
3.  Edit the code per the comments I included in it
4.  Save the file with a .vbs extension
5.  Create a scrheduled task that runs the script as needed

Outlook must be open for the script to work.
Dim objFSO, objFile, strBuffer, arrUser

On Error Resume Next

Set objFSO = CreateObject("Scripting.FileSystemObject")

'On the next line edit the file name and path'

Set objFile = objFSO.OpenTextFile("C:\eeTesting\sharath1.txt")

Do Until objFile.AtEndOfStream

	strBuffer = objFile.ReadLine

	arrUser = Split(strBuffer, ";")

	If GetUserName(arrUser(0)) <> arrUser(1) Then

		SendMsg arrUser(0), arrUser(1)

	End If

Loop

objFile.Close

Set objFile = Nothing

Set objFSO = Nothing

On Error Goto 0

WScript.Quit



Function GetUserName(strComputer)

	Dim objWMIService, colItems, objItem, arrTemp

	On Error Resume Next

	Const wbemFlagReturnImmediately = &h10

	Const wbemFlagForwardOnly = &h20

	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")

	Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)

	For Each objItem In colItems

      arrTemp = Split(objItem.UserName, "\")

      GetUserName = arrTemp(1)

	Next

	Set objWMIService = Nothing

	Set colItems = Nothing

	Set objItem = Nothing

    On Error Goto 0

End Function



Sub SendMsg(strComputer, strUser)

	Dim olkApp, olkMsg

	Set olkApp = GetObject(,"Outlook.Application")

	Set olkMsg = olkApp.CreateItem(0)

	With olkMsg

		'On the next line edit the email address'

		.To = "someone@company.com"

		'On the next line edit the subject"

		.Subject = "Your Subject Goes Here"

		'On the next line edit the message text as desired'

		.Body = "The user " & strUser & " is logged in to the computer " & strComputer

		.Send

	End With

	Set olkMsg = Nothing

	Set olkApp = Nothing

End Sub

Open in new window

0
 
LVL 11

Author Comment

by:bsharath
ID: 33500991
David thanks
I mentioned this
Pc16726;paul

Actually paul there is no user as this.
When run
The user paul is logged in to the computer Pc16726

But its sharath whose logged into the machine. The message is wrong
is there any way to skip the Security warning that we get in outlook?
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33501066
Sorry, I don't understand the first part.  

If the computer has anti-virus installed and it's up to date, then you shouldn't get any warnings.  The exception to that rule is if you have Outlook security set to always warn you.  Check your settings by clicking Tools > Trust Center > Programmatic Access.
0
 
LVL 11

Author Comment

by:bsharath
ID: 33501835
Sorry David was the last comment for me?

If yes then i meant i dont want to get the outlook warning Accept\Deny while sending an email to select a time to send email
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33502163
David thanks
I mentioned this
Pc16726;paul

Actually paul there is no user as this.
When run
The user paul is logged in to the computer Pc16726

This is the part I don't understand.  Please explain.

----

is there any way to skip the Security warning that we get in outlook?

If the computer has anti-virus installed and it's up to date, then you  shouldn't get any warnings.  The exception to that rule is if you have  Outlook security set to always warn you.  Check your settings by  clicking Tools > Trust Center > Programmatic Access.
0
 
LVL 11

Author Comment

by:bsharath
ID: 33502236
The file sharath1.txt has this
Pc16726;paul
So the script checks the machine pc16726 and checks if paul is logged in.
So if its not paul it has to email the user whose email id is in the code.
For what ever name i mention right or wrong in the txt file i get
the user is logged in
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33502489
Ok, once again I'm confused.  You said "email that i have hard-coded" which I assume meant the email address.  There is no email address in the file, so if you want the message to go to the person, then where is their address coming from?  To use your example, if Paul is supposed to be logged into the computer but the script finds Sam is logged in, then the message goes to Paul.  Where does the script get Paul's email address?
0
 
LVL 11

Author Comment

by:bsharath
ID: 33502534
No...

if Paul should be logged in and i find sam then an email has to be sent to the email address in the code.
All emails just to the administrator whose email address is in the code...
0
 
LVL 11

Author Comment

by:bsharath
ID: 33502549
I give a machine to paul and only paul should use it. I dont want to restrict it via terminal or AD. But want to find them and warn them. thats it.
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33506853
Got it.  The question then is how does the script know what Paul's address is so that it can send him a message when someone else uses his computer?
0
 
LVL 11

Author Comment

by:bsharath
ID: 33507380
I dont want to send it to paul. I want to send it to the email address thats hardcoded in the vbs thats the administrator.
It needs to check if its paul or sam. if its Paul's computer then do nothing and if its sam who is using paul's computer then email to administrator
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33509307
Now I'm totally lost.  The script already sends to the email address that's hardcoded in the vbs yet you indicated that there's some problem with that.  If sending to the address in the script is what you want, then I don't understand what the problem is.
0
 
LVL 11

Author Comment

by:bsharath
ID: 33509326
I got the email. thats right and it works
But i got the message as

The user paul is logged in to the computer dev306
But
Sam is logged in. It gets the message wrong
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 76

Expert Comment

by:David Lee
ID: 33509357
Got it.  This should fix that.
Dim objFSO, objFile, strBuffer, arrUser, strCurrentUser
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
'On the next line edit the file name and path'
Set objFile = objFSO.OpenTextFile("C:\eeTesting\sharath1.txt")
Do Until objFile.AtEndOfStream
	strBuffer = objFile.ReadLine
	arrUser = Split(strBuffer, ";")
        strCurrentUser = GetUserName(arrUser(0))
	If strCurrentUser <> arrUser(1) Then
		SendMsg arrUser(0), strCurrentUser
	End If
Loop
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
On Error Goto 0
WScript.Quit

Function GetUserName(strComputer)
	Dim objWMIService, colItems, objItem, arrTemp
	On Error Resume Next
	Const wbemFlagReturnImmediately = &h10
	Const wbemFlagForwardOnly = &h20
	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
	Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
	For Each objItem In colItems
      arrTemp = Split(objItem.UserName, "\")
      GetUserName = arrTemp(1)
	Next
	Set objWMIService = Nothing
	Set colItems = Nothing
	Set objItem = Nothing
    On Error Goto 0
End Function

Sub SendMsg(strComputer, strUser)
	Dim olkApp, olkMsg
	Set olkApp = GetObject(,"Outlook.Application")
	Set olkMsg = olkApp.CreateItem(0)
	With olkMsg
		'On the next line edit the email address'
		.To = "someone@company.com"
		'On the next line edit the subject"
		.Subject = "Your Subject Goes Here"
		'On the next line edit the message text as desired'
		.Body = "The user " & strUser & " is logged in to the computer " & strComputer
		.Send
	End With
	Set olkMsg = Nothing
	Set olkApp = Nothing
End Sub

Open in new window

0
 
LVL 11

Author Comment

by:bsharath
ID: 33509412
Now i get whose logged in the
I get the name of the logged in person. But that not what i wanted. If the person that i have mentioned in
Sharath1.txt does not match only then email
Say in the txt file i have this

machinename;Paul
If the script queries machinename and finds Paul is logged in then do nothing. And if it finds some other user logged in then email stating

The user Sam is logged in to the computer de306 where as its Paul's machine

0
 
LVL 76

Accepted Solution

by:
David Lee earned 500 total points
ID: 33509490
I've modified the code as requested.
Dim objFSO, objFile, strBuffer, arrUser, strCurrentUser
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
'On the next line edit the file name and path'
Set objFile = objFSO.OpenTextFile("C:\eeTesting\sharath1.txt")
Do Until objFile.AtEndOfStream
	strBuffer = objFile.ReadLine
	arrUser = Split(strBuffer, ";")
        strCurrentUser = GetUserName(arrUser(0))
	If strCurrentUser <> arrUser(1) Then
		SendMsg arrUser(0), strCurrentUser, arrUser(1)
	End If
Loop
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
On Error Goto 0
WScript.Quit

Function GetUserName(strComputer)
	Dim objWMIService, colItems, objItem, arrTemp
	On Error Resume Next
	Const wbemFlagReturnImmediately = &h10
	Const wbemFlagForwardOnly = &h20
	Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
	Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_ComputerSystem", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
	For Each objItem In colItems
      arrTemp = Split(objItem.UserName, "\")
      GetUserName = arrTemp(1)
	Next
	Set objWMIService = Nothing
	Set colItems = Nothing
	Set objItem = Nothing
    On Error Goto 0
End Function

Sub SendMsg(strComputer, strUser, strOwner)
	Dim olkApp, olkMsg
	Set olkApp = GetObject(,"Outlook.Application")
	Set olkMsg = olkApp.CreateItem(0)
	With olkMsg
		'On the next line edit the email address'
		.To = "someone@company.com"
		'On the next line edit the subject"
		.Subject = "Your Subject Goes Here"
		'On the next line edit the message text as desired'
		.Body = "The user " & strUser & " is logged in to the computer " & strComputer & " where as it's " & strOwner & "'s machine."
		.Send
	End With
	Set olkMsg = Nothing
	Set olkApp = Nothing
End Sub

Open in new window

0
 
LVL 11

Author Comment

by:bsharath
ID: 33509571
Thanks David all fine
Say i have Paul and paul only is logged in then i dont want any email. Only when there is a differnce i need a email.
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33509613
You should only get an email if the names don't match.  This line of code

    If strCurrentUser <> arrUser(1) Then

is comparing the name of the person logged into the computer (strCurrentUser) to the name of the person listed in the file (arrUser(1)) for that computer.  It only sends the message if the names don't match.  The ONLY way the script can send a message is if the names don't match.  There HAS to be some difference.  
0
 
LVL 11

Author Comment

by:bsharath
ID: 33509639
Ok i think the issue is. If the machine is not logged in at all or the machine is Offline i get emails like

The user  is logged in to the computer Dev18 where as it's Paul ander machine.
I dont get a name between "The user & is logged"

0
 
LVL 76

Expert Comment

by:David Lee
ID: 33509780
Replace the first 18 lines of the current script with the code below.
Dim objFSO, objFile, strBuffer, arrUser, strCurrentUser
On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
'On the next line edit the file name and path'
Set objFile = objFSO.OpenTextFile("C:\eeTesting\sharath1.txt")
Do Until objFile.AtEndOfStream
	strBuffer = objFile.ReadLine
	arrUser = Split(strBuffer, ";")
        strCurrentUser = GetUserName(arrUser(0))
	If strCurrentUser <> "" Then
            If strCurrentUser <> arrUser(1) Then
		SendMsg arrUser(0), strCurrentUser, arrUser(1)
            End If
	End If
Loop
objFile.Close
Set objFile = Nothing
Set objFSO = Nothing
On Error Goto 0
WScript.Quit

Open in new window

0
 
LVL 11

Author Comment

by:bsharath
ID: 33509799
For some machines if the user is logged in also i get an email with no user name in the email

For some i get email even when matched. I guess its because of the case?
Will case of Ntlogin matter.
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33509830
"For some machines if the user is logged in also i get an email with no user name in the email"
Both names are missing or only one of them?  If only one, which one?

"For some i get email even when matched. I guess its because of the case?"
Yes, the match is case sensitive.  I can change that if you want.
0
 
LVL 11

Author Comment

by:bsharath
ID: 33509875
After the previous fix the first issue is resolved.

Can you change the case part please
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33509963
Change line #11 from

    If strCurrentUser <> arrUser(1) Then

to

    If LCase(strCurrentUser) <> LCase(arrUser(1)) Then
0
 
LVL 11

Author Comment

by:bsharath
ID: 33510002
Thanks a lot David...
:-)

if any errors it faces. Can we write to a file after skipping?
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33510016
Errors?  What kind of errors?
0
 
LVL 11

Author Comment

by:bsharath
ID: 33510633
Say when contacting machines it gets some permission issues
0
 
LVL 11

Author Comment

by:bsharath
ID: 33518000
I have put 1000+ computers and am scanning but its 12hrs and its still running. I guess some issue . Its stuck some where. Can we have another log with machine name and shows whats its doing being logged. So we can check where its getting stuck...
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33519303
With 1,000+ computers the process is ALWAYS going to take a long time even if every check is successful.  Assume that the script takes an average of 5 seconds to check each of 1,000 computers.  It'll take 5,000 seconds (83.33 minutes) to check all the computers.  Five seconds is probably generous.  I expect that on average it'll take something like 15 - 20 seconds.  Checking a remote computer is a lot slower than checking the local computer especially if the computer isn't on.  At an average of 15 seconds per computer it'll take more than 3 hours to complete one pass through 1,000 computers.  Adding a logging function will make it take even longer.  Checking remotely has two distinct drawbacks: it is slower than checking locally, it is a serial process (i.e. it can only check one computer at a time).  

The best solution is to check locally.  I'm assuming that the computes are in a domain and that everyone has to log on to access a computer.  If so, then by adding commands to a logon script you could check who is logging on to the computer and send a report if it's not the person who is supposed to be logging on to the computer.  This would eliminate both of the problem areas I listed above.  The checks would be very fast since they're being done locally and this represents a parallel process (i.e. multiple computers can be checked at once).  It also saves checking the same computer over and over throughout the day.  It only performs the check when someone logs on.  Once they are logged on there's no need to keep checking them.  The lone downside to this solution is that sending the message is more of a problem.  My recommendation for solving that is to have the script call a web service that in turn sends the message.  Of course that presumes that you have access to a web server.
0
 
LVL 11

Author Comment

by:bsharath
ID: 33519370
Wow thanks David for such nice explanation. Login scripts is a pain reason i have to go through the CR process thats all approvals :-(

Its 18 + hrs and the script is still running. can we have something like if the script is stuck some where skip to next. And log just the skipped ones.
0
 
LVL 76

Expert Comment

by:David Lee
ID: 33519569
I understand about the pain of a CR process.  I have the same issue at work.  

Unfortunately there's no way to determine that the script is stuck.  That would require some other process that monitors the script and determines it's not working.  Once the check of a given computer begins it has to complete before the script can move on.  There is no means I know of to command the script to abort the check of that computer if it hasn't completed in x seconds.  Even if there was, the process is still going to take a long time.  It's simple arithmetic.  For 1,000 computers if the average time per computer exceeds 14.4 seconds, then it's impossible to complete a pass in 4 hours.  At 1,500 computers the average time has to be under 9.6 seconds.  Remote WMI queries just aren't very fast.  If a logon script or some other client based solution isn't possible, then the next best thing is to PING each computer to see that it's on and available before querying it for the logon information.  It means using another WMI query to perform the PING.  While that will speed things up for by bypassing computers that aren't on, it slows things down for the computers that are on.  I think the end result will be a faster process, but I don't know it'll be fast enough.  
0
 
LVL 11

Author Comment

by:bsharath
ID: 33527922
Thanks a lot David...  :-)
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Microsoft Windows Server Update Service (WSUS) is free for everyone, but it lacks of some desirable features like send an e-mail to the administrator with the status of all computers on the WSUS server. This article is based on my PowerShell script …
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now