82 lines
1.9 KiB
Go
82 lines
1.9 KiB
Go
|
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
|
||
|
ldifAddCmd.Flags().StringVarP(&flagLdifFilePath, "file_path", "f", "", "LDIF file to import")
|
||
|
}
|
||
|
|
||
|
// define ldif add subcommand
|
||
|
var ldifAddCmd = &cobra.Command{
|
||
|
Use: "add",
|
||
|
Short: "Import an LDIF file, add resources",
|
||
|
Long: `Add 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 add request
|
||
|
addRequest := ldap.NewAddRequest(entryDn)
|
||
|
|
||
|
// loop through and add the entry attributes
|
||
|
for _, entryAttr := range entry.Attributes {
|
||
|
addRequest.Attribute(entryAttr.Name, entryAttr.Values)
|
||
|
}
|
||
|
|
||
|
// let the user know what is currently being added
|
||
|
fmt.Printf("I am adding %s right now.\n", entryDn)
|
||
|
|
||
|
// perform the add operation
|
||
|
err = l.Add(addRequest)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
}
|
||
|
},
|
||
|
}
|