Share
Explore

Assignment 1 DUE April 14 W24 IN2054-G10

Following practices done by real IT teams, you will submit the documentation for your Assignment 1 in the Format of a Word Document.
Submit your Word Document - named as StudentName_StudentID.docx to

In this Assignment, you will use PYTHON CODE using the WMI Windows Management Interface Python Class to automate a set of standard Windows Administration Tasks such as creating Users and Assigning Permissions based on a Text File of user account names and details.

Prerequisities:
You must have Python up and going.
(Optional) You will use VMWare with the Windows Server 2019 ISO.
If you cannot get Server going on VMWare, just do these activities on your Standard Windows 11 Work Station.

Hand in Format: Word Document

Now: Setup a GITBOOK Account. (Optional if you want to use GitBook, else just use Word)
image.png
image.png
image.png
image.png
image.png
megaphone

Coding Exercises:


You will be doing a series of exercises for the assignment that involves using Python with the Windows Management Instrumentation (WMI) interface to automate various Windows administration tasks.
These exercises will help students gain practical experience in scripting for system administration.
The final submission should be compiled in a Word document as per the guidelines.

Exercise 1: Introduction to Python and WMI

Objective: Learn to establish a connection to the WMI interface using Python and perform basic system queries.
Task: Write a Python script that connects to the WMI interface and fetches basic system information (OS name, version, system architecture).
Concepts Covered: Python basics, WMI connection, system query.

To accomplish Exercise 1, you'll need to write a Python script that connects to the Windows Management Instrumentation (WMI) interface and fetches basic system information. This exercise will give you hands-on experience with both Python and the WMI interface.

Before you start, make sure you have the WMI Python package installed. If not, you can install it via pip:

```bash
pip install WMI
```

Now, here's a detailed Python script for the task:

```python
import wmi

def fetch_system_info():
# Create a WMI client
client = wmi.WMI()

# Fetch operating system details
for os in client.Win32_OperatingSystem():
print("OS Name:", os.Caption)
print("Version:", os.Version)
print("Architecture:", os.OSArchitecture)

if __name__ == "__main__":
fetch_system_info()
```

### How the Script Works:

1. **Import WMI Module:** We start by importing the `wmi` module, which is a Python extension that provides an interface to the WMI on Windows. This module allows your script to interact with the operating system and gather system information.

2. **Function `fetch_system_info`:**
- This function is defined to encapsulate the task. Inside this function:
- We instantiate a `wmi.WMI()` object, which allows us to make WMI queries.
- We then use this object to access the `Win32_OperatingSystem` class. This class provides various properties about the operating system.

3. **Fetching and Printing Information:**
- We iterate through the result of `client.Win32_OperatingSystem()`. Even though typically there's only one operating system per machine, the WMI interface returns a list.
- For each operating system object (`os`) in this list, we print out the OS name (`os.Caption`), its version (`os.Version`), and the architecture (`os.OSArchitecture`).

4. **Main Guard:**
- The `if __name__ == "__main__":` line checks if the script is being run as a standalone file (rather than being imported as a module elsewhere). If it is, the `fetch_system_info` function is called.

### Testing the Script:
- Run this script in a Python environment on a Windows machine.
- It will print out the OS name, version, and architecture of the machine it's run on.

This exercise demonstrates the basics of using Python to interact with the WMI for system information retrieval. It's a foundational skill for more complex administrative tasks and automation in a Windows environment.

Exercise 2: Reading and Parsing User Data from a Text File

Objective: Develop skills in file I/O operations and text data parsing in Python.
Task: Write a Python script to read a text file containing user names and details, and parse this data into a usable format for further processing.
Concepts Covered: File operations, string manipulation.
megaphone

Preamble for Students

As we delve into our exercises, it's important to recognize the context in which these skills are applied in a professional environment. In real-world IT scenarios, especially in system administration and automation tasks, you'll often find yourself needing to manage user data. This data is typically stored in organized data sources like databases or, in simpler cases, text files. Such data repositories allow for dynamic and scalable handling of user information, essential for efficient system management.
However, for our current exercises, we are taking a more focused approach. Instead of pulling user data from external sources like databases or text files, we are going to "hard code" these values directly into our scripts. This decision is made to keep our primary focus on understanding and utilizing the Windows Management Instrumentation (WMI) interface with Python.
By hard coding the values, we can: 1. **Simplify the Exercise**: Reducing the complexity of data handling so we can concentrate on the core topic - WMI and its integration with Python. 2. **Ensure Consistency**: Each student will work with the same set of data, making it easier to understand the outcomes and troubleshoot any issues. 3. **Focus on Key Learning Objectives**: By reducing the scope to WMI and Python, we can dive deeper into these critical areas, ensuring a robust learning experience.
Remember, the simplification for educational purposes does not diminish the importance of learning data handling from external sources like databases and text files. These are valuable skills in the field of web development and system administration. As you progress in your learning journey, you will certainly encounter and engage with these aspects of data handling. For now, let's focus on mastering WMI with Python!
For Exercise 2, we'll create a Python script that demonstrates how to read from a text file, and then parse user data into a format suitable for processing. This task will enhance your skills in file input/output (I/O) operations and string manipulation.

Assume we have a text file named `users.txt` with user data formatted like this:

```
username1, email1@example.com, role1
username2, email2@example.com, role2
username3, email3@example.com, role3
...
```

Each line contains a username, email, and role, separated by commas.

Here's a detailed Python script to achieve this:

```python
def parse_user_data(file_path):
user_data = []

try:
# Open the file in read mode
with open(file_path, 'r') as file:
# Read each line in the file
for line in file:
# Strip leading/trailing whitespace and split by comma
parts = line.strip().split(',')

# Check if line is properly formatted
if len(parts) == 3:
# Append a dictionary to the user_data list
user_data.append({
'username': parts[0].strip(),
'email': parts[1].strip(),
'role': parts[2].strip()
})
else:
print(f"Skipping improperly formatted line: {line}")

except FileNotFoundError:
print(f"The file {file_path} was not found.")

return user_data

if __name__ == "__main__":
file_path = 'users.txt' # Path to your file
users = parse_user_data(file_path)
for user in users:
print(user)
```

### How the Script Works:

1. **Function `parse_user_data`:**
- The function takes `file_path` as an argument, which is the path to the text file.
- It initializes an empty list `user_data` to store the parsed user information.

2. **File Handling:**
- The `with` statement is used for opening the file. This ensures proper handling of the file (like automatic closing of the file) even if an error occurs.
- `open(file_path, 'r')` opens the file in read mode.

3. **Reading and Parsing Data:**
- The script iterates over each line in the file using a `for` loop.
- `line.strip().split(',')`: Strips any leading/trailing whitespace and then splits the line into parts using the comma as a separator.
- If the line has exactly three parts (username, email, role), it strips any extra spaces from each part and adds them to `user_data` as a dictionary.
- If a line is improperly formatted, it gets skipped with a message.

4. **Error Handling:**
- A `try-except` block is used to gracefully handle the scenario where the file does not exist (`FileNotFoundError`).

5. **Testing the Function:**
- In the script's main section, the function is called with the path to the `users.txt` file.
- It prints out each user's information.

This script gives you a practical understanding of handling file I/O operations and parsing text data in Python, which are essential skills in various applications, including data processing and system administration.


Exercise 3: Creating User Accounts using WMI

Objective: Utilize Python and WMI for user account creation on Windows.
Task: Extend the script from Exercise 2 to create user accounts in Windows using the parsed data. Handle any exceptions or errors gracefully.
Concepts Covered: WMI methods for user creation, error handling.
For Exercise 3, we'll extend the script from Exercise 2 to create user accounts in Windows using Python and WMI. This task will require the use of WMI methods to interact with the Windows operating system and create user accounts. Additionally, we'll handle any exceptions or errors gracefully.

Let's assume we have the following hardcoded user data, as we are not pulling from an external file in this exercise:

```python
users = [
{"username": "user1", "password": "pass1", "description": "User One"},
{"username": "user2", "password": "pass2", "description": "User Two"},
{"username": "user3", "password": "pass3", "description": "User Three"}
]
```

Here's a detailed Python script for creating user accounts:

```python
import wmi
import traceback

def create_user_account(c, username, password, description):
try:
# Use the Win32_UserAccount class
user = c.Win32_UserAccount.create(Name=username, Password=password, Description=description)
print(f"User account {username} created successfully.")
except Exception as e:
print(f"Error creating user {username}: {str(e)}")
traceback.print_exc()

def main(users):
c = wmi.WMI()

for user in users:
create_user_account(c, user['username'], user['password'], user['description'])

if __name__ == "__main__":
users = [
{"username": "user1", "password": "pass1", "description": "User One"},
{"username": "user2", "password": "pass2", "description": "User Two"},
{"username": "user3", "password": "pass3", "description": "User Three"}
]
main(users)
```

### How the Script Works:

1. **Function `create_user_account`:**
- This function takes a WMI connection object `c`, along with `username`, `password`, and `description`.
- It uses the `Win32_UserAccount` class to create a new user with the given details.
- If successful, it prints a confirmation message.
- In case of an exception (like if the user already exists), it prints an error message and the traceback for debugging.

2. **Function `main`:**
- Establishes a WMI connection.
- Iterates over the list of user dictionaries, calling `create_user_account` for each.

3. **Error Handling:**
- The script uses a `try-except` block in the `create_user_account` function to catch and handle any exceptions during the user creation process.

4. **Testing the Script:**
- The script is initialized with a hardcoded list of users.
- When run, it attempts to create each of these users on the system.

### Important Notes:

- **Administrator Privileges:** Running this script may require administrator privileges since it involves creating user accounts.
- **Security Concerns:** Hardcoding passwords, as done here for simplicity, is not a secure practice in real-world applications. In a professional environment, you would handle credentials securely.
- **System Impact:** This script will make changes to the system's user accounts. It should be run in a controlled environment, like a VM, to prevent unintended system modifications.

This exercise will help you understand how Python can be used alongside WMI for system administration tasks such as user account management.

Exercise 4: Assigning User Permissions and Roles

Objective: Master advanced WMI usage for managing user permissions.
Task: Develop a script to assign specific permissions or roles to the newly created user accounts, based on additional details provided in the input text file.
Concepts Covered: Permission management through WMI, conditional logic.

Instructions for manually creating a group in Windows:

Windows Management Instrumentation (WMI) itself does not provide direct capabilities for creating user groups in Windows.
WMI is primarily used for accessing management information and performing administrative tasks in Windows environments, but its scope in terms of creating or managing user groups is limited.
Creating a group manually can be done through the Windows interface or using command-line tools like PowerShell.
Here's how to do it in both ways:
### Creating a Group Using Windows Interface:
1. **Open Computer Management:** - Right-click on the Start button and select "Computer Management", or search for "Computer Management" in the Start menu.
2. **Navigate to Local Users and Groups:** - In the Computer Management window, expand "System Tools" in the left-hand pane. - Click on "Local Users and Groups".
3. **Create a New Group:** - Right-click on "Groups" and choose "New Group...". - Enter the name for the new group (e.g., "ExampleGroup") and add a description if needed. - Click "Create", and then "Close".
### Creating a Group Using PowerShell:
1. **Open PowerShell as Administrator:** - Right-click on the Start button and select "Windows PowerShell (Admin)" or search for PowerShell, right-click it and choose "Run as administrator".
2. **Use the `New-LocalGroup` Command:** - In the PowerShell window, type the following command: ```powershell New-LocalGroup -Name "ExampleGroup" -Description "This is an example group" ``` - Replace `"ExampleGroup"` with your desired group name and adjust the description accordingly. - Press Enter to execute the command.
### Things to Note:
- **Administrator Privileges:** Creating a group requires administrator privileges. Ensure you have the necessary permissions. - **Consistency:** If you're doing this in a classroom or lab setting, make sure everyone uses the same group name for consistency in following the script examples. - **Use in Scripts:** Once the group is created, you can refer to this group in your Python scripts for adding users to the group.
By providing these instructions, students can learn another important aspect of system administration—managing user groups—which is integral for organizing user permissions and roles in a Windows environment.
In Exercise 4, we will focus on assigning specific permissions and roles to user accounts in Windows using Python and WMI. For simplicity, we'll use hardcoded user data again, as we're not pulling data from a text file in these exercises. We'll build upon the previous script, incorporating the concept of managing permissions and roles.

However, it's important to note that WMI itself has limited capabilities in directly setting complex permissions and roles. Instead, WMI is typically used for gathering system information or performing basic system administration tasks. Advanced permission and role management often involves other tools and scripting methods, such as PowerShell, Group Policy Objects, or Active Directory services.

Given this limitation, we'll focus on a more achievable task using WMI: adding users to an existing group. Let's assume we have a group called "ExampleGroup" in which we want to add users.

Here's how you might script this:

```python
import wmi
import traceback

def add_user_to_group(c, username, groupname):
try:
# Fetch the user and group instances
user = c.Win32_UserAccount(Name=username)
group = c.Win32_Group(Name=groupname)

# Add user to the group
if user and group:
group[0].Add(user[0].Path_.Path)
print(f"User {username} added to group {groupname}.")
else:
print(f"User or Group not found: {username}, {groupname}")

except Exception as e:
print(f"Error adding user {username} to group {groupname}: {str(e)}")
traceback.print_exc()

def main(users, groupname):
c = wmi.WMI()

for user in users:
add_user_to_group(c, user['username'], groupname)

if __name__ == "__main__":
users = [
{"username": "user1"},
{"username": "user2"},
{"username": "user3"}
]
groupname = "ExampleGroup" # Replace with your actual group name
main(users, groupname)
```

### How the Script Works:

1. **Function `add_user_to_group`:**
- It takes a WMI connection `c`, a `username`, and a `groupname`.
- The function fetches the WMI objects for the specified user and group.
- It then adds the user to the group using the `Add` method.
- Error handling is implemented to gracefully manage any exceptions that occur during this process.

2. **Function `main`:**
- Establishes a WMI connection.
- Calls `add_user_to_group` for each user in the hardcoded list to add them to the specified group.

3. **Error Handling:**
- The `try-except` block in `add_user_to_group` catches any exceptions, providing error messages and stack traces for debugging.

4. **Testing the Script:**
- Modify `users` and `groupname` with appropriate values before running the script.

### Important Notes:

- **Administrator Privileges:** This script may require administrator privileges to modify user group memberships.
- **Group Existence:** Ensure the group you're trying to add users to exists on the system.
- **Security and System Impact:** As always, be aware of the security implications and potential system impact when running scripts that modify system configurations.

This exercise will give you a basic understanding of how user roles and permissions can be managed through scripting, albeit with the noted limitations of WMI in this area. For more advanced role and permission management, further exploration into PowerShell or Active Directory scripting would be necessary.

Exercise 5: Automation Script for Regular Administrative Tasks

Objective: Combine learned concepts to create a comprehensive automation script.
Task: Create a Python script that automates a series of administrative tasks (e.g., user creation, updating details, checking system health) and logs the actions taken.
Concepts Covered: Integrated WMI tasks, logging.

In Exercise 5, we'll integrate the concepts learned in the previous exercises to create a comprehensive Python script for automating various administrative tasks using WMI. The script will include functionalities like user creation, updating details, checking system health, and will also implement logging to record actions taken.

We'll use the `logging` module in Python for logging purposes. The script will be broken down into functions, each handling a specific task:

```python
import wmi
import logging
import traceback

# Initialize logging
logging.basicConfig(filename='admin_tasks_log.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def create_user_account(c, username, password, description):
try:
c.Win32_UserAccount.create(Name=username, Password=password, Description=description)
logging.info(f"User account {username} created successfully.")
except Exception as e:
logging.error(f"Error creating user {username}: {str(e)}")
traceback.print_exc()
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.