Get additional data to LDAP with python (Writer and Reader)

Introduction

Last time has added and retrieved LDAP. This time, I will summarize how to add and get using Writer and Reader.

environment

LDAP operation

Reading LDAP using Reader

ldap3 has a Reader class with various functions. Use it to get LDAP information. Reader requires a connection, an object, and a cn (search path). The examples are basically listed in order from the top.

Object creation

The object is created by passing the target object name and connection to the ObjectDef class. This time, we want to take the value of cn, so specify inetOrgPerson. When you want to get ou, specify the target you want to get, such as organizationalUnit.

main.py



from ldap3 import Server, Connection, ObjectDef, Reader

server = Server('localhost')
conn = Connection(server, 'cn=admin,dc=sample-ldap',  password='LdapPass')
result = conn.bind()

#inetOrgPerson object creation
obj_cn_name = ObjectDef('inetOrgPerson', conn)

Reader generation

Create a Reader by giving the object, connection, and search path created earlier. The search path given at this time allows you to specify from which hierarchy information can be obtained. Here, the value is not entered because it is not searched only by generating Reader.

main.py



#Leader generation
data_reader = Reader(conn, obj_cn_name, 'ou=sample-unit,dc=sample-component,dc=sample-ldap')

Get LDAP values

Get a list of LDAP values

You can get a list of LDAP values by using the reader `search ()`.

main.py



#Search here
data = data_reader.search()

#All items can be taken
print(data)

result


[DN: cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap - STATUS: Read - READ TIME: 2020-03-27T20:50:15.470086
    cn: sample-name
    objectClass: inetOrgPerson
    sn: sample1
        sample2
    st: test2
, DN: cn=sample-name1,ou=sample-unit,dc=sample-component,dc=sample-ldap - STATUS: Read - READ TIME: 2020-03-27T20:50:15.478084
    cn: sample-name1
    objectClass: inetOrgPerson
    sn: sample
]

Looking at the result, you can see that all the cn under ou = sample-unit, dc = sample-component, dc = sample-ldap specified in Reader have been acquired. Furthermore, the respective attribute values sn and st have been acquired.

Acquisition of search data by attribute

sample-You should be able to get the name.



#### **`  main.py`**
```py


#Specify search conditions
data = data_reader.search('st')
print(data)

result


DN: cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap - STATUS: Read - READ TIME: 2020-03-27T20:50:15.470086
    cn: sample-name
    objectClass: inetOrgPerson
    sn: sample1
        sample2
    st: test2

Looking at the result, I got the cn of sample-name as expected.

Get in json format

There is a function that can be obtained by converting the LDAP value to a json format string by using the reader ```entry_to_json () `` `.

main.py



#Can be obtained in json format
json_str = data[0].entry_to_json()
print(json_str)
print(type(json_str))

result


{
    "attributes": {
        "st": [
            "test2"
        ]
    },
    "dn": "cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap"
}
<class 'str'>

Get in Dict format

There is a function that can convert the LDAP value to Dict format and get it by using the reader entry_attributes_as_dict.

main.py



ldap_dict = data[0].entry_attributes_as_dict

print(ldap_dict)
print(type(ldap_dict))

result


{'st': ['test2']}
<class 'dict'>

Get one cn with cn as the path

By specifying cn, you can get information for only that one cn.

main.py



#If you use cn as a path, you can get only one
data_reader = Reader(conn, obj_cn_name, 'cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap')
data = data_reader.search()
print(data)

result


[DN: cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap - STATUS: Read - READ TIME: 2020-03-27T21:16:17.284094
    cn: sample-name
    objectClass: inetOrgPerson
    sn: sample1
        sample2
    st: test2
]

Writing LDAP using Writer

You can write LDAP information to ldap3 using the Writer class, which has various functions. Writer can be generated using Reader.

Writer generation / writing

Generate a Writer by giving a Reader that gets the LDAP value to the Writer's `from_cursor ()` `. Write the value by putting a value in the variable of the generated Writer and doing commit () ``.

main.py



from ldap3 import Server, Connection, ObjectDef, Reader, Writer

server = Server('localhost')

conn = Connection(server, 'cn=admin,dc=sample-ldap',  password='LdapPass')
result = conn.bind()

#Get using reader
obj_cn_name = ObjectDef('inetOrgPerson', conn)
data_reader = Reader(conn, obj_cn_name, 'cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap')

data = data_reader.search()

#Display before updating
print(data[0])

#Let the writer read
data_writer = Writer.from_cursor(data_reader)

#Enter the value via writer
data_writer[0].sn = 'sample10'
data_writer[0].sn += 'sample20'
data_writer[0].st = 'test10'

#Reflection of change results
data_writer.commit()

#Display after update
data_reader2 = Reader(conn, obj_cn_name, 'cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap')
data2 = data_reader2.search()
print(data2[0])

result


DN: cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap - STATUS: Read - READ TIME: 2020-03-27T21:36:03.493031
    cn: sample-name
    objectClass: inetOrgPerson
    sn: sample1
        sample2
    st: test1

DN: cn=sample-name,ou=sample-unit,dc=sample-component,dc=sample-ldap - STATUS: Read - READ TIME: 2020-03-27T21:36:03.686030
    cn: sample-name
    objectClass: inetOrgPerson
    sn: sample10
        sample20
    st: test10

You can see that the values have changed as specified.

in conclusion

We have summarized the acquisition / modification / addition of LDAP using LDAP Reader and Writer. I feel that using Reader and Writer has made LDAP a little easier to handle. This has made it practical to use LDAP instead of RDB. This time, I wrote the source in a solid manner without considering the structure to make it as simple as possible, but I think that the source will become more convenient if I devise a little more.

Recommended Posts

Get additional data to LDAP with python (Writer and Reader)
Get additional data in LDAP with python
I tried to get CloudWatch data with Python
Link to get started with python
[Python] Get economic data with DataReader
Get rid of dirty data with Python and regular expressions
How to get started with Python
[Introduction to Python] How to get data with the listdir function
[Python / Ruby] Understanding with code How to get data from online and write it to CSV
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
Try to get CloudWatch metrics with re: dash python data source
Data pipeline construction with Python and Luigi
[Note] Get data from PostgreSQL with Python
Convert Excel data to JSON with python
Fractal to make and play with Python
Convert FX 1-minute data to 5-minute data with Python
Compress python data and write to sqlite
How to get the date and time difference in seconds with python
Scraping tabelog with python and outputting to CSV
MessagePack-Try to link Java and Python with RPC
Get stock price data with Quandl API [Python]
I tried to get and analyze the statistical data of the new corona with Python: Data of Johns Hopkins University
Write CSV data to AWS-S3 with AWS-Lambda + Python
Get Gmail subject and body with Python and Gmail API
A layman wants to get started with Python
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
Python script to get note information with REAPER
For those who want to learn Excel VBA and get started with Python
[Introduction to Python] How to get the index of data with a for statement
Data analysis with python 2
Get date with python
Data analysis with Python
[First API] Try to get Qiita articles with Python
Get media timeline images and videos with Python + Tweepy
How to scrape image data from flickr with python
I want to handle optimization with python and cplex
I tried to get started with blender python script_Part 01
Get financial data with python (then a little tinkering)
Try to operate DB with Python and visualize with d3
Reading Note: An Introduction to Data Analysis with Python
How to get more than 1000 data with SQLAlchemy + MySQLdb
Get comments on youtube Live with [python] and [pytchat]!
Get mail from Gmail and label it with Python3
Investigate Java and python data exchange with Apache Arrow
I tried to analyze J League data with Python
[Python] Get user information and article information with Qiita API
Get data from database via ODBC with Python (Access)
Something to enjoy with Prim Pro (X-Play) and Python
Get a large amount of Starbucks Twitter data with python and try data analysis Part 1
Reading, summarizing, visualizing, and exporting time series data to an Excel file with Python
[CGI] Run the Python program on the server with Vue.js + axios and get the output data
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
Get country code with python
Easy to use Nifty Cloud API with botocore and python
Programming with Python and Tkinter
[Introduction to cx_Oracle] (Part 6) DB and Python data type mapping
I want to be able to analyze data with Python (Part 3)
Encryption and decryption with Python
screen and split screen with python and ssh login to remote server
Python and hardware-Using RS232C with Python-
I tried to make various "dummy data" with Python faker