Golang连接ldap获取sAMAccountName

什么是sAMAccountName,域账号在创建的时候会有全名(fullName)和sAMAccountName,前者更像是此账号的备注,真正使用的登录账号其实是sAMAccountName,那么怎么用go-ldap获取sAMAccountName,其实就是通过设置NewSearchRequest的FilterobjectCategory=Person,而后Attributes属性获取切片中的sAMAccountName字段即可,代码如下:

GetsAMAccountName.go

package main

import (
	"crypto/tls"
	"fmt"
	"github.com/go-ldap/ldap/v3"
	"gopkg.in/ini.v1"
	"log"
	"os"
)

var (
	filePath = "./config/config.ini"
	sAMAccountName []string = make([]string, 0)
)

func main() {
	cfg, err := ini.Load(filePath)
	if err != nil {
		fmt.Printf("Fail to read file: %v\n", err)
		os.Exit(1)
	}
	username := cfg.Section("AdServer").Key("Username").String()
	password := cfg.Section("AdServer").Key("Password").String()
	ldapUrl  := cfg.Section("AdServer").Key("LdapUrl").String()
	DN 		 := cfg.Section("OrganizationalUnit").Key("BaseDN").String()

	// tls 认证
	tlsConfig := &tls.Config{InsecureSkipVerify: true}
	l, err := ldap.DialTLS("tcp", ldapUrl, tlsConfig)
	if err != nil {
		log.Panic(err)
	}
	defer l.Close()

	// 用户 bind
	err = l.Bind(username, password)
	if err != nil {
		log.Fatal(err)
	}

	// Get All sAMAccountName
	filter := fmt.Sprintf("(&(objectCategory=Person))")
	searchRequest := ldap.NewSearchRequest(
		DN,
		ldap.ScopeWholeSubtree,
		ldap.NeverDerefAliases,
		0,
		0,
		false,
		filter,
		[]string{"sAMAccountName"}, // Attributes []string
		nil,
	)
	sr, _ := l.Search(searchRequest)
	
	// 遍历 sr.Entries 把sAMAccountName追加到[]sAMAccountName切片中
	for j := range sr.Entries {
		sAMAccountName = append(sAMAccountName, sr.Entries[j].Attributes[0].Values[0])
	}
	fmt.Println("sAMAccountName============>", sAMAccountName)
}

config.ini

[AdServer]
Username = rsq
Password = 123456
LdapUrl = 192.168.1.1:636

[OrganizationalUnit]
BaseDN = DC=rsq,DC=local

Attributes属性 还有很多,仅供参考:

	filter := fmt.Sprintf("(&(objectCategory=Person))")
	searchRequest := ldap.NewSearchRequest(
		DN,
		ldap.ScopeWholeSubtree,
		ldap.NeverDerefAliases,
		0,
		0,
		false,
		filter,
		[]string{}, // Attributes 置空,打印所有属性
		nil,
	)
	sr, _ := l.Search(searchRequest)
	sr.Print() 
// 输出如下
/*
DN:
objectClass:
cn:
sn:
givenName:
distinguishedName:
instanceType:
whenCreated:
whenChanged:
displayName:
uSNCreated:
uSNChanged:
name:
objectGUID:
userAccountControl: 
badPwdCount:
codePage: 
countryCode:
badPasswordTime: 
lastLogoff:
lastLogon:
pwdLastSet: 
primaryGroupID: 
objectSid:
accountExpires: 
logonCount: 
sAMAccountName: 
sAMAccountType: 
userPrincipalName: 
objectCategory: 
dSCorePropagationData: 
lastLogonTimestamp: 
*/

参考文章:
[1] ldap objectclass
[2] Golang EscapeFilter示例
[3] Active Directory LDAP Query by sAMAccountName and Domain

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RSQ博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值