Skip to content

Instantly share code, notes, and snippets.

@AntoineVe
Created April 27, 2018 17:50
Show Gist options
  • Select an option

  • Save AntoineVe/4954238fd5159636aae626e7de2f9226 to your computer and use it in GitHub Desktop.

Select an option

Save AntoineVe/4954238fd5159636aae626e7de2f9226 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
'''
Read password from ldap and add or change it in opensmtp passwd file
'''
import ldap
OPENSMTPD_PASSWD_FILE = "/etc/mail/passwd"
SERVER_LDAP = "ldap.reve.space"
DN = "ou=utilisateurs,dc=reve,dc=space"
def read_pass():
connection = ldap.open(SERVER_LDAP)
connection.protocol_version = ldap.VERSION3
searchScope = ldap.SCOPE_SUBTREE
retrieveAttributes = ['userPassword']
searchFilter = "(objectClass=inetOrgPerson)"
ldap_result_id = connection.search(
DN,
searchScope,
searchFilter,
retrieveAttributes)
result_set = list()
while True:
result_type, result_data = connection.result(ldap_result_id, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
openldap_pass = dict()
for result in result_set:
user = result[0][1]['uid'][0]
password = result[0][1]['userPassword'][0]
openldap_pass.update({user: password})
return(openldap_pass)
def write_pass(pass_list):
opensmtp_pass = dict()
with open(OPENSMTPD_PASSWD_FILE, 'r') as file:
for line in file.readlines():
user = line.split(':')[0]
password = line.split(':')[1]
opensmtp_pass.update({user: password})
opensmtp_pass.update(pass_list)
return(opensmtp_pass)
if __name__ == '__main__':
password_dico = write_pass(read_pass())
with open(OPENSMTPD_PASSWD_FILE, 'w') as file:
for key in password_dico.keys():
file.write(key + ":" + password_dico[key] + "::::::\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment