Not sure that this list supports attachments - but here it is.

 

Here's how I launch it every half hour:

 

cscript //Nologo ExtractLDAP.wsf 70.255.255.84 "ou=Their
Staff,dc=TheirCompany,dc=local" [email protected] mypassword
"domainalias1.com domainalias2.com domainalias3.com" TheirCompany

 

I usually use the LDAP Explorer tool to make sure I can connect to their
LDAP port through their firewall, that they have set up a valid
user/password for me, etc. Then I navigate through their LDAP hierarchy to
determine the correct OU/DC/DC, CN/DC/DC, etc path to their email users.
Once that succeeds I can simply take that info and use it as the parameters
to my script.

 

From: [email protected] [mailto:[email protected]] On Behalf Of Michael
Cummins
Sent: Wednesday, May 12, 2010 3:25 PM
To: [email protected]
Subject: RE: [Declude.JunkMail] Fine tuning Declude

 

That sounds like it would be fun to review, regardless.  I can dig up my old
script and post it, too.  Mine is pretty primitive: spew and parse.

 

Does it reach out to LDAP from the internet side of things, through a
properly configured firewall, I imagine?  Mine was a local script that
uploaded.  I like your idea better, if I am reading it right.  With your
idea, I provide minimum requirements instead of installation steps.

 

 

Very Respectfully, 

 

Michael Cummins 



---
This E-mail came from the Declude.JunkMail mailing list.  To
unsubscribe, just send an E-mail to [email protected], and
type "unsubscribe Declude.JunkMail".  The archives can be found
at http://www.mail-archive.com.
<?XML version="1.0" standalone="yes" ?>
<package>

<job id="ExtractLDAPAdr">
<?job error="true" debug="true" ?>
<reference object="Scripting.FileSystemObject" />
<reference object="ADODB.Connection" />
<reference object="ADOX.Catalog" />
<reference object="ADODB.Recordset"/>

<script language="JScript">
<![CDATA[

// 
===============================================================================
// Extract Email Addresses from Active Directory
// 
------------------------------------------------------------------------------- 
//
//      Author:      © 2005, Andy Schmidt
//      Email:       [email protected]
//      Runtime:     Windows Scripting Host 5.6
//
//
// 
------------------------------------------------------------------------------- 
//
//      CHANGE HISTORY
//
//      1.0.0 05-Apr-05 (AS)  Initial Development.
//      1.1.0 17-Jan-07 (AS)  Generalization and SQL sanitizing
//      1.2.0 19-Feb-07 (AS)  Set Page Size ADO property for large query results
//      1.3.0 15-Apr-08 (AS)  Allow for CommandLine Parameters
//      1.3.1 22-Apr-08 (AS)  Reliable detection of DupRec return code from JET
//                            Permit Origin length of 15, check for max length
//
// 
===============================================================================


// ----------------------------------------------
//   Global Constants
// ----------------------------------------------

var nPageSize =         2000;   // (LDAP)

var strMDBFileName =    'ImailAdr.mdb';
var strMDBConn =        'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=';

var strTable =          'UserList';
var strTableCreate = "CREATE TABLE [" + strTable + "] ( [Domain] CHARACTER(255) 
NOT NULL, [Host] CHARACTER(255) CONSTRAINT [HostKey] NOT NULL, [User] 
CHARACTER(255) NOT NULL, [Email] CHARACTER(255) NOT NULL CONSTRAINT 
[PrimaryKey] PRIMARY KEY, [Current] BIT, [Origin] CHARACTER(15) NOT NULL );";
var strIndexCreate = "CREATE INDEX HostKey ON [" + strTable + "] ( [Host] ) 
WITH DISALLOW NULL;";


// ----------------------------------------------
//   Global Variables
// ----------------------------------------------

var retCode =           0;
var bListOnly =         false;
var nAddresses =        0;
var nInserted =         0;
var nUpdated =          0;
var nRecordsEffected =  0;

var i, tempstr, temparr;
var strDomain, strEmail;


// ==============================================
//   Prolog
// ==============================================

// Instantiate core objects
var objShell = WScript.CreateObject("WScript.Shell");
var objCat = WScript.CreateObject("ADOX.Catalog");
var objConn = WScript.CreateObject("ADODB.Connection");
var objRS = WScript.CreateObject("ADODB.Recordset");

// Get Command Line Parameters
if ( WScript.Arguments.Unnamed.Length < 6 || WScript.Arguments.Unnamed.Length > 
7  )
        {
        WScript.Echo( 'Incorrect number of command line parameters: ' + 
WScript.Arguments.Unnamed.Length + '. ');
        WScript.Arguments.ShowUsage();
        WScript.Quit( -4 );
        }

var strComputer =       WScript.Arguments.Unnamed.Item(0);
var adBase =            WScript.Arguments.Unnamed.Item(1);
var adUser =            WScript.Arguments.Unnamed.Item(2);
var adPwd =             WScript.Arguments.Unnamed.Item(3);
var strDomains =        " " + WScript.Arguments.Unnamed.Item(4) + " ";
var strOrigin =         WScript.Arguments.Unnamed.Item(5);

if ( WScript.Arguments.Unnamed.Length > 6 )
        bListOnly =             ( WScript.Arguments.Unnamed.Item(6) == "1" ? 
true : false );

WScript.Echo( (bListOnly ? 'Listing' : 'Copying' ) + ' "' + strOrigin + '" from 
"' + strComputer + ' ' + adBase + '".');

// Configure Database
if ( !bListOnly )
        {
        // Create connection string to database in current directory
        var strMDBPath = objShell.CurrentDirectory;
        var strConn = strMDBConn + strMDBPath + "\\" + strMDBFileName + ";";

        // Attempt to create database file
        try     { objCat.Create( strConn ); }
            catch(e) 
                { 
                switch( 0x7FFFFFFF & e.number )
                  {
                  case 0x40E17:
                        // Database already exists -> ok
                        break;
                  default:
                        handleException( e ); 
                  }
                }

        // Open connection to database file
        try     { objConn.Open( strConn ); }
            catch(e) { handleException( e ); }

        // Attempt to create schema
        try
                { 
                objConn.Execute( strTableCreate, null, adExecuteNoRecords );
                objConn.Execute( strIndexCreate, null, adExecuteNoRecords );
                }
            catch(e) 
                { 
                switch( 0x7FFFFFFF & e.number )
                  {
                  case 0x04005:
                  case 0x40e14:
                        // Schema already exists -> ok
                        break;
                  default:
                        handleDBException( e, objConn ); 
                  }
                }

        // Prepare table for access
        try
                { 
                // Reset flag so we can detect outdated records
                objConn.Execute( "UPDATE [" + strTable + "] SET [Current] = 0 
WHERE Origin = '" + strOrigin + "';", nRecordsEffected, adExecuteNoRecords );
                // Open empty recordset against table
                objRS.Open( "SELECT * FROM [" + strTable + "] WHERE Origin = '" 
+ strOrigin + "' AND [Current] = 1;" , objConn, adOpenForwardOnly, 
adLockOptimistic, adCmdText );
                } 
            catch(e) { handleDBException( e, objConn ); }
        }


// ==============================================
//   Mainline
// ==============================================

try
        {
        var objADConn = new ActiveXObject( 'ADODB.Connection' );
        objADConn.Provider = 'ADsDSOObject';
        objADConn.Properties( "User ID" ) = adUser;
        objADConn.Properties( "Password" ) = adPwd;
        objADConn.Properties( "ADSI Flag" ) = 0x220;
        objADConn.Open();

        var objADcmd = new ActiveXObject( 'ADODB.Command' );
        objADcmd.ActiveConnection = objADConn;
        objADcmd.Properties( "Page Size" ) = nPageSize;
        // objADcmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE;
        objADcmd.CommandText = "SELECT proxyAddresses FROM 'LDAP://" + 
strComputer + "/" + adBase + "' WHERE proxyAddresses = '*'";
        var objADRS = objADcmd.Execute();

        while ( !objADRS.EOF )
                {
                var arrAddresses = new VBArray( objADRS( 'proxyAddresses' 
).Value );
                // go through multistring attribute
                for ( i=arrAddresses.lbound(); i<=arrAddresses.ubound(); i++ )
                        {
                        // get one string from the array
                        tempstr = arrAddresses.getItem( i ).toLowerCase();
                        // seprate any method prefix from user and domain
                        temparr = tempstr.split( /[:@]/ );
                        if (   ( temparr.length == 3 && tempstr.indexOf(':') > 
0 && temparr[0] == 'smtp' )
                            || ( temparr.length == 2 && tempstr.indexOf('@') > 
0) )
                                {
                                strDomain = temparr[temparr.length - 1];
                                strEmail = temparr[temparr.length - 2] + "@" + 
strDomain;

                                if ( strDomains.indexOf( " " + strDomain + " " 
) >= 0 )
                                        {
                                        // compare against list of domains
                                        if ( bListOnly )
                                                WScript.Echo( strDomain + '\t' 
+ strEmail )
                                        else
                                                createOutput( strDomain, 
temparr[temparr.length - 2], strEmail );
                                        }
                                }
                        }
                objADRS.MoveNext();
                }

        objADRS.Close();
        objADConn.Close();
        }

   catch(e) { handleException( e ); }


// ----------------------------------------------
//   Epilog
// ----------------------------------------------

if ( !bListOnly )
        {
        objRS.Close();

        // Remove obsolete email addresses
        try     { objConn.Execute( "DELETE FROM [" + strTable + "] WHERE Origin 
= '" + strOrigin + "' AND [Current] = 0;", nRecordsEffected, adExecuteNoRecords 
); } 
            catch(e) { handleDBException( e, objConn ); }

        objConn.Close();

        WScript.Echo( 'Inserted ' + nInserted + ' new records, kept ' + 
nUpdated + ' existing records. ');
        }

WScript.Quit( retCode );


// ==============================================
//   Helper Functions
// ==============================================

// Create output record
function createOutput( vDomain, vUser, vEmail )
{
        try 
                {
                objRS.AddNew();
                objRS( 'Domain' ) = vDomain;
                objRS( 'Host' ) = vDomain;
                objRS( 'User' ) = vUser;
                objRS( 'Email' ) = vEmail;
                objRS( 'Current' ) = true;
                objRS( 'Origin' ) = strOrigin;
                objRS.Update();
                nInserted++;
                } 
            catch(e) 
                {
                switch( 0x7FFFFFFF & e.number )
                  {
                  case 0x40e21:
                        if ( objConn.Errors.Count == 1 )
                                {
                                var objConnErr = ( new 
Enumerator(objConn.Errors) ).item();
                                if ( objConnErr.NativeError == -105121349 )
                                        {
                                        // Native Error indicates duplicate 
record
                                        objRS.CancelUpdate();
                                        objConn.Execute( "UPDATE [" + strTable 
+ "] SET [Current] = -1 WHERE Origin = '" + strOrigin + "' AND Email = '" + 
sanSQLstr(strEmail) + "';", nRecordsEffected, adExecuteNoRecords );
                                        nUpdated++;
                                        break;
                                        }
                                }
                  default:
                        WScript.Echo( "Error at: " + vDomain + " | " + vUser + 
" | " + vEmail + " | " + strOrigin );
                        handleDBException( e, objConn );
                  }
                }
}

// Sanitize SQL input
function sanSQLstr( vInput, vMaxLength )
{
        // Regular Expression to double-up quotes
        var reQuote = /'/gm;
        var str2Quotes = "''";

        // Regular Expression SQL comments and system functions
        var reInvalid = /(--|\/\*|\*\/|@@)/m;

        // Default Maximum Length to 255
        var nMaxLength = ( vMaxLength == null ? 255 : vMaxLength );

        // convert to string, in case still Response object
        var strTemp = new String( vInput );

        // check if string contains special SQL characters
        if ( reInvalid.exec( strTemp ) )
                throw( 'Invalid variable: "' + RegExp.$1 + '"!' );

        // truncate string to maximum length
        strTemp = strTemp.substring( 0, nMaxLength );

        // replace single quotes with double quotes
        return( strTemp.replace( reQuote, str2Quotes ) );     
}

function sanSQLint( vString )
{
        var nValue = new Number( vString );
        if ( isNaN( nValue ) )
                throw( 'Invalid variable: "' + vString + '"!' );
        return( nValue.valueOf() );     
}


// 
------------------------------------------------------------------------------------------
//      Exception Handling and Reporting.
// 
------------------------------------------------------------------------------------------

// Format Windows error codes
function hex(nmb)
{
    if (nmb > 0)
        return nmb.toString(16);
    else
        return (nmb + 0x100000000).toString(16);
}

function handleException( vE )
{
        if ( isNaN(vE.number) )
                {
                WScript.Echo( 'Error: ' + vE );
                retCode = -1;
                }
        else
                {
                WScript.Echo( 'Error: ' + hex(vE.number) + ', ' + 
vE.description );
                retCode = vE.number;
                }

        WScript.Echo( 'Script Aborted! ' );
        WScript.Quit( retCode );
}

function handleDBException( vE, vObj )
{
        var eErr, objErr;

        WScript.Echo( "Database error!" );
        if ( !isNaN(vE.number) )
                WScript.Echo( "WScript Error: " + vE.description + ", " + 
vE.number + " [0x" + hex(vE.number) + "] " );
        if ( vObj.Errors.Count > 0 )
                {
                eErr = new Enumerator(vObj.Errors);
                for ( ; !eErr.atEnd(); eErr.moveNext() )
                        {
                        objErr = eErr.item();
                        WScript.Echo( objErr.Source + " reports: " + 
objErr.Description + ", " + objErr.Number + " [0x" + hex(objErr.Number) + "]" );
                        WScript.Echo( "Native Error: " + objErr.NativeError + " 
[0x" + hex(objErr.NativeError) + "]" );
                        WScript.Echo( "SQL State: " + objErr.SQLState );
                        }
                }
        WScript.Echo( "Script Aborted!" );
        WScript.Quit( -2 );
}

]]>
</script>

</job>
</package>

---
This E-mail came from the Declude.JunkMail mailing list.  To
unsubscribe, just send an E-mail to [email protected], and
type "unsubscribe Declude.JunkMail".  The archives can be found
at http://www.mail-archive.com.

Reply via email to