Monday, June 27, 2005

Reverse Permissions Audit Scripts Part 2

*****If your looking for a Exchange 2007/2010 solution have a look at this post http://gsexdev.blogspot.com/2008/04/exchange-permission-and-reverse.html *****

In April I posted this script that did a reverse lookup of mailbox permissions that had been assigned via Active Directory Users and Computers. This was to give a view by user of what mailbox’s a particular user had access to (instead of the normal view which is who has access to this mailbox). The second part of the permission story with exchange is the actually MAPI permissions that are set on each of the folders in a mailbox. When you delegate folders in outlook this will modify the rights of each of the folders that you delegate (eg calendar,contact,tasks). To view the Mapi permissions on a folder programmatically from a script there are a few methods that can be used the easiest way to do it is to use the Acl.dll from the platform SDK see KB240911 for details for more details. The basis of this article can be used to create a conventional script that will log the rights on each folder and save this to a CSV file. You can then open the CSV in Excel do a auto filter on the folder you want to audit and you very quick and useful report. I’ve included a conventional version of a script that does just this in the download for this post this script takes the name of the server you want to run it against as a command line parameter. Both these scripts require the acl.dll to be registered on the machine you are running the script on. Acl.dll can be found in the Platform SDK or downloaded as part of this CDOlive sample .

With the reverse MAPI permission script what I’ve done is to take the data shaping logic I used previously and applied it to all the root mailbox folders eg the root of the mailbox tree and the calendar,inbox,contacts,tasks,notes and sent item folders. So what the script will output is a per user view of what other Users’s mailbox folders each user has access to. So this script could be used to answer the question what calendars is fred-blogs able to see. To do this the script first looks up Active Directory for all users that have a mailbox in a domain and creates a parent record-set of these values. Then for every user it tries to establish a MAPI connection to there mailbox via CDO 1.2 and enumerates permissions on the root folders in the mailbox and writes these permissions to the child record-set. The recordset’s are then related on the Exchange LegacyDN and the address retrieved from CDO addressEntry object.

The script tries to connect to every mailbox in a domain and expects that the user running it will have full rights to every mailbox in the domain equiv to http://support.microsoft.com/?kbid=262054 . I’ve put a download copy of both scripts that I’ve talked about here. The code for the reverse permissions script looks like


on error resume next
set conn1 = createobject("ADODB.Connection")
strConnString = "Data Provider=NONE; Provider=MSDataShape"
conn1.Open strConnString
set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
Query = "<LDAP://" & strNameingContext & ">;(&(&(&(& (mailnickname=*)" & _
"(!msExchHideFromAddressLists=TRUE) (| (&(objectCategory=person)(objectClass=user)"
& _
"(|(homeMDB=*)(msExchHomeServerName=*))) )))))" & _
";samaccountname,legacyExchangeDN,msExchHomeServerName," &_
"displayname,distinguishedName;subtree"
Com.ActiveConnection = Conn
Com.CommandText = Query
Com.Properties("Page Size") = 1000
set objParentRS = createobject("adodb.recordset")
set objChildRS = createobject("adodb.recordset")
strSQL = "SHAPE APPEND" & _
" NEW adVarChar(255) AS UOADDisplayName, " & _
" NEW adVarChar(255) AS UOADTrusteeName, " & _
" NEW adVarChar(255) AS UOADLegacyDN, " & _
" ((SHAPE APPEND " & _
" NEW adVarChar(255) AS MRmbox, " & _
" NEW adVarChar(255) AS MRFolder, " & _
" NEW adVarChar(255) AS MRTrusteeName, " & _
" NEW adVarChar(255) AS MRRights) " & _
" RELATE UOADLegacyDN TO MRTrusteeName) AS rsUOMR"
objParentRS.LockType = 3
objParentRS.Open strSQL, conn1

Set Rs = Com.Execute
While Not Rs.EOF
objParentRS.addnew
objParentRS("UOADDisplayName") = rs.fields("displayname")
objParentRS("UOADTrusteeName") = rs.fields("samaccountname")
objParentRS("UOADLegacyDN") = rs.fields("legacyExchangeDN")
objParentRS.update
Set objChildRS = objParentRS("rsUOMR").Value
inplinearray = Split(rs.fields("msExchHomeServerName").value, "=", -1, 1)
CDOAddr =
getpermissions(inplinearray(ubound(inplinearray)),rs.fields("samaccountname").value,rs.fields("displayname").value)
rs.movenext
Wend
wscript.echo "Number of Mailboxes Checked " & objParentRS.recordcount
Wscript.echo

objParentRS.MoveFirst
Do While Not objParentRS.EOF
Set objChildRS = objParentRS("rsUOMR").Value
if objChildRS.recordcount <> 0 then wscript.echo objParentRS("UOADDisplayName")
Do While Not objChildRS.EOF
wscript.echo " " & objChildRS.fields("MRmbox") & _
" " & objChildRS.fields("MRFolder") & " " & objChildRS.fields("MRRights")
objChildRS.movenext
loop
objParentRS.MoveNext
loop

function getpermissions(servername,mailboxname,displayname)
wscript.echo "Processing " & mailboxname
Set objSession = CreateObject("MAPI.Session")
objSession.Logon "","",false,true,true,true,servername & vbLF & mailboxname
if err.number <> 0 then wscript.echo err.description
err.clear
set objCuser = objSession.CurrentUser
Set CdoInfoStore = objSession.GetInfoStore
Set CdoFolderRoot = CdoInfoStore.RootFolder
Set ACLObj = CreateObject("MSExchange.aclobject")
ACLObj.CDOItem = CdoFolderRoot
Set FolderACEs = ACLObj.ACEs
For each fldace in FolderACEs
if cstr(objCuser.address) <> cstr(GetACLEntryName(fldace.ID, objSession)) then
objChildRS.addnew
objChildRS("MRmbox") = mailboxname
objChildRS("MRFolder") = "Root"
objChildRS("MRTrusteeName") = GetACLEntryName(fldace.ID, objSession)
objChildRS("MRRights") = DispACERules(fldace)
objChildRS.update
end if
Next
Set CdoFolders = CdoFolderRoot.Folders
Set CdoFolder = CdoFolders.GetFirst
do while Not (CdoFolder Is Nothing)
ACLObj.CDOItem = CdoFolder
Set FolderACEs = ACLObj.ACEs
For each fldace in FolderACEs
if cstr(objCuser.address) <> cstr(GetACLEntryName(fldace.ID, objSession)) then

objChildRS.addnew
objChildRS("MRmbox") = mailboxname
objChildRS("MRFolder") = CdoFolder.Name
objChildRS("MRTrusteeName") = GetACLEntryName(fldace.ID, objSession)
objChildRS("MRRights") = DispACERules(fldace)
objChildRS.update
end if
Next
Set CdoFolder = CdoFolders.GetNext
loop
if Not objSession Is Nothing Then objSession.Logoff
set objSession = nothing
End function

Function GetACLEntryName(ACLEntryID,SubSession)

select case ACLEntryID
case "ID_ACL_DEFAULT"
GetACLEntryName = "Default"
case "ID_ACL_ANONYMOUS"
GetACLEntryName = "Anonymous"
case else
Set tmpEntry = SubSession.GetAddressEntry(ACLEntryID)
tmpName = tmpEntry.address
GetACLEntryName = tmpName
end select
Set objSession = nothing
Set CdoFolderRoot = nothing
Set ACLObj = nothing
Set FolderACEs = nothing
Set objSession = nothing

End Function

Function DispACERules(DisptmpACE)

Select Case DisptmpACE.Rights

Case ROLE_NONE, 0 ' Checking in case the role has not been set on that entry.
DispACERules = "None"
Case 1024 ' Check value since ROLE_NONE is incorrect
DispACERules = "None"
Case ROLE_AUTHOR
DispACERules = "Author"
Case 1051 ' Check value since ROLE_AUTHOR is incorrect
DispACERules = "Author"
Case ROLE_CONTRIBUTOR
DispACERules = "Contributor"
Case 1026 ' Check value since ROLE_CONTRIBUTOR is incorrect
DispACERules = "Contributor"
Case 1147 ' Check value since ROLE_EDITOR is incorrect
DispACERules = "Editor"
Case ROLE_NONEDITING_AUTHOR
DispACERules = "Nonediting Author"
Case 1043 ' Check value since ROLE_NONEDITING AUTHOR is incorrect
DispACERules = "Nonediting Author"
Case 2043 ' Check value since ROLE_OWNER is incorrect
DispACERules = "Owner"
Case ROLE_PUBLISH_AUTHOR
DispACERules = "Publishing Author"
Case 1179 ' Check value since ROLE_PUBLISHING_AUTHOR is incorrect
DispACERules = "Publishing Author"
Case 1275 ' Check value since ROLE_PUBLISH_EDITOR is incorrect
DispACERules = "Publishing Editor"
Case ROLE_REVIEWER
DispACERules = "Reviewer"
Case 1025 ' Check value since ROLE_REVIEWER is incorrect
DispACERules = "Reviewer"
Case Else
DispACERules = "Custom"
End Select

