Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import re
- import sys
- import csv
- import ldap
- from xlsxwriter.workbook import Workbook
- from ldap3 import Server, Connection, ALL
- from ldap3.core.exceptions import LDAPBindError
- from config import LDAP_IP, LDAP_PORT
- def check_credentials(samaccountname, password):
- try:
- get_connection(samaccountname, password)
- return True
- except LDAPBindError:
- return False
- def convert_to_xls():
- workbook = Workbook('employees.xlsx')
- worksheet = workbook.add_worksheet()
- with open('employees.csv', 'rt', encoding='utf8') as f:
- reader = csv.reader(f)
- for r, row in enumerate(reader):
- for c, col in enumerate(row):
- worksheet.write(r, c, col)
- workbook.close()
- def write_to_csv(employees: list):
- with open('employees.csv', 'w') as csvfile:
- fieldnames = ['Identifier', 'Name', 'Position']
- writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
- writer.writeheader()
- samaname_matcher = re.compile(r'\w+\.\w+')
- for emp in employees:
- keys = dir(emp)
- if 'sAMAccountName' in keys and 'displayName' in keys and 'title' in keys:
- ident = emp.samaccountname
- if samaname_matcher.match(str(ident)):
- response = dict()
- response['Identifier'] = ident
- response['Name'] = emp.displayName
- response['Position'] = 'Fired' if 'Fired' in str(emp.distinguishedName) else emp.title
- writer.writerow(response)
- def get_connection(samaccountname, password):
- try:
- return Connection(Server(host=LDAP_IP, port=int(LDAP_PORT)), user=f'ELAMA\{samaccountname}', password=password,
- auto_bind=True)
- except LDAPBindError as err:
- raise err
- def my_connection(username, password):
- try:
- conn = get_connection(username, password)
- conn.search('dc=elama,dc=local', '(&(objectCategory=person)(objectClass=person)(sAMAccountName=*))',
- attributes='*')
- write_to_csv(conn.entries)
- convert_to_xls()
- except LDAPBindError:
- print('Oops, you have inserted invalid credentials')
- def main():
- argv = sys.argv
- if len(argv) != 3:
- print('usage: <username> <password>')
- else:
- my_connection(argv[1], argv[2])
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment