How do I run a ldap query using R?

后端 未结 4 1288
既然无缘
既然无缘 2021-02-06 12:30

I want to make a query against a LDAP directory of how employees are distributed in departments and groups...

Something like: \"Give me the department name of all th

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-06 12:41

    I've written a function here to parse ldap output into a dataframe, and I used the examples provided as a reference for getting everything going.

    I hope it helps someone!

    library(RCurl)
    library(gtools)
    
    parseldap<-function(url, userpwd=NULL)
    {
      ldapraw<-getURL(url, userpwd=userpwd)
      # seperate by two new lines
      ldapraw<-gsub("(DN: .*?)\n", "\\1\n\n", ldapraw)
      ldapsplit<-strsplit(ldapraw, "\n\n")
      ldapsplit<-unlist(ldapsplit)
      # init list and count
      mylist<-list()
      count<-0
      for (ldapline in ldapsplit) {
        # if this is the beginning of the entry
        if(grepl("^DN:", ldapline)) {
          count<-count+1
          # after the first 
          if(count == 2 ) {
            df<-data.frame(mylist)
            mylist<-list()
          }
          if(count > 2) {
            df<-smartbind(df, mylist)
            mylist<-list()
          }
          mylist["DN"] <-gsub("^DN: ", "", ldapline)
        } else {
          linesplit<-unlist(strsplit(ldapline, "\n"))
          if(length(linesplit) > 1) {
            for(line in linesplit) {
              linesplit2<-unlist(strsplit(line, "\t"))
              linesplit2<-unlist(strsplit(linesplit2[2], ": "))
              if(!is.null(unlist(mylist[linesplit2[1]]))) {
                x<-strsplit(unlist(mylist[linesplit2[1]]), "|", fixed=TRUE)
    
                x<-append(unlist(x), linesplit2[2])
                x<-paste(x, sep="", collapse="|")
                mylist[linesplit2[1]] <- x
              } else {
                mylist[linesplit2[1]] <- linesplit2[2]  
              }
            }
          } else {
            ldaplinesplit<-unlist(strsplit(ldapline, "\t"))
            ldaplinesplit<-unlist(strsplit(ldaplinesplit[2], ": "))
            mylist[ldaplinesplit[1]] <- ldaplinesplit[2]
          }
    
        }
    
      }
      if(count == 1 ) {
        df<-data.frame(mylist)
      } else {
        df<-smartbind(df, mylist)
      }
      return(df)
    }
    

提交回复
热议问题