End Function

Setting the frame sizes in OWA 2003 programmatically

Had an Interesting question about adjusting the default frame sizes in OWA 2003 that I thought I’d share. In OWA 2003 there are two frames that a user can adjust the size off themselves and these changes are stored so that the next time the user goes into OWA the frame positions are remembered.

The left most frame which houses the navigation bar and OWA shortcuts is controlled via the http://schemas.microsoft.com/exchange/webclientnavbarwidth property which exists on the root folder of the mailbox eg http://servername/exchange/mailbox. You may want to make it wider or narrower depending if your customizing other parts of OWA. The other frame that is adjustable in the right most frame which holds the preview pain. The size of this frame is controlled by the http://schemas.microsoft.com/exchange/wcviewwidth property which is located on the inbox folder eg (http://servername/exchange/mailbox/inbox).

Both these properties are integers and if I was to have a guess I would say the integers represent the size of the frames in pixels. If you want to modify the values you can use a WebDAV proppatch an example script would look like the following I’ve put a downloadable copy of this code here . Setting this property doesn’t affect the user’s ability to resize the frame themselves.


servername = "servername"
mailbox = "mailbox"

xmlhdr = "<?xml version=""1.0"" encoding=""UTF-8"" ?>"
xmlhdr = xmlhdr & "<D:propertyupdate xmlns:D=""DAV:"" xmlns:a=""http://schemas.microsoft.com/exchange/"">"
xmlhdr = xmlhdr & "<D:set>"
xmlhdr = xmlhdr & "<D:prop>"
xmlftr = xmlftr & "</D:prop>"
xmlftr = xmlftr & "</D:set>"
xmlftr = xmlftr & "</D:propertyupdate>"

sDestinationURL = "http://" & servername & "/exchange/" & mailbox & "/"
xmlstr = xmlhdr & "<a:webclientnavbarwidth>200</a:webclientnavbarwidth>" &
xmlftr
df = sendrequest(xmlstr,sDestinationURL)

sDestinationURL = "http://" & servername & "/exchange/" & mailbox & "/inbox"
xmlstr = xmlhdr & "<a:wcviewwidth>400</a:wcviewwidth>" & xmlftr
df = sendrequest(xmlstr,sDestinationURL)

function sendrequest(xmlstr,sDestinationURL)
Set XMLreq = CreateObject("Microsoft.xmlhttp")
XMLreq.open "PROPPATCH", sDestinationURL, False
XMLreq.setRequestHeader "Content-Type", "text/xml;"
XMLreq.setRequestHeader "Translate", "f"
XMLreq.setRequestHeader "Content-Length:", Len(xmlstr)
XMLreq.send(xmlstr)

If (XMLreq.Status >= 200 And XMLreq.Status < 300) Then
Wscript.echo "Success! " & "Results = " & XMLreq.Status & ": " &
XMLreq.statusText
ElseIf XMLreq.Status = 401 then
Wscript.echo "You don't have permission to do the job! Please check your
permissions on this item."
Else
Wscript.echo "Request Failed. Results = " & XMLreq.Status & ": " &
XMLreq.statusText
End If
set XMLreq = nothing
end function
 

Thursday, June 09, 2005

Syslogging the Message Tracking Logs on Exchange 2x

The Syslog protocol is a very popular way of sending log information over TCP/IP to event log collectors (The introduction to Syslog in the RFC is well worth a read).Sendmail can do logging to a syslog server straight of the bat but in the Windows world it unfortunately doesn’t get much of a run. Exchange does make its tracking logs available via WMI as well as the raw tab separated text file but doesn’t give you any way of sending them to another server. To get my Exchange server producing syslog messages for the tracking log data I thought I’d write a small c# console application that would retrieve the tracking log data for the last 5 minutes then create and send syslog messages for each message in the log. Then all I need to do is create a scheduled task on the Exchange boxes to run the app every five minutes.

