How do I run a ldap query using R?

rstudio server ldap authentication
rstudio connect authentication
shiny ldap

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 the members of a group" and then use R to make a frequency analysis, but I can not find any examples on how to connect and run a LDAP query using R.

RCurl seems to have some kind of support ( http://cran.r-project.org/web/packages/RCurl/index.html ):

Additionally, the underlying implementation is robust and extensive, supporting FTP/FTPS/TFTP (uploads and downloads), SSL/HTTPS, telnet, dict, ldap, and also supports cookies, redirects, authentication, etc.

But I am no expert in R and have not been able to find a single example using RCurl (or any other R library) to do this..

Right now I am using CURL like this to obtain the members of a group:

curl "ldap://ldap.replaceme.com/o=replaceme.com?memberuid?sub?(cn=group-name)"

Anyone here knows how to do the same in R with RCurl?

Found the answer myself:

First run this commands to make sure RCurl is installed (as described in http://www.programmingr.com/content/webscraping-using-readlines-and-rcurl/ ):

install.packages("RCurl", dependencies = TRUE)
library("RCurl")

And then user getURL with an ldap URL (as described in http://www.ietf.org/rfc/rfc2255.txt although I couldn't understand it until I read http://docs.oracle.com/cd/E19396-01/817-7616/ldurl.html and saw ldap[s]://hostname:port/base_dn?attributes?scope?filter):

getURL("ldap://ldap.replaceme.com/o=replaceme.com?memberuid?sub?(cn=group-name)")

Analyze LDAP Objects in R, This article shows how to use the driver to execute SQL queries to LDAP objects and visualize LDAP objects in R. Install R. You can complement the driver's  Let’s try to execute this query using the ADUC console. Open the ADUC console and go to the Saved Queries section; Create a new query: New > Query; Specify the name of the request and click the Define Query button; Select the Custom Search type, go to the Advanced tab and copy your LDAP query code into the Enter LDAP query field;

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)
}

LDAP and Active Directory authentication in RStudio Connect , RStudio Connect can integrate with your company's LDAP or Active LDAP and Active Directory support in RStudio Connect has the following constraints: If you do not specify these attributes, some functionality of RStudio  To use SQL, open an R Notebook in the RStudio IDE under the File > New File menu. Start a new code chunk with {sql}, and specify your connection with the connection=con code chunk option. If you want to send the query output to an R dataframe, use output.var = "mydataframe" in the code chunk options.

I followed this strategy:

  1. run a Perl script with an LDAP query, write data to disc as JSON.
  2. read in the json structure with R, create a dataframe.

For step (1), I used this script:

#use Modern::Perl;
use strict;
use warnings;
use feature 'say';
use Net::LDAP;
use JSON;
chdir("~/git/_my/R_one-offs/R_grabbag");
my $ldap = Net::LDAP->new( 'ldap.mydomain.de' ) or die "$@";
my $outfile = "ldapentries_mydomain_ldap.json";
my $mesg = $ldap->bind ;    # an anonymous bind
# get all cn's (= all names)
$mesg = $ldap->search(
                base   => " ou=People,dc=mydomain,dc=de",
                filter => "(cn=*)"
              );

my $json_text = "";
my @entries;

foreach my $entry ($mesg->entries){
 my %entry;
 foreach my $attr ($entry->attributes) {
    foreach my $value ($entry->get_value($attr)) {
      $entry{$attr} = $value;
    }
  }
  push @entries, \%entry;
}

$json_text = to_json(\@entries);
say "Length json_text: " . length($json_text);


open(my $FH, ">", $outfile);
print $FH $json_text;
close($FH);
$mesg = $ldap->unbind;

You might need check the a max size limit of entries returned by the ldap server. See https://serverfault.com/questions/328671/paging-using-ldapsearch

For step (2), I used this R code:

setwd("~/git/_my/R_one-offs/R_grabbag")
library(rjson)
# read into R list, from file, created from perl script
json <- rjson::fromJSON(file="ldapentries_mydomain_ldap.json",method = "C")
head(json)

# create a data frame from list
library(reshape2)
library(dplyr)
library(tidyr)

# not really efficient, maybe thre's a better way to do it
df.ldap <- json %>% melt %>% spread( L2,value)

# optional:
# turn factors into characters
i <- sapply(df.ldap, is.factor)
df.ldap[i] <- lapply(df.ldap[i], as.character)

Configuring Shiny Server Pro with LDAP or Active Directory , If you do not define group_filter , Shiny Server by default uses uniqueMember={​username} as the filter, and searches in ou=Groups , as the  Everywhere I find solutions for how a LDAP Query has to look like in Windows CMD. It is not a problem for me to adjust such a query to my needs, but none of the common help pages tells you how to make the ldap commands work. Everytime I am trying to execute a ldap command, comandline only response that the command is not known.

I wrote a R library for accessing ldap servers using the openldap library. In detail, the function searchldap is a wrapper for the openldap method searchldap. https://github.com/LukasK13/ldapr

parseLDAP: Parse LDAP output into dataframe in stackoverflow , References. https://stackoverflow.com/questions/22793855/how-do-i-run-a-ldap-​query-using-r · stackoverflow documentation built on Jan. 10, 2020, 9:07 a.m.  In Query root box, you can specify the container (OU), in which the query is run. By default, the search by the query criteria is performed in the whole AD domain. In our example, we’ll narrow the search scope by selecting Brasil container. Then click Define Query, and select Custom Search on Find drop down.

[R] Using LDAP search filter to query attributes without value, [R] Using LDAP search filter to query attributes without value wanted to perform a query with additional conditions based on some attribute of  Based on this output, the user account that you used to run the LDAP query has the AAM feature enabled. When you run the LDAP query, you use a filtered access token instead of a full access token. Even if full control permission for the Administrators group is granted to the user object, you still do not have full control permission. Therefore, you obtain only a partial attribute list.

Create an LDAP query, You can create an LDAP query using the tools in PureCloud's self-service interface, or you can make LDIFDE is a free tool provided by Microsoft for running on their servers. ldifde -r "LDAP query" -f ExportUser.ldf -d "dc=Export,​dc=com". With PortQry, you can also query an LDAP service. It sends an LDAP query, using either UDP or TCP, and interprets the LDAP server's response to the query. It sends an LDAP query, using either UDP or TCP, and interprets the LDAP server's response to the query.

Microsoft SharePoint: Building Office 2007 Solutions in VB 2005, 10, Select Start X- Run. 11. Exclude disabled accounts from the LDAP query typingldifde-fc:\users.txt-r “(&(objectCategory=Person)(objectClass=User)  These are some LDAP Query Advanced Examples LDAP Query Examples for AD # Some examples that are specific or often used with Microsoft's Active Directory. Retrieving the LDAP Schema # How to find and retrieve the LDAP schema from a LDAP server. Search Filters for Bit Fields # By using LDAP filters it's also possible to find objects for which a specific bit either is or is not set within a bit field.

Comments
  • We'd need to know a bit more about the LDAP server config. An example LDAP query via curl -u USERNAME 'ldap://192.168.0.66/CN=Users,DC=training,DC=local\?sAMAccountName?sub?(ObjectClass=*)' (that's from an IBM example). It won't work for you since you need to know the proper search parameters. It's pretty straightforward to run that via RCurl and then process the results, but if you should get the query working from curl on the command line first.
  • Right now I am retrieving the list of members of a group like this: ldapsearch -t -h ldap.replaceme.com -x -b "o=replaceme.com" "(cn=group-name)" memberuid
  • @hrbrmstr if you can translate my ldapsearch to curl and then to R with RCurl, that would be the exact answer I am looking for...
  • Hi @hrbrmstr I have translated my ldapsearch query to curl... Can you tell me how do I run it with RCurl?
  • Already did it my self... but thanks a lot for your guidance @hrbrmstr :-)
  • On a related note this is an excellent guide on the usage of RCurl omegahat.org/RCurl/RCurlJSS.pdf