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:
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.