Digging a bit deeper.

When you dig a bit deeper into the message tracking logs on Exchange you’ll find there are a lot of events that are logged and only some of them are of day to day use. The way I approached the application is that I decided I wanted to log 3 different types of syslog events the first was a Mail.Notice priority syslog message for normal email traffic on the server. I also run the IMF on my exchange boxes so I wanted to send a different Syslog message for any messages that where blocked by the IMF on my server so I decided to use the Mail.Warning priority for any IMF messages. The last event I wanted to know about was any NDR’s that where sent so I used the Mail.Error priority syslog for these. There where a couple of approaches I could have taken to extract these messages from the log files the first would have been just to open the file and parse it out. The second was to query every event for the last five minutes via WMI and then filter out the ones I didn’t want. The third method was to query the logs for each of the different event numbers and use the filtered result set that WMI returns. I went for the third method which means that the code ends up doing three separate queries to get all the different categories of the events I wanted to report on. This didn’t seem to come at two much of a performance penalty and made the code a little more logical to understand. I may switch to another method once I got some more testing done. (I guess a fourth method would have been to use the Microsoft log parser util)

The Code itself

The code itself consists of two functions the first function goes out and grabs all the tracking log events for the last five minutes based on two input parameters which are the eventids and servername and then builds a syslog message for each log entry and then stores the message text in an arraylist which is returned to the calling stub. The main stub then goes though the arraylist and calls the sendsyslog function which takes the syslog message text, the priority of the Syslog message you want to send and the ipaddress of the syslog server you want to send to. The Syslog sending code itself is pretty simple the following links where helping in putting something basic together http://blogs.msdn.com/2004/11/05/252920.aspx and http://www.eggheadcafe.com/articles/20050212.asp . I should make one note about the WMI code when you have a message that is sent to multiple recipients WMI returns this to you as one entry. I guess it all depends on the way you look at it but a message sent to two recipients to me is two messages. So what I’ve done with the code is I create a separate syslog event for every recipient of a message. An alternative to this would be to create one syslog message and then stack the to field this reduces the number of syslog messages but makes it harder to process.

The code is designed to run with two command line parameters the first is the name of the Exchange server you want to extract the data from and the second is the IPaddress of the syslog server you want the syslogs sent to.

Making it real-time

Having this run in real-time vs on a scheduled basis is certainly a more desirable way to go. There is an Event that gets fired "OnMsgTrackLog" which looks like it could be used to hook in and do this with but its undocumented territory so I’ve had to leave untill I have more time.

I’ve put a downloadable copy of the code here the code itself looks like

using System;
using System.Collections;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Management;

