muldap/cmd/search.go
2018-07-14 19:48:24 -04:00

68 lines
1.7 KiB
Go

package cmd
import (
"fmt"
"log"
"strings"
"github.com/spf13/cobra"
ldap "gopkg.in/ldap.v2"
)
var (
flagAttrs string
flagBase string
flagFilter string
flagIndent int
)
func init() {
// define search command flags
searchCmd.Flags().StringVarP(&flagAttrs, "attributes", "a", "", "Comma-separated list of LDAP attributes to retrieve in the search")
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 slice of attributes
var attrs []string = nil
if flagAttrs != "" {
attrs = strings.Split(flagAttrs, ",")
}
// create new LDAP connection
l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", flagHost, flagPort))
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
attrs, // 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)
},
}