golang ldap 学习
就是一个简单的关于ldap的学习,ldap server 使用了openldap,基于docker 运行
环境准备
- docker-compose 文件
version: "3"
services:
ldap:
image: osixia/openldap:latest
environment:
- "LDAP_ORGANISATION=dalongrong"
- "LDAP_DOMAIN="
- "LDAP_ADMIN_PASSWORD=12sROjpn*^"
ports:
- 389:389
- 636:636
- go mod
module myldapapp
go 1.14
require (
/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
/alecthomas/units v0.0.0-20190924025748-f65c72e2690d // indirect
/go-ldap/ldap/v3 v3.2.3 // indirect
gopkg.in/alecthomas/kingpin.v2 v2.2.6
)
- main.go
package main
import (
"fmt"
"log"
"gopkg.in/alecthomas/kingpin.v2"
"/go-ldap/ldap/v3"
)
var (
ldapaddr = kingpin.Flag("addr", "ldap addr").Default("127.0.0.1").String()
ldapport = kingpin.Flag("port", "ldap connect port").Default("389").Int()
ldapusername = kingpin.Flag("username", "ldap connect usernmae").Default("cn=admin,dc=rongfengliang,dc=com").String()
ldapuserpassword = kingpin.Flag("password", "ldap connect password").Default("12sROjpn*^").String()
debug = kingpin.Flag("debug", "run with debug").Default("false").Bool()
)
func main() {
kingpin.Parse()
fmt.Printf("%v, %d\n", *ldapaddr, *ldapport)
con, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", *ldapaddr, *ldapport))
if err != nil {
log.Fatal("connect err:", err)
}
defer con.Close()
con.Debug.Enable(*debug)
err = con.Bind(*ldapusername, *ldapuserpassword)
if err != nil {
log.Fatal("bind err:", err)
}
searchRequest := ldap.NewSearchRequest(
"dc=rongfengliang,dc=com",
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
"(objectClass=*)",
[]string{"dn", "cn", "objectClass"},
nil,
)
searchResult, err := con.Search(searchRequest)
if err != nil {
log.Println("can't search ", err.Error())
}
log.Printf("%d", len(searchResult.Entries))
for _, item := range searchResult.Entries {
item.PrettyPrint(4)
}
}
- 代码说明
配置部分基于kingpin,对于ldap 的使用,首先需要connect。然后需要bind(安全),之后就是一些功能操作了(查询,更新,删除。。) - 运行效果
ldap 数据:
cli 参数:
运行效果: