Scripts

Python Script Example with Main Method in Active Directory

Here is a simple Python script that interacts with Active Directory (AD) using the pyad library:

import pyad

def main():
    # Connect to the local Active Directory
    pyad.set_defaults(ldap_server="localhost")

    # Search for a user with the username "john.doe"
    user = pyad.aduser.ADUser.from_cn("john.doe")

    # Print the user's distinguished name (DN)
    print("User DN:", user.dn)

    # Print the user's email address
    print("Email:", user.get_attribute("mail"))

if __name__ == "__main__":
    main()

Note that in this example, the pyad library is assumed to be installed in your Python environment. If it is not, you can install it using the following command:

pip install pyad

Here is another example of a Python script that interacts with Active Directory (AD) using the ldap3 library:

from ldap3 import Server, Connection, ALL

def main():
    # Connect to the local Active Directory server
    server = Server("localhost", get_info=ALL)
    connection = Connection(server, auto_bind=True)

    # Search for a user with the username "john.doe"
    connection.search("dc=example,dc=com", "(cn=john.doe)", attributes=["dn", "mail"])

    # Get the search results
    results = connection.response

    # Print the user's distinguished name (DN) and email address
    if results:
        user = results[0]
        print("User DN:", user["dn"])
        print("Email:", user["attributes"]["mail"])
    else:
        print("User not found.")

if __name__ == "__main__":
    main()

Note that in this example, the ldap3 library is assumed to be installed in your Python environment. If it is not, you can install it using the following command:

pip install ldap3
PyJoy

Recent Posts

Python Script to Monitor Network Traffic

Here is a simple Python script to monitor network traffic. import psutil def monitor_network(): #…

2 years ago

Python Script for Web Scraping

Here's a basic example of web scraping in Python using the requests and BeautifulSoup libraries:…

2 years ago

Python Script to SSH and Run Commands

Here's an example of how you can use Python to SSH into a remote server…

2 years ago

Python Code Example with Classes

Here's an example of a Python class that represents a rectangle: class Rectangle: def __init__(self,…

2 years ago

Python Script Example for System Administrators

Here's a Python script to monitor disk usage on a system and send an email…

2 years ago

How to Run a Python Script on Mac

Running a Python script on a Mac is a relatively straightforward process that can be…

2 years ago