0

I have a code below which is just fetching the data from the ldapsearch command, now i am thinking about to use pandas to get data into a desired format but i am not getting how i can access the python function data into Pandas DataFrame.

Code :

import subprocess

def UserID():
    LDP = "ldapsearch -h ldap.example.com -xLLLb 'ou=Personal,ou=People,ou=udalt' uid fullName"
    proc = subprocess.Popen(LDP, shell=True, stdout=subprocess.PIPE)
    info_str = proc.stdout.read().decode('utf8')
    str_info = info_str.splitlines()
    prefixes = ["uid:", "fullName:"]
    for line in str_info:
        if line.startswith(tuple(prefixes)):
            lines = line
            for line in lines.splitlines():
                     print(line, end=' ' if line.startswith("uid:")  else "\n")
UserID()

Result:

uid: khati06610 fullName: Anik sa
uid: khati06648 fullName: Vikur Doom
uid: khati06663 fullName: Gopi sa
uid: khati06718 fullName: Jeff kana
uid: khati10131 fullName: Peter j
uid: khati10152 fullName: Mie sean

Desired Data From pandas Processing will be :

User ID        User Name
khati06610    Anik sa 
khati06648    Vikur Doom
khati06663    Gopi sa 
khati06718    Jeff kana
khati10131    Peter j 
khati10152    Mie sean
5
  • can you modify UserID func? Commented Jul 24, 2020 at 12:59
  • @Roim, I am okay to modify if you have any suggestion pls. Commented Jul 24, 2020 at 13:01
  • Maybe I'm naive, but why not parse the full string into two lists? one list to hold userid and second username. If you can do that, building dataframe from two list is easy. Can you parse each line to retrieve userId and username? like splitting on 'uid' and 'fullName' Commented Jul 24, 2020 at 13:09
  • @SaiSreenivas , its always alphabets and numbers indeed yes. Commented Jul 24, 2020 at 13:10
  • @Roim, appreciate your comment , yes that's another choice but just looking a way with pandas. Commented Jul 24, 2020 at 13:13

1 Answer 1

2

try this, but the preferable way would be to use python-ldap which provides an object-oriented API to access LDAP & avoid's the overhead of string parsing.

import re
import pandas as pd

search_ = re.compile("uid:\s(.*)\sfullName:\s(.*)")

print(
    pd.DataFrame(
        [{"User ID": u, "User Name": n} for u, n in search_.findall(line)]
    )
)

      User ID   User Name
0  khati06610     Anik sa
1  khati06648  Vikur Doom
2  khati06663     Gopi sa
3  khati06718   Jeff kana
4  khati10131     Peter j
5  khati10152    Mie sean
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.