Python Forum

Full Version: How can i parse my output?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have this code script for ldap search.
I want to find user's group.

import ldap
 

username = "user1"
l = ldap.initialize("ldap://192.168.1.24")
try:
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)
 
    bind = l.simple_bind_s("[email protected]", "mypassword")
 
    base = "dc=my, dc=server"
    criteria = f"(sAMAccountName={username})"
    attributes = ['distinguishedName', 'company']
    result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes)
 
    results = [entry for dn, entry in result if isinstance(entry, dict)]
    print(results)
finally:
    l.unbind()
My output is:

[{'distinguishedName': [b'CN=User1,OU=DEVELOPER,OU=DEFAULT,OU=TURKIYE,OU=GLOBAL,DC=TRADONS,DC=local']}]
I will use OU's in this output. How can I get OU's one by one?
You could start by splitting
>>> x = b'CN=User1,OU=DEVELOPER,OU=DEFAULT,OU=TURKIYE,OU=GLOBAL,DC=TRADONS,DC=local'
>>> L = [t.split(b'=', 1) for t in x.split(b',')]
>>> L
[[b'CN', b'User1'], [b'OU', b'DEVELOPER'], [b'OU', b'DEFAULT'], [b'OU', b'TURKIYE'], [b'OU', b'GLOBAL'], [b'DC', b'TRADONS'], [b'DC', b'local']]
(Mar-16-2022, 09:03 AM)Gribouillis Wrote: [ -> ]You could start by splitting
>>> x = b'CN=User1,OU=DEVELOPER,OU=DEFAULT,OU=TURKIYE,OU=GLOBAL,DC=TRADONS,DC=local'
>>> L = [t.split(b'=', 1) for t in x.split(b',')]
>>> L
[[b'CN', b'User1'], [b'OU', b'DEVELOPER'], [b'OU', b'DEFAULT'], [b'OU', b'TURKIYE'], [b'OU', b'GLOBAL'], [b'DC', b'TRADONS'], [b'DC', b'local']]

I split it. Now i have

CN=User1,OU=DEVELOPER,OU=DEFAULT, OU=TURKIYE,OU=GLOBAL,DC=TRD,DC=local
I have no idea, how should i get ou's and save it to database
ilknurg Wrote:I split it. Now i have
I don't understand. What code do you have now?
(Mar-16-2022, 02:39 PM)ilknurg Wrote: [ -> ]I have no idea, how should i get ou's and save it to database
Have you make it into one string?
To get it database i would use a dictionary(as it almost there) or could serialize(search if you unsure what this mean) it in and back.
Using L from Grib example.
>>> record = dict(L)
>>> record
{b'CN': b'User1', b'DC': b'local', b'OU': b'GLOBAL'}
Into a database example and back to original record.
>>> import sqlite3
>>>
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute("create table Test (key text, value text);")
<sqlite3.Cursor object at 0x000002E0047AE1C0>

>>> record = {b'CN': b'User1', b'DC': b'local', b'OU': b'GLOBAL'}
# Insert the dictionary 
>>> c.executemany("insert into Test values (?,?);", record.items())
<sqlite3.Cursor object at 0x000002E0047AE1C0>

# Get all
>>> rec = c.execute("select * from Test;").fetchall()
[(b'CN', b'User1'), (b'DC', b'local'), (b'OU', b'GLOBAL')]

# Back to start
>>> record = dict(rec)
>>> record
{b'CN': b'User1', b'DC': b'local', b'OU': b'GLOBAL'}