package cmd import ( "fmt" "log" "strings" "github.com/spf13/cobra" "github.com/spf13/viper" ldap "gopkg.in/ldap.v2" ) var ( flagAttrs string flagFilter string ) func init() { // define search command flags searchCmd.Flags().StringP("base", "b", "dc=example,dc=com", "LDAP search base DN") searchCmd.Flags().IntP("indent", "i", 2, "Number of spaces to use while indenting search output") searchCmd.Flags().StringVarP(&flagAttrs, "attributes", "a", "", "Comma-separated list of LDAP attributes to retrieve in the search") searchCmd.Flags().StringVarP(&flagFilter, "filter", "f", "objectClass=*", "LDAP search filter") // bind config file values to flags viper.BindPFlag("search_base", searchCmd.Flags().Lookup("base")) viper.BindPFlag("print_indent", searchCmd.Flags().Lookup("indent")) // 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", viper.GetString("host"), viper.GetInt("port"))) if err != nil { log.Fatal(err) } defer l.Close() // create a new LDAP search request searchRequest := ldap.NewSearchRequest( viper.GetString("search_base"), // 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(viper.GetInt("print_indent")) }, }