admin scripts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
4.3 KiB

  1. #!/usr/bin/python3
  2. """
  3. -maK
  4. This is a script to send a mail to a group
  5. defined by an ldap search
  6. or simply send a singular mail
  7. use ./groupmail -h
  8. """
  9. import smtplib
  10. import argparse
  11. import os
  12. def sendmail(frm, to_email, subject, body, cc_email=''):
  13. """ Send email"""
  14. msg = '\r\n'
  15. msg.join(('From: %s' % frm,
  16. 'To: %s' % to_email,
  17. 'CC: %s' % cc_email,
  18. 'Subject: %s' % subject,
  19. '',
  20. '%s' % body))
  21. try:
  22. smtp = smtplib.SMTP('mailhost.redbrick.dcu.ie')
  23. smtp.sendmail(frm, to_email, msg)
  24. smtp.quit()
  25. except smtp.SMTPRecipientsRefused:
  26. print('Error sending mail to ' + to_email)
  27. except smtp.SMTPHeloError:
  28. print('The server didn’t reply properly to the HELO greeting.')
  29. except smtp.SMTPSenderRefused:
  30. print('The server didn’t accept the from address')
  31. except smtp.SMTPDataError:
  32. print('The server replied with an unexpected error code')
  33. except smtp.SMTPNotSupportedError:
  34. print('utf8 not supported by server')
  35. def mailgroup(ldif, frm, subject, body, prnt):
  36. """ email groups"""
  37. to_mail = ldif.split('dn: uid=')
  38. ldap_cn = ''
  39. altmail = ''
  40. uid = ''
  41. for j in range(1, len(to_mail)):
  42. credentials = to_mail[j].split('\n')
  43. for i in credentials:
  44. if i.startswith('uid: '):
  45. uid = i.split()[1]
  46. if i.startswith('cn: '):
  47. ldap_cn = i.split('cn: ')[1]
  48. if i.startswith('altmail: '):
  49. altmail = i.split()[1]
  50. if prnt:
  51. print(uid + ' - ' + ldap_cn + ' : ' + altmail)
  52. else:
  53. #Send mail to each
  54. print('Send mail to ' + ldap_cn + ' using ' + altmail + ' (y|n)?')
  55. send = input('default(y): ')
  56. if(send == 'n') or (send == 'N'):
  57. print('Mail not sent to ' + ldap_cn + ' using ' + altmail + '\n')
  58. else:
  59. sendmail(frm, altmail.strip(), subject, body)
  60. print('Mail sent to ' + ldap_cn + ' using ' + altmail + '\n')
  61. def check_args(args):
  62. """check args for sending"""
  63. if(args.GROUPS is None and args.FROM != None and args.TO != None and args.SUBJECT != None and
  64. args.MSG != None):
  65. return not args.PRINT
  66. return False
  67. def main():
  68. """Main method"""
  69. parser = argparse.ArgumentParser(description='Used to mail an ldap group/groups')
  70. parser.add_argument('-g', dest='GROUPS', type=str,
  71. help='Specify groups or singular group.\
  72. (eg. club or club,society,founders,redbrick)')
  73. parser.add_argument('-p', dest='PRINT', action='store_true',
  74. help='Only print details - Do not send')
  75. parser.add_argument('-f', dest='FROM', type=str, help='Who the mail is from.')
  76. parser.add_argument('-cc', dest='CC', type=str, help='cc all mails to.')
  77. parser.add_argument('-m', dest='MSG', type=str,
  78. help='Location of Message to be sent (text file etc)')
  79. parser.add_argument('-t', dest='TO', type=str, help='Who singular mail is To.')
  80. parser.add_argument('-s', dest='SUBJECT', type=str, help='Subject of mail.')
  81. args = parser.parse_args()
  82. if args.GROUPS != None:
  83. if ',' in args.GROUPS:
  84. search_params = args.GROUPS.split(',')
  85. else:
  86. search_params = args.GROUPS
  87. ldapsearch = 'ldapsearch -D cn=root,ou=ldap,o=redbrick -y /etc/ldap.secret -xLLL '
  88. if isinstance(search_params, str):
  89. ldapsearch += '"(objectClass=' + search_params + ')" uid cn altmail'
  90. else:
  91. ldapsearch += '"(|'
  92. for i in search_params:
  93. ldapsearch += '(objectClass='+ i +')'
  94. ldapsearch += ')" uid cn altmail'
  95. ldif = os.popen(ldapsearch).read()
  96. if args.FROM != None and args.SUBJECT != None and args.MSG != None:
  97. mailgroup(ldif, args.FROM, args.SUBJECT, args.MSG, args.PRINT)
  98. else:
  99. mailgroup(ldif, '', '', '', args.PRINT)
  100. exit()
  101. if args.MSG != None:
  102. with open(args.MSG, 'r') as content:
  103. args.MSG = content.read()
  104. if check_args(args):
  105. sendmail(args.FROM, args.TO, args.SUBJECT, args.MSG, args.CC)
  106. if __name__ == '__main__':
  107. main()