Share
Explore

Hands-on Python programming drills focused on learning to use PYTHON to manipulate a target computer system.

How to do this Lab: Do all exercises
Make a Word Document: saved as StudentName_StudentID.docx

Open a Text Editor. Sublime is a nice and free text editor.

Make a directory to work your code in.

image.png
Write the Python Code and execute it at the command prompt.
Take a screen shot and paste into your Word Document.

megaphone

Learning Outcomes:

By incorporating these hands-on PYTHON exercises and real-world workflows, students will gain practical experience in using Python to automate the tasks of Windows System Administration.
You will learn to:
Automate repetitive tasks,
Streamline day to day system management,
Improve efficiency in their day-to-day responsibilities as Windows administrators. [citation:2][citation:8]

Introduction: Tanveer's Journey into Hands-on Windows Administration
Hey everyone, I'm Tanveer, a 26-year-old fresh hire at Mega Data Corporation. I recently joined the company as a DevOps Windows Administrator, and let me tell you, it's been an incredible journey of learning and growth. [citation:2]
When I first started, I thought I could become a Windows administration wizard by burying my nose in Microsoft documentation and memorizing every single command. Boy, was I wrong! It didn't take me long to realize that the real magic happens when you get your hands dirty and start exploring the Windows operating system firsthand. [citation:4]
I remember my first day on the job, sitting in front of a Windows server, feeling both excited and nervous. My mentor, a seasoned admin, smiled at me and said, "Tanveer, the best way to learn is by doing. Don't be afraid to experiment, break things, and figure out how to fix them." Those words stuck with me, and I embraced the challenge head-on. [citation:3][citation:11]
As I dove into the world of hands-on Windows administration, I discovered a whole new level of understanding. Each interactive exercise felt like a puzzle waiting to be solved. I found myself eagerly exploring the intricacies of user management, network configurations, and system optimization. With every successful task, my confidence grew, and I could feel the power of hands-on learning. [citation:5][citation:7]
One of my favorite moments was when I automated my first task using PowerShell. It was a script to monitor disk space and send alerts when thresholds were reached. I remember the sense of accomplishment I felt as I watched my script run flawlessly, saving me hours of manual work. That's when it hit me: hands-on learning not only deepens your understanding but also empowers you to be more efficient and effective in your role. [citation:6]
But it wasn't always smooth sailing. There were times when I encountered challenges and roadblocks. However, those obstacles turned out to be the best learning opportunities. I learned to troubleshoot, seek help from my colleagues, and find creative solutions. Each challenge I overcame added another tool to my Windows administration toolkit. [citation:7]
As I progressed in my role, I realized that hands-on learning goes beyond just memorizing commands and configurations. It's about developing a intuitive understanding of how Windows components work together and how to optimize them for different scenarios. It's about being able to think on your feet, adapt to new situations, and find innovative ways to streamline processes. [citation:4][citation:5]
Through my hands-on experiences, I've grown not only as a Windows administrator but also as a problem solver. I've learned to embrace challenges as opportunities for growth and to continuously push myself out of my comfort zone. And you know what? The more I practice, the more confident and skilled I become. [citation:3][citation:11]
So, to all the aspiring Windows administrators out there, my advice is this: don't be afraid to get your hands dirty. Embrace the power of hands-on learning and let your curiosity guide you. Experiment, make mistakes, and learn from them. Trust me, the satisfaction of successfully troubleshooting a complex issue or automating a tedious task is unmatched. [citation:7]
Join me on this exciting journey of hands-on Windows administration. Let's explore, learn, and grow together. Who knows, maybe one day you'll be the one sharing your own stories and inspiring the next generation of administrators. [citation:2]
So, let's roll up our sleeves, dive into the Windows operating system, and unlock our full potential as Windows administrators. Trust me, it's going to be an incredible ride! [citation:11]

# Python for Windows Administration

## Lesson Objective

Students will learn how to use Python to automate common Windows administration tasks through hands-on programming exercises.
These exercises drill you in practical skills in using Python libraries to interact with the Windows operating system - via the Windows System Administration Objects that are exposed via WMI APIs and Interfaces - to perform system management functions.
Core Skills as Windows Dev Ops Specialists:
Working with the Terminal Window - Command Prompt
megaphone

WMI (Windows Management Instrumentation) module:

The WMI module is a Python module that provides a lightweight wrapper around available WMI classes and functionalities.

The WMI MODULE enables our PYTHON PROGRAMs to enable system administrators to query data from Windows machines, both locally and remotely.