namespace ExchangeTrackinglogSender
{
class SendLog
{
static void Main(string[] args)
{
try
{
SendLog sl = new SendLog();
string snServername = args[0];
string snSyslogIPName = args[1];
ArrayList alEmailalist = sl.getRecentLogs(5,snServername,1020,1028);
IEnumerator raEnumerator = alEmailalist.GetEnumerator();
while ( raEnumerator.MoveNext() )
{
sl.sendsyslog(raEnumerator.Current.ToString(),snSyslogIPName,21);
}
ArrayList alIMFalist = sl.getRecentLogs(5,snServername,1039,1039);
IEnumerator raEnumerator1 = alIMFalist.GetEnumerator();
while ( raEnumerator1.MoveNext() )
{
sl.sendsyslog(raEnumerator1.Current.ToString(),snSyslogIPName,20);}
ArrayList alNDRalist = sl.getRecentLogs(5,snServername,1026,1030);
IEnumerator raEnumerator2 = alNDRalist.GetEnumerator();
while ( raEnumerator2.MoveNext() )
{
sl.sendsyslog(raEnumerator2.Current.ToString(),snSyslogIPName,19);}
}
catch(IndexOutOfRangeException e){
Console.WriteLine("Usage exsyslog.exe ");
}
catch(Exception e)
{
System.IO.StreamWriter elErrorlog = new System.IO.StreamWriter("c:\\Syslogsendererror.log",true);
elErrorlog.WriteLine(System.DateTime.Now + " " + e.InnerException + " " + " Exception Description:" + e.ToString());
elErrorlog.Close();
}
}


void sendsyslog(string mtMessagetxt,string iaIpaddress, int spPriority){
UdpClient ucUdpclient = new UdpClient(iaIpaddress, 514);
byte[] rawMsg;
string strParams = System.String.Format("<{0}>{1}",spPriority, mtMessagetxt);
rawMsg = System.Text.Encoding.ASCII.GetBytes(string.Concat(strParams));
ucUdpclient.Send(rawMsg, rawMsg.Length);
ucUdpclient.Close();
ucUdpclient=null;
}
ArrayList getRecentLogs(int tiTimeinterval,string snServername, int idTid1, int idTid2){
ArrayList alRecpalist = new ArrayList();
ConnectionOptions coObjconn = new ConnectionOptions();
coObjconn.Impersonation = ImpersonationLevel.Impersonate;
coObjconn.EnablePrivileges = true;
string qtQuerytime = ManagementDateTimeConverter.ToDmtfDateTime(DateTime.Now.ToUniversalTime().AddMinutes(-tiTimeinterval));
ManagementScope msExmangescope = new ManagementScope(@"\\" + snServername + @"\root\MicrosoftExchangeV2",coObjconn);
ObjectQuery qoObjquery = new ObjectQuery("Select * FROM Exchange_MessageTrackingEntry where entrytype = '" + idTid1 + "' and OriginationTime >= '" + qtQuerytime + "' or entrytype = '" + idTid2 + "' and OriginationTime > '" + qtQuerytime + "'");
System.Management.ManagementObjectSearcher osObjsearch = new System.Management.ManagementObjectSearcher(msExmangescope,qoObjquery);
System.Management.ManagementObjectCollection qcQueryCollection1 = osObjsearch.Get();
foreach( System.Management.ManagementObject reTrackinglogEntry in qcQueryCollection1 )
{
string[] raReciparray = (string[])reTrackinglogEntry["RecipientAddress"];
UInt32[] raRecipStatusarray = (UInt32[])reTrackinglogEntry["RecipientStatus"];
for(int i=0;i<=raReciparray.GetUpperBound(0);i++)
{
string msMsgtext;
msMsgtext = "date=" + ManagementDateTimeConverter.ToDateTime(reTrackinglogEntry["OriginationTime"].ToString()).ToString("yyyy-MM-dd") + ",";
msMsgtext = msMsgtext + "time=" + ManagementDateTimeConverter.ToDateTime(reTrackinglogEntry["OriginationTime"].ToString()).ToString("HH:mm:ss") + ",";
msMsgtext = msMsgtext + "servername=" + snServername + ",eventid=" + reTrackinglogEntry["EntryType"].ToString() + ",";
msMsgtext = msMsgtext + "msgid=" + "\"" + reTrackinglogEntry["MessageID"].ToString() + "\",RecipientType=" + raRecipStatusarray[i] + ",";
msMsgtext = msMsgtext + "nrcpts=" + reTrackinglogEntry["RecipientCount"] + ",";
if(reTrackinglogEntry["subject"] != null) {msMsgtext = msMsgtext + "subject=\"" + reTrackinglogEntry["subject"].ToString().Replace("\"","") + "\",";}
msMsgtext = msMsgtext + "from=" + reTrackinglogEntry["SenderAddress"].ToString() + ",to=" + raReciparray[i] + ",size=" + reTrackinglogEntry["size"].ToString();
alRecpalist.Add(msMsgtext);
}
}
return alRecpalist;

}
}
}

Friday, June 03, 2005

Shaping Outlook Version data with the Exchange_logon WMI Class

A different slant on this script I posted yesterday is if maybe your only interested in just displaying information about the different outlook versions people are using. So what this version of the script does is instead of shaping data from ADSI with WMI we take the Outlook version table from http://www.cdolive.com/build.htm and this time put this in a disconnected recordset and then shape the logon data from WMI to this build table. Using the same trick I used previously you can then either display a table that just shows the count of each Outlook version being used or show a hierarchal view of Outlook versions per user.

To run the script it still takes two command-line parameters the first being the servername and with the second parameter there are 2 options which should be self explanatory

Detail - Show Details of exch Oulook version logged on
Count -Show just the count of Outlook versions logged on

I’ve put a downloadable copy of the script here

Thursday, June 02, 2005

Displaying the Logon Status using Data shaping via ADSI and the Exchange_Logon WMI Class in Exchange 2003

Being able to display logon information via the various Exchange administrator tools has been around for a while but until Exchange 2003 there was never any scriptable interface you could use to display this data . Although for various reasons this data is never 100% accurate it can be used to get an indication of who’s logged onto the server and what client they are using. If you shape the data you can retrieve using Exchange_logon with a full list of mailboxes on that server retrieved via ADSI then you can get a bit more of a clear picture as to who is logged on, who is not logged on, how many people are logged on to one particular mailbox, how they are logged on (OWA or Outlook) and what version of outlook they are using.

The script itself uses the same ADO data shaping techniques I described in this post. Some different bits and pieces that have been added to this script are

Front End
The Front end of the code accepts two command line variables the first is the severname of the Exchange server you want to run it against and the second is the type of logon you want to report on. With the second parameter there are 5 options which should be self explanatory

OWA -Show user logged on via Outlook Web Access"
Outlook -Show users logged on via Outlook"
Loggedon -Show All logged on Users"
Loggedout -Show Users not Logged On"
ALL -Show all users Logged in and Out"

Displaying the Outlook version

The Exchange_Logon class displays the version of Outlook that is being used by the client to connect to exchange. There is a complete list of which versions relates to which Outlook build on http://www.cdolive.com/build.htm . I’ve taken this list and dropped it into a Case statement in the script so I can display the friendly Outlook build name instead of the the build version number. If you are using a build number not on the list then the script should just output the version number

Displaying IP address and Cache/Online Mode if the client is using Outlook 2003

Outlook 2003 now allows you to track weather a user is in cache mode or online mode as well as the IP address of the client PC. The WMI class returns an integer indicating weather the client is using cache mode or online so I’ve added a simple function to convert this to a friendly name. The IP address is displayed if possible if not it just shows blank.

With the ADSI query it only shows the visible users in the GAL for that server and ignores any hidden mailboxes. If you wanted to include hidden mailboxes you’ll need to tweak the ADSI.

The WMI query will differ based on the command line parameters you enter in. The rest of the script is pretty straight forward. One thing to note is i haven't tested this with OMA user logging on.(I think it will show them as OWA users)

To run the script use something like cscript displogon.vbs servername ALL

I’ve put a downloadable copy of the script here the code itself looks like

if WScript.Arguments.Count <> 2 then
call DisplayUsage
else
call Main()
end if


sub main()
servername = wscript.arguments(0)
showarg = lcase(wscript.arguments(1))
set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
set conn1 = createobject("ADODB.Connection")
strConnString = "Data Provider=NONE; Provider=MSDataShape"
conn1.Open strConnString
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
set objParentRS = createobject("adodb.recordset")
set objChildRS = createobject("adodb.recordset")
strSQL = "SHAPE APPEND" & _
" NEW adVarChar(255) AS ADDisplayName, " & _
" NEW adVarChar(255) AS ADLegacyDN, " & _
" ((SHAPE APPEND " & _
" NEW adVarChar(255) AS WMIDisplayName, " & _
" NEW adVarChar(255) AS WMILegacyDN, " & _
" NEW adVarChar(255) AS WMILoggedOnUserAccount, " & _
" NEW adVarChar(255) AS WMIClientVersion, " & _
" NEW adVarChar(255) AS WMIClientIP, " & _
" NEW adVarChar(255) AS WMIClientMode " & _
")" & _
" RELATE ADLegacyDN TO WMILegacyDN) AS rsADWMI "
objParentRS.LockType = 3
objParentRS.Open strSQL, conn1
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
svcQuery = ""<LDAP://" & strNameingContext & "">;(&(objectCategory=msExchExchangeServer)(cn=" & Servername & "));cn,name,distinguishedName,legacyExchangeDN;subtree"
Com.ActiveConnection = Conn
Com.CommandText = svcQuery
Set Rs = Com.Execute
while not rs.eof
GALQueryFilter = "(&(&(&(& (mailnickname=*)(!msExchHideFromAddressLists=TRUE)(| (&(objectCategory=person)(objectClass=user)(msExchHomeServerName=" & rs.fields("legacyExchangeDN") & ")) )))))"
strQuery = ";" & GALQueryFilter & ";distinguishedName,displayname,legacyExchangeDN,homemdb;subtree"
com.Properties("Page Size") = 100
Com.CommandText = strQuery
Set Rs2 = Com.Execute
while not rs2.eof
objParentRS.addnew
objParentRS("ADDisplayName") = rs2.fields("displayname")
objParentRS("ADLegacyDN") = rs2.fields("legacyExchangeDN")
objParentRS.update
rs2.movenext
wend
wscript.echo "finished 1st AD of Mailbox's"
rs.movenext
wend

