简体   繁体   English

如何使用Active Directory中的用户信息填充SQL Server表?

[英]How to populate an SQL Server table with users information from Active Directory?

使用SSIS包中的VB.NET,如何用多个Active Directory域(在同一林中)的用户填充SQL Server表?

I went the route of using a query similar to Siva's approach except instead of a linked server query, I use the ADSI provider. 除了使用链接服务器查询之外,我使用ADSI提供程序来使用与Siva相似的查询。 Active Directory SSIS Data Source Active Directory SSIS数据源

SELECT
    distinguishedName
,   mail
,   samaccountname
,   Name
,   employeeNumber
,   objectSid
,   userAccountControl
,   givenName
,   middleName
,   sn
FROM
    'LDAP://DC=domain,DC=net'
WHERE
    sAMAccountType = 805306368
ORDER BY
    sAMAccountName ASC

The code in the referenced post will pull all users from a given domain. 引用的帖子中的代码将从指定域中提取所有用户。 After converting from NTEXT to TEXT to String, I then use the distinguished name and the DirectoryServices assembly to enumerate all the first order groups for a user via their distinguished name. 从NTEXT转换为TEXT转换为String之后,我然后使用专有名称和DirectoryServices程序集通过其专有名称枚举用户的所有第一订单组。 It does not address nested groups. 它不解决嵌套组。 Conveniently enough, that post covered a 2005 SSIS implementation so the logic is in VB. 方便的是,该帖子涵盖了2005 SSIS实现,因此逻辑在VB中。

Linked Server approach: 链接服务器方法:

Set up a linked server to connect to Active Directory: 设置链接服务器以连接到Active Directory:

Here is one possible option using Linked Server on SQL Server that does not actually require VB.NET , if that is an option for you. 这是在SQL Server上使用链接服务器的一种可能的选项,实际上它不需要VB.NET ,如果您可以选择的话。 The queries given below are only for syntax references. 下面给出的查询仅用于语法参考。 Please read the links for proper usage of these SQL Server objects. 请阅读链接以正确使用这些SQL Server对象。

You could set up a linked server on SQL Server to connect to the Active Directory using OLE DB Provider for Microsoft Directory Services . 您可以在SQL Server上设置链接服务器,以使用OLE DB Provider for Microsoft Directory Services连接到Active Directory Below is a sample script that would set up a linked server and map it with a login that has access to the Active directory. 下面是一个示例脚本,该脚本将设置链接服务器,并使用有权访问Active Directory的登录名将其映射。

Usage of sp_addlinkedserver (Transact-SQL) sp_addlinkedserver的用法(Transact-SQL)

Usage of sp_addlinkedsrvlogin (Transact-SQL) sp_addlinkedsrvlogin的用法(Transact-SQL)

Sample script to set up linked server: 设置链接服务器的示例脚本:

USE [master];
GO

EXEC    master.dbo.sp_addlinkedserver 
        @server     = N'ADSI'
    ,   @srvproduct = N'ADSI'
    ,   @provider   = N'ADsDSOObject'
    ,   @datasrc    = N'adsdatasource'
    ,   @provstr    = N'ADSDSOObject';
GO

EXEC    master.dbo.sp_addlinkedsrvlogin 
        @rmtsrvname     = N'ADSI'
    ,   @useself        = N'False'
    ,   @locallogin     = NULL
    ,   @rmtuser        = N'<User account goes here...>'
    ,   @rmtpassword    = '<Password goes here...>';
GO

Use OpenQuery to query Active Directory: 使用OpenQuery查询Active Directory:

You can then use OpenQuery to query the Active Directory for user information. 然后,您可以使用OpenQuery向Active Directory查询用户信息。 Read the below link on MSDN for more information on how to formulate the query. 阅读以下有关MSDN的链接,以获取有关如何编制查询的更多信息。

Search Active Directory - Distributed Query 搜索Active Directory-分布式查询

Sample script to query Active Directory: 用于查询Active Directory的示例脚本:

