-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathldap-ad.py
executable file
·106 lines (90 loc) · 3.92 KB
/
ldap-ad.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
#!/usr/bin/env python3
import os
import re
import ldap3
import json
import configparser
import argparse
import ssl
parser = argparse.ArgumentParser(
description='Script to obtain host inventory from AD')
parser.add_argument('--list', action='store_true',
help='prints a json of hosts with groups and variables')
parser.add_argument('--host', help='returns variables of given host')
args = parser.parse_args()
class ADAnsibleInventory():
def __init__(self):
directory = os.path.dirname(os.path.abspath(__file__))
configfile = directory + '/ldap-ad.ini'
config = configparser.ConfigParser()
config.read(configfile)
username = config.get('ldap-ad', 'username')
password = config.get('ldap-ad', 'password')
basedn = config.get('ldap-ad', 'basedn')
ldapuri = config.get('ldap-ad', 'ldapuri')
port = config.get('ldap-ad', 'port')
ca_file = config.get('ldap-ad', 'ca_file')
adfilter = "(&(sAMAccountType=805306369))"
self.inventory = {"_meta": {"hostvars": {}}}
self.ad_connect(ldapuri, username, password, port, ca_file)
self.get_hosts(basedn, adfilter)
self.org_hosts(basedn)
if args.list:
print(json.dumps(self.inventory, indent=2))
if args.host is not None:
try:
print(self.inventory['_meta']['hostvars'][args.host])
except Exception:
print('{}')
def ad_connect(self, ldapuri, username, password, port, ca_file):
tls_configuration = ldap3.Tls(validate=ssl.CERT_REQUIRED,
ca_certs_file=ca_file)
server = ldap3.Server(ldapuri, use_ssl=True, tls=tls_configuration)
conn = ldap3.Connection(server,
auto_bind=True,
user=username,
password=password,
authentication=ldap3.NTLM)
self.conn = conn
def get_hosts(self, basedn, adfilter):
self.conn.search(search_base=basedn,
search_filter=adfilter,
attributes=['cn', 'dnshostname'])
self.conn.response_to_json
self.results = self.conn.response
def org_hosts(self, basedn):
# Removes CN,OU, and DC and places into a list
basedn_list = (re.sub(r"..=", "", basedn)).split(",")
for computer in self.results:
org_list = (re.sub(r"..=", "", computer['dn'])).split(",")
# Remove hostname
del org_list[0]
# Removes all excess OUs and DC
for count in range(0, (len(basedn_list)-1)):
del org_list[-1]
# Reverse list so top group is first
org_list.reverse()
org_range = range(0, (len(org_list)))
for orgs in org_range:
if computer['attributes']['dNSHostName']:
if orgs == org_range[-1]:
self.add_host(org_list[orgs],
computer['attributes']['dNSHostName'])
else:
self.add_group(group=org_list[orgs],
children=org_list[orgs+1])
def add_host(self, group, host):
host = (''.join(host)).lower()
group = (''.join(group)).lower()
if group not in self.inventory.keys():
self.inventory[group] = {'hosts': [], 'children': []}
self.inventory[group]['hosts'].append(host)
def add_group(self, group, children):
group = (''.join(group)).lower()
children = (''.join(children)).lower()
if group not in self.inventory.keys():
self.inventory[group] = {'hosts': [], 'children': []}
if children not in self.inventory[group]['children']:
self.inventory[group]['children'].append(children)
if __name__ == '__main__':
ADAnsibleInventory()