Guest User

Untitled

a guest
Nov 26th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import json
  2. import re
  3. import sys
  4. import csv
  5.  
  6. import ldap
  7. from xlsxwriter.workbook import Workbook
  8.  
  9. from ldap3 import Server, Connection, ALL
  10. from ldap3.core.exceptions import LDAPBindError
  11.  
  12. from config import LDAP_IP, LDAP_PORT
  13.  
  14.  
  15. def check_credentials(samaccountname, password):
  16. try:
  17. get_connection(samaccountname, password)
  18. return True
  19. except LDAPBindError:
  20. return False
  21.  
  22.  
  23. def convert_to_xls():
  24. workbook = Workbook('employees.xlsx')
  25. worksheet = workbook.add_worksheet()
  26. with open('employees.csv', 'rt', encoding='utf8') as f:
  27. reader = csv.reader(f)
  28. for r, row in enumerate(reader):
  29. for c, col in enumerate(row):
  30. worksheet.write(r, c, col)
  31. workbook.close()
  32.  
  33.  
  34. def write_to_csv(employees: list):
  35. with open('employees.csv', 'w') as csvfile:
  36. fieldnames = ['Identifier', 'Name', 'Position']
  37. writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  38. writer.writeheader()
  39. samaname_matcher = re.compile(r'\w+\.\w+')
  40. for emp in employees:
  41. keys = dir(emp)
  42. if 'sAMAccountName' in keys and 'displayName' in keys and 'title' in keys:
  43. ident = emp.samaccountname
  44. if samaname_matcher.match(str(ident)):
  45. response = dict()
  46. response['Identifier'] = ident
  47. response['Name'] = emp.displayName
  48. response['Position'] = 'Fired' if 'Fired' in str(emp.distinguishedName) else emp.title
  49. writer.writerow(response)
  50.  
  51.  
  52. def get_connection(samaccountname, password):
  53. try:
  54. return Connection(Server(host=LDAP_IP, port=int(LDAP_PORT)), user=f'ELAMA\{samaccountname}', password=password,
  55. auto_bind=True)
  56. except LDAPBindError as err:
  57. raise err
  58.  
  59.  
  60. def my_connection(username, password):
  61. try:
  62. conn = get_connection(username, password)
  63. conn.search('dc=elama,dc=local', '(&(objectCategory=person)(objectClass=person)(sAMAccountName=*))',
  64. attributes='*')
  65. write_to_csv(conn.entries)
  66. convert_to_xls()
  67. except LDAPBindError:
  68. print('Oops, you have inserted invalid credentials')
  69.  
  70.  
  71. def main():
  72. argv = sys.argv
  73. if len(argv) != 3:
  74. print('usage: <username> <password>')
  75. else:
  76. my_connection(argv[1], argv[2])
  77.  
  78.  
  79. if __name__ == '__main__':
  80. main()
Add Comment
Please, Sign In to add comment