SELECT  *
FROM    OPENQUERY
        (           ADSI
            ,   '   SELECT  *
                    FROM    ''LDAP://<OU path goes here...>''
                    WHERE   objectClass = ''user'''
        );

How to use this data in SSIS package: 如何在SSIS包中使用此数据:

You could set up this query as an SQL Server view and then call the view from OLE DB Source available on Data Flow Task within SSIS package and then redirect the output to an OLE DB Destination to populate the database tables. 您可以将此查询设置为SQL Server视图,然后从SSIS包中的“ 数据流任务”上的OLE DB源调用该视图,然后将输出重定向到OLE DB目标以填充数据库表。

Script Component (VB.NET) with System.DirectoryServices 具有System.DirectoryServices的脚本组件(VB.NET)

Here is a sample logic that import Active Directory users information from one domain into database table with the help of VB.NET in Script Component configured as Source . 这是一个示例逻辑,该逻辑在VB.NET的帮助下将配置为Source的 脚本组件中的 Active Directory用户信息从一个域导入数据库表中。 This sample was tested in SSIS 2012 but should work in SSIS 2008 and above. 该示例在SSIS 2012中进行了测试,但应在SSIS 2008及更高版本中工作。 This logic will not work in SSIS 2005 because the namespace System.DirectoryServices.AccountManagement was introduced only in .NET framework 3.5 and SSIS 2005 uses .NET Framework 2.0 此逻辑在SSIS 2005中不起作用,因为仅在.NET Framework 3.5中引入了名称空间System.DirectoryServices.AccountManagement ,而SSIS 2005使用.NET Framework 2.0

  • Create an SSIS package. 创建一个SSIS包。 This sample uses SSIS 2012. 本示例使用SSIS 2012。

  • Create an OLEDB Connection Manager that would connect to the SQL Server database. 创建将连接到SQL Server数据库的OLEDB Connection Manager If you created a data source, add the data source to the package's connection manager tab. 如果创建了数据源,则将数据源添加到程序包的“连接管理器”选项卡中。

  • Drag and drop a Data Flow Task onto the Control Flow tab. Data Flow Task拖放到“ 控制流”选项卡上。

  • Double-click the Data Flow Task to switch to the Data Flow tab. 双击“ Data Flow Task以切换到“ 数据流”选项卡。

  • Drag and drop a Script Component onto the Data Flow tab. Script Component拖放到“ 数据流”选项卡上。

  • Check Source on the Select Script Component Type dialog and click OK. 在“ 选择脚本组件类型”对话框中检查“ Source ”,然后单击“确定”。

  • Double-click the Script Component to open the Script Transformation Editor . 双击脚本组件以打开脚本转换编辑器 Click Inputs and Outputs tab page. 单击“ Inputs and Outputs页签。

  • Rename the Output to ActiveDirectory to give a meaningful name. 将输出重命名为ActiveDirectory以提供有意义的名称。

  • Select Output Columns and click Add Column to add each of the below mentioned columns. 选择输出列,然后单击添加列以添加下面提到的每个列。 This is only to illustrate this example. 这仅是为了说明该示例。 You might need to add columns of your preference. 您可能需要添加首选项列。

Column definition within script component 脚本组件中的列定义

Name              Data Type                Length
----------------- ------------------------ ------
FirstName         Unicode string [DT_WSTR]    255
LastName          Unicode string [DT_WSTR]    255
SAMAccountName    Unicode string [DT_WSTR]    255
UserPrincipalName Unicode string [DT_WSTR]    255
  • After defining the columns, click Script tab page 定义列后,单击“ Script选项卡页

  • Change the ScriptLanguage to Microsoft Visual Basic 2010 将ScriptLanguage更改为Microsoft Visual Basic 2010

  • On the Solution Explorer, right-click the Script Component project and click Add Reference... . 在解决方案资源管理器上,右键单击“脚本组件”项目,然后单击“ Add Reference... Add references to the following namespaces. 添加对以下名称空间的引用。

Namespaces to be referenced in the script component 脚本组件中要引用的命名空间

System.DirectoryServices
System.DirectoryServices.AccountManagement
  • Paste the below VB.NET code into the Script component. 将下面的VB.NET代码粘贴到脚本组件中。 Replace the section <Your domain name goes here> with your appropriate domain name. 用您的适当域名替换<Your domain name goes here>部分。 The code initializes PrincipalContext and PrincipalSearcher objects in PreExecute method and then disposes them in PostExecute method. 该代码在PreExecute方法中初始化PrincipalContextPrincipalSearcher对象,然后在PostExecute方法PreExecute它们处置。 CreateNewOutputRows method loops through each of the row found in AD to fetch the user attributes information. CreateNewOutputRows方法循环遍历AD中找到的每一行,以获取用户属性信息。

Script component code (VB.NET) 脚本组件代码(VB.NET)

#Region "Imports"
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices

#End Region

<Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute()> _
<CLSCompliant(False)> _
Public Class ScriptMain
    Inherits UserComponent

    Dim principalContext As PrincipalContext = Nothing
    Dim principalSearcher As PrincipalSearcher = Nothing

    Public Overrides Sub PreExecute()
        principalContext = New PrincipalContext(ContextType.Domain, "<Your domain name goes here>")
        principalSearcher = New PrincipalSearcher(New UserPrincipal(principalContext))
        MyBase.PreExecute()
    End Sub

    Public Overrides Sub PostExecute()
        principalContext = Nothing
        principalSearcher = Nothing
        MyBase.PostExecute()
    End Sub

    Public Overrides Sub CreateNewOutputRows()

        For Each principal As Principal In principalSearcher.FindAll()

            Dim entry As DirectoryEntry = TryCast(principal.GetUnderlyingObject(), DirectoryEntry)

            With ActiveDirectoryBuffer
                .AddRow()

                If entry.Properties("givenName").Value IsNot Nothing Then
                    .FirstName = entry.Properties("givenName").Value.ToString()
                Else
                    .FirstName = "Unknown"
                End If

                If entry.Properties("sn").Value IsNot Nothing Then
                    .LastName = entry.Properties("sn").Value.ToString()
                Else
                    .LastName = "Unknown"
                End If

                If entry.Properties("samAccountName").Value IsNot Nothing Then
                    .SAMAccountName = entry.Properties("samAccountName").Value.ToString()
                Else
                    .SAMAccountName = "Unknown"
                End If

                If entry.Properties("userPrincipalName").Value IsNot Nothing Then
                    .UserPrincipalName = entry.Properties("userPrincipalName").Value.ToString()
                Else
                    .UserPrincipalName = "Unknown"
                End If

            End With

        Next
    End Sub

End Class
  • Close the Script Transformation Editor. 关闭脚本转换编辑器。

  • Drag and drop an OLE DB Destination onto the Data Flow tab. 将OLE DB目标拖放到“数据流”选项卡上。 Connect the Script component to the OLE DB destination to redirect the source output. 将脚本组件连接到OLE DB目标,以重定向源输出。 Select the appropriate OLE DB Connection Manager and the table where the data should be inserted into. 选择适当的OLE DB连接管理器和应在其中插入数据的表。

Ways to improve this approach: 改进此方法的方法:

This sample provides loading information from only one domain. 此示例仅提供来自一个域的加载信息。 If you have multiple domains, you could stored them in a table. 如果您有多个域,则可以将它们存储在表中。 Fetch information of all the domain lists and use Foreach Loop Container available on the Control Flow to loop through each domain and get the users information using the above mentioned approach. 提取所有域列表的信息,并使用控制流上可用的Foreach Loop Container遍历每个域并使用上述方法获取用户信息。 May be there is also a better way to do this within VB.NET. 也许在VB.NET中还有更好的方法可以做到这一点。

Active Directory User Attributes Active Directory用户属性

You can find the complete list of Active Directory user attributes in the below MSDN link. 您可以在下面的MSDN链接中找到Active Directory用户属性的完整列表。 You need to click the links to find the LDAP-Display-Name. 您需要单击链接以找到LDAP显示名称。

All Attributes (Windows) 所有属性(Windows)

Here is another link that might help to get the user object attributes 这是另一个可能有助于获取用户对象属性的链接

User Object Attributes (Windows) 用户对象属性(Windows)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 asp.net 和 SQL 服务器更新 Active Directory 帐户信息 - Update Active Directory account information from asp.net and SQL server Active Directory链接到SQL Server - Active Directory Linked to SQL Server 如何使用户从Active Directory上次登录 - How to get users last logon from Active Directory 从SQL Server数据库表填充Combobox VB - Populate Combobox VB from SQL Server database table 有没有一种方法可以用SQL Server表中的列填充多个DataGridView - Is there a way to populate multiple DataGridViews with Columns from a SQL Server Table 如何从两个不同的SQL Server数据库表填充组合框 - How to populate a combobox from two different SQL Server database tables 如何从Active Directory中获取属于特定部门的所有用户的列表? - How can I get a list of all users that belong to a specific department from Active Directory? 有没有一种快速的方法可以将所有用户从Active Directory中拉出? - Is there a quick way to pull all of the users from Active Directory? 从剪贴板中的表自动填充活动浏览器窗口中字段的脚本 - Script to auto populate fields in active browser window from table in clipboard 在中断期间将SQL Server上的活动用户设置为非活动状态 - Setting active users on SQL Server to inactive during blackout
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM