Debian Codegraph @

docs/tutorial.rst

raw
1 Quickstart
2 **********
3
4 .. module:: bonsai
5 :noindex:
6
7 After we installed the Bonsai module, let's see the basic functions to communicate with an LDAP
8 server.
9
10 Connecting
11 ==========
12
13 First we are connecting to the LDAP server at "example.org" using an :class:`LDAPClient` object:
14
15 >>> from bonsai import LDAPClient
16 >>> client = LDAPClient("ldap://example.org")
17 >>> conn = client.connect()
18
19 If we want to use a secure connection over SSL/TLS we can change the URL to `ldaps://`:
20
21 >>> client = LDAPClient("ldaps://example.org")
22
23 Or set the `tls` parameter to True for the LDAPClient:
24
25 >>> client = LDAPClient("ldap://example.org", True)
26 >>> conn = client.connect()
27
28 .. note::
29 Use either the `ldaps://` scheme or the tls parameter set to True for secure connection,
30 but it's ill-advise to use both. If both present the client will set the tls attribute
31 to False to avoid connection error.
32
33 .. note::
34 When you encounter "unknown error code"-errors thrown by the exception
35 :class:`ConnectionError` when setting up SSL/TLS-connections with OpenLDAP, use the
36 bonsai-Debug-function :func:`bonsai.set_debug`. Set the first parameter to True and the
37 second to -1. Then you will see the calls (and probably errormessages) of the underlying
38 OpenLDAP-Library in the output.
39
40 If we want to use a filesocket connection point the URL to `ldapi://`:
41
42 >>> client = LDAPClient("ldapi://%2Frun%2Fslapd%2Fldapi")
43
44 (Please note that in this case the file location has to be URL-encoded.)
45
46 Now, we have an anonym bind to the server, so LDAP whoami operation - which helps to get the
47 identity about the authenticated user - will return with the following:
48
49 >>> conn.whoami()
50 'anonymous'
51
52 To connect with a certain user to the server we have to set credentials before connection:
53
54 >>> client = LDAPClient("ldaps://example.org")
55 >>> client.set_credentials("SIMPLE", user="cn=test,dc=bonsai,dc=test", password="secret")
56 >>> conn = client.connect()
57 >>> conn.whoami()
58 'cn=test,dc=bonsai,dc=test'
59
60 Searching
61 =========
62
63 To execute a simple search in the dictionary we have to use the :meth:`LDAPConnection.search`
64 method. The function's first parameter - the base DN - sets where we would like to start the search
65 in the dictionary tree, the second parameter - the search scope - can have the following values:
66
67 - 0 (base): searching only the base DN.
68 - 1 (one): searching only one tree level under the base DN.
69 - 2 (sub): searching of all entries at all levels under, including the base DN.
70
71 The scope parameter is replaceable with an :class:`LDAPSearchScope` enumeration, for e.g.
72 :attr:`LDAPSearchScope.ONE` for one level search.
73
74 The third parameter is a standard LDAP filter string.
75
76 The result will be a list of LDAPEntry objects or an empty list, if no object is found.
77
78 >>> conn = client.connect()
79 >>> conn.search("ou=nerdherd,dc=bonsai,dc=test", bonsai.LDAPSearchScope.ONE, "(objectclass=*)")
80 [{'dn': <LDAPDN cn=chuck,ou=nerdherd,dc=bonsai,dc=test>, 'sn': ['Bartowski'],
81 'cn': ['chuck'], 'givenName': ['Chuck'], 'objectClass': ['inetOrgPerson',
82 'organizationalPerson', 'person', 'top']}, {'dn': <LDAPDN cn=lester,ou=nerdherd,dc=bonsai,dc=test>,
83 'sn': ['Patel'], cn': ['lester'], 'givenName': ['Laster'], 'objectClass': ['inetOrgPerson',
84 'organizationalPerson', 'person', 'top']}, {'dn': <LDAPDN cn=jeff,ou=nerdherd,dc=bonsai,dc=test>,
85 'sn': ['Barnes'], 'cn': ['jeff'], 'givenName': ['Jeff'], 'objectClass': ['inetOrgPerson',
86 'organizationalPerson', 'person', 'top']}]
87 >>> conn.search("ou=nerdherd,dc=bonsai,dc=test", 0, "(objectclass=*)")
88 [{'dn': <LDAPDN ou=nerdherd,dc=bonsai,dc=test>, 'objectClass': ['organizationalUnit', 'top'],
89 'ou': ['nerdherd']}]
90
91 The other possible parameters are listed on the API page of :meth:`LDAPConnection.search`.
92
93 .. note::
94 As you can see every key - or LDAP attribute - in the entry has a list for clarity, even
95 if only one value belongs to the attribute. As most of the attributes could have more
96 than one value, it would be confusing, if some of the keys had string value and the
97 others had list.
98
99 Add and modify LDAP entry
100 =========================
101
102 To add a new entry to our dictionary we need to create an :class:`LDAPEntry` object with a valid new
103 LDAP DN:
104
105 >>> from bonsai import LDAPEntry
106 >>> anna = LDAPEntry("cn=anna,ou=nerdherd,dc=bonsai,dc=test")
107 >>> anna['objectClass'] = ['top', 'inetOrgPerson'] # Must set schemas to get a valid LDAP entry.
108 >>> anna['sn'] = "Wu" # Must set a surname attribute because inetOrgPerson schema requires.
109 >>> anna['mail'] = "[email protected]"
110 >>> anna.dn
111 <LDAPDN cn=anna,ou=nerdherd,dc=bonsai,dc=test>
112 >>> anna
113 {'dn': <LDAPDN cn=anna,ou=nerdherd,dc=bonsai,dc=test>, 'objectClass': ['top', 'inetOrgPerson'],
114 'sn': ['Wu'], 'mail': ['[email protected]']}
115
116 then call :meth:`LDAPConnection.add` to add to the server:
117
118 >>> conn.add(anna)
119 True
120
121 It's important, that we must set the schemas and every other attribute, that the schemas require.
122 If we miss a required attribute, the server will not finish the operation and return with an
123 :class:`bonsai.ObjectClassViolation` error.
124
125 To modify an entry we need to have one that is already in the dictionary (got it back after a
126 search or added it by ourselves previously), then we can easily add new attributes or modify
127 already existing ones like we usually do with a Python dict, the only difference is that we need to
128 call :meth:`LDAPEntry.modify` method at the end to save our modifications on the server side.
129
130 >>> anna['givenName'] = "Anna" # Set new givenName attribute.
131 >>> anna['cn'].append('wu') # Add new common name attribute without remove the already set ones.
132 >>> del anna['mail'] # Remove all values of the mail attribute.
133 >>> anna.modify()
134 True
135
136 In certain cases, an LDAP entry can have write-only attribute (e.g. password) that cannot be
137 represented in an LDAPEntry or we just want to change the value of an attribute without reading
138 it first. The :meth:`LDAPEntry.change_attribute` method expects an attribute name, the type
139 of the modification (as an integer or an :class:`LDAPModOp` enum) and the values as parameters
140 to change an entry:
141
142 >>> from bonsai import LDAPEntry, LDAPModOp
143 >>> anna = LDAPEntry("cn=anna,ou=nerdherd,dc=bonsai,dc=test")
144 >>> anna.change_attribute("userPassword", LDAPModOp.REPLACE, "newsecret")
145 >>> anna.modify()
146 True
147
148 Delete an LDAP entry
149 ====================
150
151 To delete an entry we've got two options: :meth:`LDAPConnection.delete` and
152 :meth:`LDAPEntry.delete`:
153
154 >>> conn.delete("cn=anna,ou=nerdherd,dc=bonsai,dc=test") # We have to know the DN of the entry.
155 True
156 >>> # Or we have a loaded LDAPEntry object, then
157 >>> anna.delete()
158 True
159
160 In the second case the entry is removed on the server, but we still have the data on the
161 client-side.
162
163 Rename an LDAP entry
164 ====================
165
166 To rename an existing entry call the :meth:`LDAPEntry.rename` method with the new DN on an already
167 loaded :class:`LDAPEntry` object:
168
169 >>> anna.dn
170 <LDAPDN cn=anna,ou=nerdherd,dc=bonsai,dc=test>
171 >>> anna.rename("cn=wu,ou=nerdherd,dc=bonsai,dc=test")
172 True
173 >>> anna.dn
174 <LDAPDN cn=wu,ou=nerdherd,dc=bonsai,dc=test>
175
176 Be aware that if you would like to move the entry into a different subtree of the directory, then
177 the stated subtree needs to already exist.
178
179 Close connection
180 ================
181
182 After we finished our work with the directory server we should close the connection:
183
184 >>> conn.close()
185
186 The :class:`LDAPConnection` object can be used with a context manager that will implicitly call the
187 :meth:`LDAPConnection.close` method:
188
189 .. code-block:: python
190
191 import bonsai
192
193 cli = bonsai.LDAPClient("ldap://localhost")
194 with cli.connect() as conn:
195 res = conn.search("ou=nerdherd,dc=bonsai,dc=test", 1)
196 print(res)
197 print(conn.whoami())
198
199
200 To find out more about the Bonsai module functionality read the :doc:`advanced` and the :doc:`api`.