package ldif import ( "fmt" "io/ioutil" "log" "github.com/spf13/cobra" "github.com/spf13/viper" ldif "github.com/vetinari/ldif" ldap "gopkg.in/ldap.v2" ) func init() { // define ldif command flags ldifDeleteCmd.Flags().StringVarP(&flagLdifFilePath, "file_path", "f", "", "LDIF file to import") } // define ldif subcommand var ldifDeleteCmd = &cobra.Command{ Use: "delete", Short: "Import an LDIF file, delete resources", Long: `Delete LDAP resources using an LDIF file.`, Run: func(cmd *cobra.Command, args []string) { // 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() // bind as the admin user err = l.Bind(viper.GetString("bind_dn"), viper.GetString("bind_pw")) if err != nil { log.Fatal(err) } // read LDIF file to bytes ldifBytes, err := ioutil.ReadFile(flagLdifFilePath) if err != nil { log.Fatal(err) } // convert bytes to string ldifText := string(ldifBytes) // parse ldif text ldifParse, err := ldif.Parse(ldifText) if err != nil { log.Fatal(err) } // let the user know how many entries we found in the LDIF fmt.Printf("I found %d entries in the LDIF file.\n", len(ldifParse.Entries)) // loop through each entry for _, entryWrap := range ldifParse.Entries { // grab the entry entry := entryWrap.Entry // grab the entry DN entryDn := entry.DN // create a new LDAP delete request deleteRequest := ldap.NewDelRequest(entryDn, []ldap.Control{}) // let the user know what is currently being deleted fmt.Printf("I am deleting %s right now.\n", entryDn) // perform the delete operation err = l.Del(deleteRequest) if err != nil { log.Fatal(err) } } }, }