Created
July 5, 2014 00:21
-
-
Save troyjr/3ea9b3856efe724b175c to your computer and use it in GitHub Desktop.
R LDAP - parse ldap output from RCurl to dataframe ala Apache Directory studio export to csv.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
parseldap("ldap://ldap.replaceme.com/o=replaceme.com?memberuid?sub?(cn=group-name)", "username:password") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment