-
Notifications
You must be signed in to change notification settings - Fork 7
/
ldap-freeipa.py
executable file
·223 lines (190 loc) · 7.25 KB
/
ldap-freeipa.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python3
#
# ldap-freeipa.py
# Dynamic inventory script for FreeIPA using LDAP simple binds
# Steve Bonneville <sbonnevi@redhat.com>
#
# Copyright 2017 Red Hat, Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY RED HAT, INC. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL RED HAT, INC. BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import json
import ldap
import os
import sys
import six
from six.moves import configparser
###################################################
# DO NOT EDIT ABOVE THIS LINE.
##
# Configuration settings
##
# EDIT: LDAP URI of your FreeIPA server
LDAP_URI = "ldap://utility.lab.example.com"
# EDIT: BaseDN of your FreeIPA server
LDAP_BASEDN = "dc=lab,dc=example,dc=com"
# EDIT: DN and password of a service user on your FreeIPA server
# (anonymous bind can't see all the necessary attributes)
# should not be a normal end-user account since password is exposed
# to anyone with access to this script
# See http://www.freeipa.org/page/HowTo/LDAP (may be outdated)
LDAP_BINDDN = "uid=inventory,cn=users,cn=accounts,dc=lab,dc=example,dc=com"
LDAP_BINDPW = "needabetterpassword"
# DO NOT EDIT BELOW THIS LINE.
###################################################
# Above settings will be used as defaults.
# These settings can be overwritten by a ini file with a `ldap-freeipa` section
# and valid entries. The path of the ini file can be set with the environment
# variable 'LDAP_FREEIPA_INI_PATH', defaults to `ldap-freeipa.ini` in same
# directory as the `ldap-freeipa.py` script.
#
# Example `ldap-freeipa.ini`:
#
# [ldap-freeipa]
# ldap_uri = ldap://utility.lab.example.com
# ldap_basedn = dc=lab,dc=example,dc=com
# ldap_bindpw = needabetterpassword
# ldap_binddn = uid=inventory,cn=users,cn=accounts,dc=lab,dc=example,dc=com
# Work needed:
# * LDAPS support for FreeIPA
# * Potentially set some host variables from other attributes
# * Make it easier for a newbie to set the LDAP_* variables above
def get_config():
'''
Reads the settings from the ldap-freeipa.ini file
Returns ldap-freeipa setting dict.
'''
defaults = {
'ldap-freeipa': {
'ldap_uri': LDAP_URI,
'ldap_basedn': LDAP_BASEDN,
'ldap_binddn': LDAP_BINDDN,
'ldap_bindpw': LDAP_BINDPW,
'ini_path': os.path.join(
os.path.dirname(__file__),
'ldap-freeipa.ini',
)
}
}
if six.PY3:
config = configparser.ConfigParser()
else:
config = configparser.SafeConfigParser()
# where is the config?
ldap_freeipa_ini_path = os.environ.get(
'LDAP_FREEIPA_INI_PATH',
defaults['ldap-freeipa']['ini_path'])
config.read(ldap_freeipa_ini_path)
if 'ldap-freeipa' not in config.sections():
config.add_section('ldap-freeipa')
# apply defaults
for k, v in defaults['ldap-freeipa'].items():
if not config.has_option('ldap-freeipa', k):
config.set('ldap-freeipa', k, str(v))
# update ini_path
config.set('ldap-freeipa', 'ini_path', ldap_freeipa_ini_path)
return dict(config.items('ldap-freeipa'))
def listgroup(ldap_uri, ldap_basedn, ldap_binddn, ldap_bindpw):
# Simple bind to the FreeIPA server and run a subtree
# search for hostgroups (objectclass=ipahostgroup),
# and retrieve all values of their 'member' attributes
conn = ldap.initialize(ldap_uri)
search_scope = ldap.SCOPE_SUBTREE
search_filter = "(objectclass=ipahostgroup)"
search_attribute = ["cn", "member"]
try:
conn.protocol_version = ldap.VERSION3
conn.simple_bind_s(ldap_binddn, ldap_bindpw)
except ldap.INVALID_CREDENTIALS:
print("Your bind DN or password is incorrect.")
sys.exit(1)
except ldap.LDAPError as e:
print("LDAPError: %s." % e)
sys.exit(1)
try:
ldap_result = conn.search(
ldap_basedn,
search_scope,
search_filter,
search_attribute
)
hostgroup = {}
while 1:
result_type, result_data = conn.result(ldap_result, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
groupname = result_data[0][1]['cn'][0].decode("utf-8")
try:
memberlist = result_data[0][1]['member']
except KeyError:
memberlist = []
# If the RDN of a hostgroup member is "cn",
# then it's a nested hostgroup.
#
# If the RDN of a hostgroup member is "fqdn",
# then it's a host.
hosts = []
children = []
for member in memberlist:
memberdn = ldap.dn.str2dn(member)
if (memberdn[0][0][0] == "cn"):
children.append(memberdn[0][0][1])
if (memberdn[0][0][0] == "fqdn"):
hosts.append(memberdn[0][0][1])
if (children != []):
hostgroup[groupname] = {
'hosts': hosts,
'children': children
}
else:
hostgroup[groupname] = {
'hosts': hosts
}
# assume that we have no hostvars
hostgroup["_meta"] = {'hostvars': {}}
print(json.dumps(hostgroup))
except ldap.LDAPError as e:
print("LDAPError: %s." % e)
finally:
conn.unbind_s()
def listhost(hostname):
# does not check to ensure host exists
# assume that we have no hostvars
print(json.dumps({}))
if __name__ == '__main__':
if len(sys.argv) == 2 and (sys.argv[1] == '--list'):
config = get_config()
listgroup(
config['ldap_uri'],
config['ldap_basedn'],
config['ldap_binddn'],
config['ldap_bindpw'],
)
elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):
listhost(sys.argv[2])
else:
print("Usage: %s --list or --host <hostname>" % sys.argv[0])
sys.exit(1)