Added an LDAP search command with some basic searching options
This commit is contained in:
@ -12,7 +12,7 @@ var rootCmd = &cobra.Command{
|
||||
Short: "muldap is Metaunix.net's LDAP management tool",
|
||||
Long: "LDAP management tool for Metaunix.net user and group resources.",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Metaunix.net LDAP tool - available commands are: version")
|
||||
fmt.Println("Metaunix.net LDAP tool - available commands are: search, version")
|
||||
},
|
||||
}
|
||||
|
||||
|
58
cmd/search.go
Normal file
58
cmd/search.go
Normal file
@ -0,0 +1,58 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
ldap "gopkg.in/ldap.v2"
|
||||
)
|
||||
|
||||
var (
|
||||
flagBase string
|
||||
flagFilter string
|
||||
flagIndent int
|
||||
)
|
||||
|
||||
func init() {
|
||||
// define search command flags
|
||||
searchCmd.Flags().StringVarP(&flagBase, "base", "b", "dc=example,dc=com", "LDAP search base DN")
|
||||
searchCmd.Flags().StringVarP(&flagFilter, "filter", "f", "objectClass=*", "LDAP search filter")
|
||||
searchCmd.Flags().IntVarP(&flagIndent, "indent", "i", 0, "Number of spaces to use while indenting search output")
|
||||
|
||||
// register search command
|
||||
rootCmd.AddCommand(searchCmd)
|
||||
}
|
||||
|
||||
// define search command
|
||||
var searchCmd = &cobra.Command{
|
||||
Use: "search",
|
||||
Short: "Search an LDAP directory",
|
||||
Long: `Perform an LDAP search operation on an LDAP directory`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// create new LDAP connection
|
||||
l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "ldap.example.com", 389))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
|
||||
// create a new LDAP search request
|
||||
searchRequest := ldap.NewSearchRequest(
|
||||
flagBase, // The base dn to search
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
fmt.Sprintf("(%s)", flagFilter), // The filter to apply
|
||||
nil, // A list attributes to retrieve
|
||||
nil,
|
||||
)
|
||||
|
||||
// perform the LDAP search
|
||||
sr, err := l.Search(searchRequest)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// print the results
|
||||
sr.PrettyPrint(flagIndent)
|
||||
},
|
||||
}
|
Reference in New Issue
Block a user