Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Sunday, January 7, 2018

Connecting to Active Directory using Python

This post speaks about connecting to Active Directory using python - 

python provides the ldap3 for python which can be used to connect to active directory servers. The below code will take the userid and password of the user and check it against active directory to verify the user and his credentials.

import sys
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, AUTO_BIND_NO_TLS, SUBTREE
from ldap3.core.exceptions import LDAPCursorError

server_name = 'your server name or ipaddress'
domain_name = 'your domain name'
user_name = <username of the user>
password = <password of the user>


format_string = '{:40}   {}'

server = Server(server_name, get_info=ALL)
conn = Connection(server, user='{}\\{}'.format(domain_name, user_name), password=)
if not conn.bind():
    print("error")
else:
    print("sucessful")
   
print(format_string.format('Group', 'Description'))

#CN to get the only the users and not the servers
conn.search('CN=users,dc=domain_name,dc=com'.format(domain_name), search_filter='(&(samAccountName=' + '' + '))',search_scope=SUBTREE,attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])
for e in sorted(conn.entries):
    try:
        desc = e.description
    except LDAPCursorError:
        desc = ""
    print(format_string.format(str(e.name), desc))


This code will connect and print. However this code is not production ready code as you can see there is no exception handling, and the values are more or less hard coded in the code.

Friday, January 5, 2018

Send email using Python with To, Cc, and Bcc

So this is a very small post on how to send email in python where in there needs to be users in To, Cc and Bcc. 

Let us say we need to send mail with the below details - 
From address - abc@gmail.com
To address - def@gmail.com
Cc address - d@gmail.com, e@gmail.com
Bcc address - f@gmail.com 
Email subject - test
Email Body - test body
smtp - smtp.gmail.com
port - 587

*please note the email random.

Based on the above below is the code and explanation is above each one of the lines


import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import sys
import logging
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


def sendemail(fromaddr,senderpwd,smtp,port,msgSubject,msgBody,toaddr,cc,bcc):
      
    # instance of MIMEMultipart
    msg = MIMEMultipart()
    toaddr = toaddr 
    # storing the senders email address  
    msg['From'] = fromaddr
     
    # storing the receivers email address 
    msg['To'] = toaddr
    msg['Cc'] = cc
    msg['Bcc']= bcc
     
    # storing the subject 
    msg['Subject'] = msgSubject
     
    # string to store the body of the mail
    body = msgBody
     

     
    msg.attach(MIMEText(body, 'plain'))
     
    
      
    # creates SMTP session
    s = smtplib.SMTP(smtp, port)
     
    # start TLS for security
    s.starttls()
     
    # Authentication
    s.login(fromaddr, senderpwd)
     
    # Converts the Multipart msg into a string
    text = msg.as_string()
    msg.attach(body)
     
    # sending the mail
    s.sendmail(fromaddr, [toaddr,cc,bcc], text)
     
    # terminating the session
    s.quit()
    



def main():
    sendemail(' abc@gmail.com','randaompawd','smtp.gmail.com',587,'test','body test','def@gmail.com','d@gmail.com,e@gmail.com','f@gmail.com')
    
if __name__=="__main__":
    main()