check if an active directory group exists in go

To check if an Active Directory group exists using Go, you'll need to use the ldap package to communicate with the Active Directory through LDAP protocol.

Here is an example code that checks if a group exists:

main.go
package main

import (
	"fmt"
	"gopkg.in/ldap.v3"
)

func main() {
	// Specify the LDAP server details
	server := "ldap://yourserver.domain.com"
	bindDN := "adminuser@domain.com"
	bindPassword := "password"

	// Connect to the LDAP server
	l, err := ldap.DialURL(server)
	if err != nil {
		fmt.Println("Error connecting to LDAP server:", err.Error())
		return
	}
	defer l.Close()

	// Bind to the LDAP server with the admin user account
	err = l.Bind(bindDN, bindPassword)
	if err != nil {
		fmt.Println("Error binding to LDAP server:", err.Error())
		return
	}

	// Search for the group using the group name
	searchRequest := ldap.NewSearchRequest(
		"DC=domain,DC=com", // BaseDn
		ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
		fmt.Sprintf("(cn=%s)", "groupName"), // Filter
		[]string{"dn"}, // Attributes to retrieve
		nil,
	)

	searchResult, err := l.Search(searchRequest)
	if err != nil {
		fmt.Println("Error searching for group:", err.Error())
		return
	}

	// Check if the search result contains any entries
	if len(searchResult.Entries) == 0 {
		fmt.Println("Group not found")
		return
	}

	// Group found
	fmt.Println("Group exists")
}
1164 chars
53 lines

Make sure to replace the server, bindDN, bindPassword and groupName with your own values.

gistlibby LogSnag