WMI is an implementation of Microsoft's Common Information Model (CIM) and provides a way to represent management information.

The WMI module can be used to automate various system administration tasks on Windows
.


It's worth noting that while Python can be used for system administration on Windows, PowerShell is often the preferred language for Windows system administration due to its integration with the Windows operating system and Microsoft products

PowerShell is specifically designed for Windows administration tasks and has extensive support for .NET.

Python distributions like Fabric and the WMI module can be useful for Windows system administration tasks. However, it's important to consider the specific requirements of your system administration tasks and the tools that are commonly used in your environment.

## Lesson Plan (2 hours)

1. Introduction to Python for Windows Administration (15 min)

- Overview of Python's capabilities for system administration [citation:7] - Benefits of automating tasks with Python [citation:11] - Setting up the Python environment on Windows [citation:6]
→ 2. Hands-on Exercise 1: Gathering System Information (20 min)
- Using Python's `wmi` module to retrieve system details [citation:5] - Querying system properties like CPU, memory, disks - Displaying system information in a formatted output
3. Hands-on Exercise 2: Managing Files and Directories (25 min) - Using Python's `os` and `shutil` modules for file operations - Creating, copying, moving, and deleting files and folders - Searching for files based on patterns using `glob`
4. Hands-on Exercise 3: Automating User Management (30 min) - Using Python to create, modify, and delete user accounts - Managing user groups and permissions - Generating reports on user activities and login history
5. Hands-on Exercise 4: Scheduling Tasks and Scripts (20 min) - Using Python's `sched` module to schedule tasks - Creating scripts to automate recurring administration tasks - Configuring scripts to run at specific times or intervals
*** 6. Hands-on Exercise 5: Monitoring System Performance (25 min) - Using Python to monitor CPU usage, memory consumption, and disk space - Collecting performance metrics and generating reports - Setting up alerts and notifications for critical thresholds
*** 7. Conclusion and Next Steps (10 min) - Recap of key concepts and skills learned - Resources for further learning and exploration [citation:9][citation:10] - Real-world applications and projects ideas [citation:3][citation:4]

Case Studies

*** 5 Standard Workflows for Windows Administration with Python


1. Automated System Inventory:

Script to gather hardware and software details of multiple machines, store the data in a central database, and generate inventory reports.

[citation:5][citation:11]

2. **User Provisioning**: Automate the process of creating new user accounts, assigning permissions, and setting up user environments based on predefined templates. [citation:7][citation:8]
3. **Patch Management**: Use Python to scan systems for missing updates, download and install required patches, and verify the patch status across the network. [citation:6][citation:11]
4. **Disk Space Cleanup**: Create a script to analyze disk space usage, identify large files and old data, and automate the cleanup process based on specified criteria. [citation:3][citation:5]
5. **System Health Monitoring**: Develop a Python-based monitoring solution that continuously checks system metrics, logs events, sends alerts on issues, and generates performance reports. [citation:4][citation:7]


megaphone

# Introduction to Python for Windows Administration


Overview of Python's Capabilities for System Administration

Python is a versatile and powerful programming language that offers extensive capabilities for system administration tasks, particularly on the Windows platform. [citation:7] Some key areas where Python excels in Windows administration include:
- Scripting and automation:
Python's simplicity and rich libraries make it an ideal choice for writing scripts to automate repetitive tasks, such as file management, user provisioning, and system configuration. [citation:7]
- System information gathering:
Python provides modules like `wmi` and `psutil` to retrieve detailed system information, including hardware specs, installed software, and performance metrics. [citation:5][citation:7] - File and directory management: With built-in modules like `os` and `shutil`, Python enables administrators to perform file and directory operations efficiently, such as copying, moving, deleting, and searching for files. [citation:4] - User and group management: Python can interact with Windows APIs to manage user accounts, groups, and permissions programmatically, simplifying user provisioning and access control. [citation:8] - Task scheduling and automation: Python's `sched` module and third-party libraries like `schedule` allow administrators to create and manage scheduled tasks, automating recurring maintenance activities. [citation:6][citation:11]

Benefits of Automating Tasks with Python

Automating Windows administration tasks using Python offers several significant benefits:
1. Time savings: By automating repetitive and time-consuming tasks, administrators can free up valuable time to focus on more strategic initiatives and problem-solving. [citation:11]
2. Consistency and accuracy: Automated scripts ensure that tasks are performed consistently and accurately every time, reducing the risk of human errors and misconfigurations. [citation:7][citation:11]
3. Scalability: Python scripts can be easily scaled to manage a large number of systems and perform actions across multiple machines simultaneously, improving efficiency in enterprise environments. [citation:5]
4. Customization and flexibility: Python's extensive libraries and modules provide administrators with the flexibility to customize scripts and tailor them to their specific requirements and workflows. [citation:6][citation:11]
5. Integration with other tools: Python integrates well with various Windows administration tools and technologies, such as PowerShell, Windows Management Instrumentation (WMI), and Active Directory, enabling seamless automation and management. [citation:4][citation:7]

## Setting up the Python Environment on Windows

To start using Python for Windows administration, you need to set up the Python environment on your Windows machine. Here's a step-by-step guide:
1. Download Python: Visit the official Python website (https://www.python.org) and download the latest version of Python for Windows. Choose the appropriate installer based on your system architecture (32-bit or 64-bit). [citation:6][citation:9] 2. Run the installer: Double-click on the downloaded installer file and follow the installation wizard. Make sure to select the option to add Python to the PATH environment variable during the installation process. [citation:6][citation:10] 3. Verify the installation: Open the Command Prompt and type `python --version` to check if Python is installed correctly. It should display the installed Python version. [citation:6][citation:8]
4. Set up a virtual environment (optional): It's recommended to create a virtual environment for each Python project to keep the dependencies isolated

Use the following commands to create and activate a virtual environment:

``` python -m venv myenv myenv\Scripts\activate ``` [citation:3][citation:6]
5. Install additional libraries:
Python comes with a wide range of built-in modules, but you may need to install additional libraries for specific administration tasks.

Use the `pip` package manager to install libraries, for example:

``` pip install wmi psutil ``` [citation:4][citation:6]
With the Python environment set up, you're ready to start writing and executing Python scripts for Windows administration tasks. [citation:6][citation:11]
Remember to refer to the official Python documentation and relevant library documentation for detailed information on specific modules and their usage in Windows administration scenarios. [citation:9][citation:10]

megaphone

Python Packages 'wmi' and 'psutil' for Windows System Administration

The **'wmi'** and **'psutil'** packages in Python are commonly used for Windows system administration tasks. Let's take a closer look at each package and their functionalities.
#### 'wmi' Package: The **'wmi'** package is a lightweight wrapper around the Windows Management Instrumentation (WMI) classes and functionalities.
WMI is Microsoft's implementation of the Common Information Model (CIM), which is an industry-standard way of representing management information. It allows you to query various pieces of information from Windows machines running the necessary agent with the right permissions.
The 'wmi' package in Python provides a convenient way for system administrators to query information from local or remote Windows machines. It offers a set of classes and methods that allow you to interact with the WMI API and retrieve information about system resources, processes, services, and more. By utilizing the 'wmi' package, system administrators can automate tasks and perform system administration processes using Python scripts.
To use the 'wmi' package, you need to install it using the 'pip' package management framework. Once installed, you can import the 'wmi' module in your Python program and start querying information from Windows machines.

psutil' Package:

The **'psutil'** package is another useful Python package for system administration tasks,
including monitoring and managing processes and system utilization.
The name 'psutil' stands for "process and system utilities." It provides a cross-platform library that allows administrators and developers to gather information about running processes, system resources, and more.
With the 'psutil' package, you can retrieve information such as CPU usage, memory usage, disk usage, network statistics, and process details.
It offers a simple and intuitive interface to access system-related information, making it easier to monitor and manage systems programmatically.
To use the 'psutil' package, you need to install it using the 'pip' package management framework. Once installed, you can import the 'psutil' module in your Python program and start utilizing its functionalities to gather system information and manage processes.
In summary, the **'wmi'** package provides a lightweight wrapper around the WMI classes and functionalities, allowing system administrators to query information from Windows machines. On the other hand, the **'psutil'** package offers a convenient way to monitor and manage processes and system utilization. Both packages are valuable tools for Windows system administration tasks and can be used to automate various processes and gather system information using Python.
Please note that the installation and usage details of these packages may vary depending on your specific Python environment and requirements. It is recommended to refer to the official documentation and examples provided by the package developers for more detailed instructions on installation and usage.
Geeks for Geeks
image.png

Hands On Exercise 1:

Get Your System Information - Using Python Script geeksforgeeks.org
How to Create a Computer Inventory Script in Python for ... progress.com
How to Get the list of Running Processes using Python? ​

To run our labs, we will use:
Anaconda PYTHON distribution installed on your O.S.
The Command Terminal
Sublime Text Editor:
megaphone

# Hands-on Exercise 1: Gathering System Information

In this exercise, we will explore how to gather system information using Python's `wmi` module.
The `wmi` module provides a simple and efficient way to retrieve various system details, such as CPU information, memory usage, and disk properties. [citation:5]
To get started, make sure you have the `wmi` module installed. You can install it using the following command: ``` ​pip install wmi
Once installed, you can import the `wmi` module in your Python script: ```python import wmi ```
The `wmi` module allows you to connect to the local machine or a remote machine and query system information using WMI (Windows Management Instrumentation) classes. [citation:5]
Here are a few examples of how you can retrieve system details using the `wmi` module:
1. Retrieving CPU Information: ```python C:\lab2_python_may22> ``` [citation:5][citation:7]
2. Retrieving Memory Information: c = wmi.WMI() for memory in c.Win32_PhysicalMemory(): print(f"Memory Capacity: {int(memory.Capacity) // (1024**3)} GB") print(f"Memory Speed: {memory.Speed} MHz")
Retrieving Disk Information: ```python c = wmi.WMI() for disk in c.Win32_LogicalDisk(DriveType=3): print(f"Disk Name: {disk.Name}") print(f"Total Size: {int(disk.Size) // (1024**3)} GB") print(f"Free Space: {int(disk.FreeSpace) // (1024**3)} GB") ``` [citation:5][citation:7]
These are just a few examples of the system information you can retrieve using the `wmi` module.
You can explore other WMI classes and properties to gather additional details based on your specific requirements. [citation:5][citation:7]
Code Drills
Now, let's practice gathering system information through some code drills. Follow the instructions below and complete the code exercises:
1. Retrieve the total number of processors and the architecture of the operating system. import wmi
c = wmi.WMI() # Write your code here to retrieve the total number of processors and the OS architecture ```
2. Retrieve the total physical memory and the available virtual memory. ```python import wmi
c = wmi.WMI() # Write your code here to retrieve the total physical memory and available virtual memory ```
3. Retrieve the system name, manufacturer, and model. ```python import wmi
c = wmi.WMI() # Write your code here to retrieve the system name, manufacturer, and model ```
4. Display the retrieved system information in a formatted output. ```python import wmi
c = wmi.WMI() # Write your code here to retrieve system information and display it in a formatted output ```
image.png

Once you have completed the code drills, you can compare your solutions with the provided examples and discuss any questions or challenges you encountered. [citation:3][citation:6]
Remember to refer to the `wmi` module documentation for more details on available WMI classes and properties that you can query to gather additional system information. [citation:9][citation:10]
By practicing these code drills and exploring the `wmi` module, you will gain hands-on experience in gathering system information using Python for Windows administration tasks. [citation:5][citation:7]


megaphone

Hands-on Exercise 2: Managing Files and Directories

Learning outcomes:

Working With Files in Python: realpython.com
practice-quiz-managing-files-and-directories.md github.com
shutil — High-level file operations docs.python.org

In this exercise, we will explore how to manage files and directories using Python's built-in `os` and `shutil` modules.
These modules provide a wide range of functions for performing common file and directory operations. [citation:3][citation:7]

Using the `os` module

The `os` module offers various functions for interacting with the operating system, including file and directory management. Here are some commonly used functions from the `os` module:
- `os.getcwd()`: Returns the current working directory. - `os.listdir(path)`: Returns a list of files and directories in the specified path. - `os.mkdir(path)`: Creates a new directory at the specified path. - `os.remove(path)`: Deletes a file at the specified path. - `os.rmdir(path)`: Deletes an empty directory at the specified path. - `os.rename(src, dst)`: Renames a file or directory from the source path to the destination path. [citation:4][citation:7]

Using the `shutil` module

The `shutil` module provides high-level operations for file and directory management, including copying and moving files. Some commonly used functions from the `shutil` module include:
- `shutil.copy(src, dst)`: Copies a file from the source path to the destination path. - `shutil.copy2(src, dst)`: Copies a file, preserving metadata, from the source path to the destination path. - `shutil.copytree(src, dst)`: Recursively copies a directory tree from the source path to the destination path. - `shutil.move(src, dst)`: Moves a file or directory from the source path to the destination path. - `shutil.rmtree(path)`: Recursively deletes a directory tree. [citation:3][citation:8]

Searching for files using `glob`

The `glob` module is used for searching and matching file patterns using wildcards. It allows you to find files based on specific criteria. Here's an example of using `glob` to search for files:
```python ​import glob
# Search for all text files in the current directory text_files = glob.glob("*.txt") print("Text files:", text_files) ```
[citation:5][citation:7]

Let’s create some text files to glob onto:
//
we can use Python's standard libraries to generate the text files and perhaps a simple method to create varied stories about bears. For this example, I'll create a basic framework for the stories and write them into text files. Keep in mind that the story generation will be quite rudimentary.
Here's a Python script for this purpose:
import random
import os

# Function to generate a short story about a bear
def generate_bear_story(index):
bear_types = ["grizzly", "polar", "black", "panda", "brown"]
activities = ["fishing", "sleeping", "exploring", "playing", "hunting"]
places = ["forest", "mountain", "river", "field", "snowy plain"]

bear = random.choice(bear_types)
activity = random.choice(activities)
place = random.choice(places)

story = f"Story {index}: Once upon a time, a {bear} bear was {activity} in a {place}."
return story

# Directory to store the text files
directory = "bear_stories"
os.makedirs(directory, exist_ok=True)

# Generate and write 100 stories
for i in range(100):
story = generate_bear_story(i + 1)
with open(f"{directory}/story_{i+1}.txt", "w") as file:
file.write(story)

print("100 bear stories have been created.")

This script does the following:
Defines a generate_bear_story function that randomly selects a bear type, activity, and place to construct a short story.
Creates a directory named bear_stories where all the story files will be saved.
Generates 100 text files, each containing a different short bear story.
Remember, the stories generated are very basic. For more complex or meaningful stories, you would need a more advanced approach, possibly involving natural language processing or a predefined larger set of story templates.
//
Code Drills
Now, let's practice managing files and directories through some code drills. Follow the instructions below and complete the code exercises:
1. Create a new directory called "my_directory" in the current working directory. ```python import os
# Write your code here to create the "my_directory" directory ```
2. Copy a file named "example.txt" from the current directory to the "my_directory" directory. ```python import shutil
# Write your code here to copy "example.txt" to "my_directory" ```
3. Move a file named "document.pdf" from the current directory to the "my_directory" directory. ```python import shutil
# Write your code here to move "document.pdf" to "my_directory" ```
4. Delete a file named "temp.txt" from the current directory. ```python import os
# Write your code here to delete "temp.txt" ```
5. Search for all Python files (*.py) in the current directory and its subdirectories. ```python import glob
# Write your code here to search for all Python files ```
6. Delete the "my_directory" directory and its contents. ```python import shutil
# Write your code here to delete "my_directory" and its contents ```
Once you have completed the code drills, you can compare your solutions with the provided examples and discuss any questions or challenges you encountered. [citation:3][citation:6]
Remember to refer to the official Python documentation for more details on the `os`, `shutil`, and `glob` modules and their available functions for file and directory management. [citation:9][citation:10]
By practicing these code drills and exploring the file and directory management modules, you will gain hands-on experience in automating file operations using Python for Windows administration tasks. [citation:4][citation:7]



→ Hands-on Exercise 3: Automating User Management

Important Points: User Account Privledge Escalation: The basis the the Not Petya Cyber Attack:

Lecture Content
In this exercise, we'll explore how to automate user management tasks using Python.
We'll dive into creating, modifying, and deleting user accounts,
managing user groups and permissions, and generating
reports on user activities and login history. [citation:7][citation:8]

Creating, Modifying, and Deleting User Accounts

First things first, let's talk about managing user accounts using Python.
We'll be using the `win32api` and `win32net` modules from the `pywin32` library to interact with the Windows API.
Here's how you can create, modify, and delete user accounts:
```python import win32api import win32net
# Create a new user account username = "johndoe" password = "P@ssw0rd" flags = win32net.USER_PRIV_USER level = 1 user_info = { "name": username, "password": password, "flags": flags, "priv": win32net.USER_PRIV_USER } try: win32net.NetUserAdd(None, level, user_info) print(f"User '{username}' created successfully.") except win32net.error as e: print(f"Error creating user: {e}")
# Modify user account properties username = "johndoe" new_full_name = "John Doe" user_info = { "name": username, "full_name": new_full_name } try: win32net.NetUserSetInfo(None, username, level, user_info) print(f"User '{username}' modified successfully.") except win32net.error as e: print(f"Error modifying user: {e}")
# Delete a user account username = "johndoe" try: win32net.NetUserDel(None, username) print(f"User '{username}' deleted successfully.") except win32net.error as e: print(f"Error deleting user: {e}") ```
In this code snippet, we demonstrate how to create a new user account with a specified username and password, modify user account properties like the full name, and delete a user account. [citation:7][citation:8]
Managing User Groups and Permissions
Next up, let's explore how to manage user groups and permissions using Python. We'll use the `win32net` module to add users to groups and modify group memberships. Here's an example:
```python import win32net
# Add a user to a group username = "johndoe" group_name = "Administrators" try: user_group_info = { "domainandname": username } win32net.NetLocalGroupAddMembers(None, group_name, 3, [user_group_info]) print(f"User '{username}' added to the '{group_name}' group.") except win32net.error as e: print(f"Error adding user to group: {e}")
# Remove a user from a group username = "johndoe" group_name = "Administrators" try: user_group_info = { "domainandname": username } win32net.NetLocalGroupDelMembers(None, group_name, [user_group_info]) print(f"User '{username}' removed from the '{group_name}' group.") except win32net.error as e: print(f"Error removing user from group: {e}") ```
In this code snippet, we demonstrate how to add a user to a group (e.g., the "Administrators" group) and remove a user from a group. [citation:7][citation:8]

Generating Reports on User Activities and Login History

Finally, let's explore how to generate reports on user activities and login history using Python. We'll use the `win32evtlog` module to access the Windows event log and retrieve user-related events. Here's an example:
```python import win32evtlog
# Retrieve user login events server = "localhost" log_type = "Security" hand = win32evtlog.OpenEventLog(server, log_type) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ events = win32evtlog.ReadEventLog(hand, flags, 0) login_events = [event for event in events if event.EventID == 4624]
# Generate a report on user login activities report = "User Login Report\n" report += "-------------------\n" for event in login_events: username = event.StringInserts[5] login_time = event.TimeGenerated.Format() report += f"User: {username}\tLogin Time: {login_time}\n"
print(report) win32evtlog.CloseEventLog(hand) ```
In this code snippet, we retrieve user login events from the Windows Security event log. We filter the events to include only those with the event ID 4624, which represents successful user logons. We then generate a report that includes the username and login time for each login event. [citation:7][citation:8]
Code Drills
Now it's your turn to practice automating user management tasks using Python!
Let's go through some code drills to reinforce what we've learned.
1. Create a new user account with the username "janedoe" and password "S3cur3P@ss". ```python import win32net
# Write your code here to create the "janedoe" user account ```
2. Modify the full name of the user "janedoe" to "Jane Doe". ```python import win32net
# Write your code here to modify the full name of the "janedoe" user account ```
3. Add the user "janedoe" to the "Users" group. ```python import win32net
# Write your code here to add the "janedoe" user to the "Users
megaphone

Hands-on Exercise 3: Code Drills Solution

Hands-on Exercise 3: Automating User Management with Python
In this exercise, we'll explore how to automate user management tasks using Python.
We will cover creating, modifying, and deleting user accounts, managing user groups and permissions, and generating reports on user activities and login history.
Lecture Content
In this exercise, we’ll use the `win32api` and `win32net` modules from the `pywin32` library to interact with the Windows API.
This lab will help you understand how to create, modify, and delete user accounts, manage user groups and permissions, and generate reports on user activities and login history.

3.A : Creating, Modifying, and Deleting User Accounts
First, let's talk about managing user accounts using Python. Here's how you can create, modify, and delete user accounts:
import win32net
def create_user(username, password): """Creates a new user account.""" user_info = { "name": username, "password": password, "priv": win32net.USER_PRIV_USER, "flags": win32net.UF_SCRIPT } try: win32net.NetUserAdd(None, 1, user_info) print(f"User '{username}' created successfully.") except win32net.error as e: print(f"Error creating user: {e}")
def modify_user(username, new_full_name): """Modifies user account properties.""" user_info = { "name": username, "full_name": new_full_name } try: win32net.NetUserSetInfo(None, username, 1, user_info) print(f"User '{username}' modified successfully.") except win32net.error as e: print(f"Error modifying user: {e}")
def delete_user(username): """Deletes a user account.""" try: win32net.NetUserDel(None, username) print(f"User '{username}' deleted successfully.") except win32net.error as e: print(f"Error deleting user: {e}")
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.