sql 使用MS SQL链接服务器连接到Active Directory并使用OpenQuery进行查询

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 使用MS SQL链接服务器连接到Active Directory并使用OpenQuery进行查询相关的知识,希望对你有一定的参考价值。

--First thing we'll do is create our linked server, Active Directory Service Interface also known as ASDI, to Active Directory using the code below:
--Make sure you change the @rmtuser and @rmtpassword variables to a login and password that has access to your Active Directory.

USE [master]
GO 
EXEC master.dbo.sp_addlinkedserver @server = N'ADSI', @srvproduct=N'Active Directory Service Interfaces', @provider=N'ADSDSOObject', @datasrc=N'adsdatasource'
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'ADSI',@useself=N'False',@locallogin=NULL,@rmtuser=N'DOMAIN\USER',@rmtpassword='*********'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'collation compatible',  @optvalue=N'false'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'data access', @optvalue=N'true'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'dist', @optvalue=N'false'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'pub', @optvalue=N'false'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'rpc', @optvalue=N'false'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'rpc out', @optvalue=N'false'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'sub', @optvalue=N'false'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'connect timeout', @optvalue=N'0'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'collation name', @optvalue=null
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'lazy schema validation',  @optvalue=N'false'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'query timeout', @optvalue=N'0'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'use remote collation',  @optvalue=N'true'
GO 
EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'remote proc transaction promotion', @optvalue=N'true'
GO

--Configure the server to allow OPENQUERY functions if not done so yet
sp_configure 'show advanced options', 1 
reconfigure with override

sp_configure 'Ad Hoc Distributed Queries', 1 
reconfigure

-- simple query to retrieve users from OU in AD

SELECT * FROM OpenQuery
  ( 
  ADSI,  
  'SELECT streetaddress, pager, company, title, displayName, telephoneNumber, sAMAccountName, 
  mail, mobile, facsimileTelephoneNumber, department, physicalDeliveryOfficeName, givenname 
  FROM  ''LDAP://DOMAIN.com/OU=Players,DC=DOMAIN,DC=com''
  WHERE objectClass =  ''User'' 
  ') AS tblADSI
ORDER BY displayname

--second simple query
SELECT * FROM OpenQuery (
ADSI,
'SELECT  name
FROM ''LDAP://domain.coom/OU=SubOU4,OU=SubOU3,OU=SubOU2,OU=SubOU1,OU=TopOU,DC=doamain,DC=com''
WHERE objectCategory = ''person''
AND objectClass =''user''
');

-- Advanced Query to get all users assigned to group/container in AD
CREATE PROCEDURE [dbo].[sp_GetADGroupMembers]
    (
      @groupName VARCHAR(35),
      @OrganizationalUnit VARCHAR(35)
    )
AS 
    DECLARE @tsql VARCHAR(4000)

    SET @tsql = 'SELECT sn LastName,GivenName FirstName,sAMAccountName DomainAccount,
department, manager, pager as CorpNick
 FROM OPENQUERY(ADSI,'
        + '''SELECT sn,GivenName,sAMAccountName,department,manager,employeeID,pager 

 
FROM ''''LDAP://DC=domain,DC=com''''
WHERE objectCategory = ''''Person'''' AND objectClass = ''''user''''
AND memberOf=''''CN=' + @groupName + ',OU=Groups,OU=' + @OrganizationalUnit +',OU=Security&Services' +
        + ',DC=domain,DC=com'''' ''' + ')'

    EXEC(@tsql)

-- query to get all groups that user is member of
CREATE PROCEDURE dbo.Get_ADGroups_ForUser
(
    @Username NVARCHAR(256) 
)
AS
BEGIN

    DECLARE @Query NVARCHAR(1024), @Path NVARCHAR(1024)

    -- Find the fully qualified CN e.g: CN=Beau Holland,OU=Users,OU=Australia,OU=NSO,OU=Company,DC=Domain,DC=local
    -- replace "LDAP://DC=Domain,DC=local" with your own domain
    SET @Query = '
        SELECT @Path = distinguishedName
        FROM OPENQUERY(ADSI, ''
            SELECT distinguishedName 
            FROM ''''LDAP://DC=kantherm,DC=corp''''
            WHERE 
                objectClass = ''''user'''' AND
                sAMAccountName = ''''' + @Username + '''''
        '')
    '
    EXEC SP_EXECUTESQL @Query, N'@Path NVARCHAR(1024) OUTPUT', @Path = @Path OUTPUT 

    -- get all groups for a user
    -- replace "LDAP://DC=Domain,DC=local" with your own domain
    SET @Query = '
        SELECT cn,AdsPath
        FROM OPENQUERY (ADSI, ''<LDAP://DC=kantherm,DC=corp>;(&(objectClass=group)(member:1.2.840.113556.1.4.1941:=' + @Path +'));cn, adspath;subtree'')'

    EXEC SP_EXECUTESQL @Query  

END
GO

以上是关于sql 使用MS SQL链接服务器连接到Active Directory并使用OpenQuery进行查询的主要内容,如果未能解决你的问题,请参考以下文章

尝试连接到 SQL 表时,MS Access 2007 中的查询错误

无法使用 pymssql 烧瓶连接到 ms sql 服务器

使用 ODBC 连接到 MYSQL 在 MS-Access 中运行 SQL 时出错

如何在 T-SQL 查询中针对连接到 SAP-HANA 的链接服务器使用“占位符”?

sqlalchemy 无法连接到 ms sql server

使用 Java 从 Oracle 服务器连接到 MS SQL Server