strWinMgmts ="winmgmts:{impersonationLevel=impersonate}!//"& servername &"/root/MicrosoftExchangeV2"
Select case showarg
case "owa" sqlstate = "Select * FROM Exchange_Logon where StoreType = 1 and ClientVersion = 'HTTP'"
case "outlook" sqlstate = "Select * FROM Exchange_Logon where StoreType = 1 and ClientVersion <> 'SMTP' AND ClientVersion <> 'OLEDB' AND ClientVersion <> 'HTTP'"
case else sqlstate = "Select * FROM Exchange_Logon where StoreType = 1 and ClientVersion <> 'SMTP' AND ClientVersion <> 'OLEDB'"
end select
Set objWMIExchange = GetObject(strWinMgmts)
Set listExchange_ExchangeLogons = objWMIExchange.ExecQuery(sqlstate,,48)
objChildRS.LockType = 3
Set objChildRS = objParentRS("rsADWMI").Value
For each objExchange_ExchangeLogon in listExchange_ExchangeLogons
if objExchange_ExchangeLogon.LoggedOnUserAccount <> "NT AUTHORITY\SYSTEM" then
objChildRS.addnew
objChildRS("WMIDisplayName") = objExchange_ExchangeLogon.MailboxDisplayName
objChildRS("WMILegacyDN") = objExchange_ExchangeLogon.MailboxLegacyDN
objChildRS("WMILoggedOnUserAccount") = objExchange_ExchangeLogon.LoggedOnUserAccount
objChildRS("WMIClientVersion") = objExchange_ExchangeLogon.ClientVersion
objChildRS("WMIClientIP") = objExchange_ExchangeLogon.ClientIP
objChildRS("WMIClientMode") = objExchange_ExchangeLogon.ClientMode
objChildRS.update
end if
Next
wscript.echo "finished Exchange WMI query"
Wscript.echo "Dislay Results " & showarg
wscript.echo
objParentRS.MoveFirst
Do While Not objParentRS.EOF
Set objChildRS = objParentRS("rsADWMI").Value
objChildRS.sort = "WMILoggedOnUserAccount"
select case showarg
case "all" Wscript.echo objParentRS.fields("ADDisplayName")
if objChildRS.recordcount = 0 then Wscript.echo " " & "Not Logged On"
case "loggedon" if objChildRS.recordcount <> 0 then Wscript.echo objParentRS.fields("ADDisplayName")
case "owa" if objChildRS.recordcount <> 0 then Wscript.echo objParentRS.fields("ADDisplayName")
case "outlook" if objChildRS.recordcount <> 0 then Wscript.echo objParentRS.fields("ADDisplayName")
case "loggedout"if objChildRS.recordcount = 0 then Wscript.echo objParentRS.fields("ADDisplayName")
case else Wscript.echo objParentRS.fields("ADDisplayName")
end select
if showarg <> "loggedout" then
Do While Not objChildRS.EOF
currec = objChildRS.fields("WMILoggedOnUserAccount") & objChildRS.fields("WMIClientVersion") & objChildRS.fields("WMIClientIP") & objChildRS.fields("WMIClientMode")
if currec <> prevrec then
Wscript.echo " " & objChildRS.fields("WMILoggedOnUserAccount") & " " & getversion(objChildRS.fields("WMIClientVersion")) & " " & _
getmode(objChildRS.fields("WMIClientMode")) & " " & objChildRS("WMIClientIP")
end if
prevrec = currec
objChildRS.MoveNext
Loop
end if
objParentRS.MoveNext
Loop

end sub


function getversion(version)

Select case version
case "4.0.994.0" getversion = "Outlook 97 Initial release in Q1/1997."
case "5.0.1457.0" getversion = "Outlook 97 Ships only with Microsoft Exchange 5.0 Service Pack 1"
case "5.0.1458.0" getversion = "Outlook 97 Ships only with Microsoft Office 97 SR-1"
case "5.0.1960.0" getversion = "Outlook 97 Ships only with Microsoft Exchange Server 5.5 and Microsoft Exchange 5.0 Service Pack 2"
case "5.0.2178.0" getversion = "Outlook 98 Initial release in Q1/1998."
case "5.0.2819.0" getversion = "Outlook 2000 Initial release in Q2/1999"
case "5.0.3121.0" getversion = "Outlook 2000 update included with Office 2000 SR1 (and SR1a)"
case "5.0.3136.0" getversion = "Outlook 2000 security update patch"
case "5.0.3144.0" getversion = "Outlook 2000 with Service Pack 2 installed"
case "10.0.0.3311" getversion = "Outlook 2002 with hotifx"
case "8.00.3511" getversion = "Outlook 97 Initial release in Q1/1997."
case "8.01.3817" getversion = "Outlook 97 Ships only with Microsoft Exchange 5.0 Service Pack 1"
case "8.02.4212" getversion = "Outlook 97 Ships only with Microsoft Office 97 SR-1"
case "8.03.4629" getversion = "Outlook 97 Ships only with Microsoft Exchange Server 5.5 and Microsoft Exchange 5.0 Service Pack 2"
case "8.04.5619" getversion = "Outlook 97 Ships only with Microsoft Office 97 SR-2"
case "8.5.5104.6" getversion = "Outlook 98 Initial release in Q1/1998. Is included with the Microsoft Exchange 5.5 Service Pack 1 CD-ROM (not available for download at the Microsoft site)"
case "8.5.5603.0" getversion = "Outlook 98 Microsoft Outlook 98 Security Patch 2 "
case "8.5.7806" getversion = "Outlook 98 Outlook 98 security update"
case "9.0.0.2711" getversion = "Outlook 2000 Initial Release in Q2/1999"
case "9.0.0.3011" getversion = "Outlook 2000 Microsoft Office 2000 Developer Edition released in Q3/1999"
case "9.0.0.3821" getversion = "Outlook 2000 update included with Office 2000 SR1 (and SR1a)"
case "9.0.0.4201" getversion = "Outlook 2000 security update patch installed."
case "9.0.0.4527" getversion = "Outlook 2000 with Service Pack 2 installed"
case "9.0.0.6673" getversion = "Outlook 2000 - SP3"
case "10.0.0.2625" getversion = "Outlook 2002 Initial release in Q1/2001."
case "10.0.0.2627" getversion = "Outlook 2002 Initial release in Q1/2001."
case "10.0.0.3513" getversion = "Outlook 2002 with Service Pack 1"
case "10.0.0.3501" getversion = "Outlook 2002 with Service Pack 1"
case "10.0.0.4115" getversion = "Outlook 2002 with Service Pack 2"
case "10.0.0.3416" getversion = "Outlook 2002 with Service Pack 1"
case "10.0.0.4219" getversion = "Outlook 2002 with Service Pack 2"
case "10.0.0.6515" getversion = "Outlook 2002 with Service Pack 3"
case "10.0.0.6626" getversion = "Outlook 2002 with Service Pack 3"
case "11.0.5604.0" getversion = "Outlook 2003 Initial release Oct. 2003 RTM Build"
case "11.0.5606.0" getversion = "Outlook 2003 Initial release Oct. 2003 RTM Build"
case "11.0.5608.0" getversion = "Outlook 2003 Initial release Oct. 2003 RTM Build"
case "11.0.5703.0" getversion = "Outlook 2003 with critical update releases on 11.4.2003"
case "11.0.6353.0" getversion = "Outlook 2003 SP1, released August 2003. "
case "11.0.6352.0" getversion = "Outlook 2003 SP1, released August 2003. "
case "HTTP" getversion = "Outlook Web Access"
case else getversion = version
end select

end function

function getmode(clientmode)
select case clientmode
case 1 getmode = "Classic Online"
case 2 getmode = "Cached Mode"
case else getmode = " "
end select
end function

public sub DisplayUsage
WScript.echo "usage: cscript displogon.vbs "
WScript.echo "Vaid Modes"
WScript.echo " OWA - Show user logged on via Outlook Web Access"
WScript.echo " Outlook -Show users logged on via Outlook"
WScript.echo " Loggedon -Show All logged on Users"
WScript.echo " Loggedout -Show Users not Logged On"
WScript.echo " ALL -Show all users Logged in and Out"
end sub