Q:

How to export a full list of users in Samba Active Directory?

I have an Active Directory running on Samba 4.6.3, on a server with Debian Jessie. On a Windows 7 PC (AD client) I installed the RSAT and from there I manage the server using an administrator account, but now I need to export the full list of users in a readable format, preferably .csv
Using the RSAT (from the client in Windows) until now I have only managed to export all the objects within an OU (organizational unit), ONE OU AT A TIME, either the OU a user container or a PC container, that is, I could do what I want (export the full list of users) by repeating the process for each OU user container but I have many OU user containers.
Question: Is there any way to export the complete list of users, with name and surname, with its corresponding OU in a quick way and without having to do this iterative work?
PD: The answer does not have to be limited to the client in Windows with the RSAT, it can also be in the Samba server

A:

Bash solution..  parts...
Start with extracting the AD contents: 
ldapsearch -s -h <ADHOST> -P <ADPORT> -D <USERDN WITH RIGHTS TO READ AD> -W -E pr-1000/noprompt -b <BASEDN FOR SEARCH> > ad_extract_tmp.ldif

The "-W" forces an interactive prompting for the user password.  You don't want that in command history.  If you are combining this into a script, then you can use the "-w" and protect the password access.
Now that the content has been extracted into a text file, we can use text processing to convert to CSV or any other format we want.
ldif files are wrapped, so the first step would be to unwrap it
awk ' BEGIN (RS="\n\n"; FS="\n "} {for (i=1,i<=NF;i++) printf $i; printf "\n\n"}' ad_extract_tmp.ldif > ad_extract_tmp.ldif.unwrapped

Here we redefine the record to consist of a block of text with two line endings and a field to consist of a block of text with only one line ending and a space. Next we process each line as a field, joining the likes that are ldif wrapped ("\n ") into a single fields.  Now that we have an unwrapped ldif, the final step is to convert from ldif to csv.  
awk ' Begin {
             record = "false";
             print "\x22uid\x22,\x22dn\x22";
  }
  { if ( record = "true") {

       if ( $0 ~ /~sAMAccountName./) {
         uid = $0;
         sub (/^.*: /,"",uid);
        }

       if ( $0 ~ /^\s*$/) {
           print "\x22" uid "\x22,\x22" dn "\x22";
           dn = "";  record = "false";
         }
      }
  }
  {
    if ($0 ~ /^dn:./) {
       record = "true";
       dn = $0;
     }
  }' ad_extract_tmp.ldif.unwrapped > ad_extract.csv

This is a significantly simplified awk conversion script that will convert the unwrapped ldif to csv. 
It's possible to extract the dn to the users ou and to go after the additional fields that are needed.  Just extend the final awk script.

