Share
Explore

Hands-on Python programming class focused on Windows administration tasks:

How to do this Lab: Do all exercises
Make a Word Document: saved as StudentName_StudentID.docx
An upload link will be provided:

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

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]


# 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]

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

# 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 ``` [citation:6]
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 = wmi.WMI() for processor in c.Win32_Processor(): print(f"Processor Name: {processor.Name}") print(f"Number of Cores: {processor.NumberOfCores}") print(f"Clock Speed: {processor.MaxClockSpeed} MHz") ``` [citation:5][citation:7]
2. Retrieving Memory Information: ```python 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") ``` [citation:5][citation:7]
3. 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]


# Hands-on Exercise 2: Managing Files and Directories

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


Lecture Content
Hey there, Windows administration wizards! 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


# Hands-on Exercise 4: Scheduling Tasks and Scripts

## Lecture Content
Alright, folks, let's dive into the world of task scheduling and automation using Python! In this exercise, we'll explore how to use the `sched` module to schedule tasks, create scripts to automate recurring administration tasks, and configure scripts to run at specific times or intervals. [citation:6][citation:11]
### Using Python's `sched` module to schedule tasks
First up, let's talk about the `sched` module. This module allows you to schedule the execution of tasks at specific times or intervals. It provides a simple way to create a task scheduler within your Python scripts. Here's a basic example:
```python import sched import time
def task(): print("Running scheduled task...")
scheduler = sched.scheduler(time.time, time.sleep) delay = 5 # Schedule the task to run after 5 seconds scheduler.enter(delay, 1, task)
print("Starting the scheduler...") scheduler.run() print("Scheduler finished.") ```
In this example, we define a function called `task` that represents the task we want to schedule. We create an instance of the `scheduler` class, specifying the `time.time` function for the current time and the `time.sleep` function for delaying execution. We then use the `enter` method to schedule the `task` function to run after a delay of 5 seconds. Finally, we start the scheduler with the `run` method. [citation:6][citation:10]
### Creating scripts to automate recurring administration tasks
Now, let's explore how to create scripts to automate recurring administration tasks. Let's say you want to automate the backup of important files every day at a specific time. Here's an example script:
```python import sched import time import shutil
def backup_files(): source_dir = "C:\\important_files" destination_dir = "D:\\backups" timestamp = time.strftime("%Y%m%d_%H%M%S") backup_dir = f"{destination_dir}\\backup_{timestamp}" shutil.copytree(source_dir, backup_dir) print(f"Files backed up to {backup_dir}")
scheduler = sched.scheduler(time.time, time.sleep) backup_time = "18:00" # Schedule the backup for 6:00 PM daily
while True: current_time = time.strftime("%H:%M") if current_time == backup_time: scheduler.enter(0, 1, backup_files) scheduler.run(blocking=False) time.sleep(60) # Check every minute ```
In this script, we define a function called `backup_files` that performs the backup operation. It copies the files from the `source_dir` to a timestamped directory in the `destination_dir`. We create an instance of the `scheduler` class and specify the desired backup time (`backup_time`). We then enter an infinite loop that checks the current time every minute. If the current time matches the `backup_time`, we schedule the `backup_files` function to run immediately using `scheduler.enter`. We run the scheduler with `blocking=False` to allow the loop to continue executing. [citation:6][citation:11]
### Configuring scripts to run at specific times or intervals
Lastly, let's explore how to configure scripts to run at specific times or intervals using the `sched` module. Here's an example script that demonstrates running a task every 30 minutes:
```python import sched import time
def task(): print("Running scheduled task...")
scheduler = sched.scheduler(time.time, time.sleep) interval = 30 * 60 # 30 minutes in seconds
def schedule_task(): scheduler.enter(interval, 1, task) scheduler.enter(interval, 2, schedule_task)
schedule_task() print("Starting the scheduler...") scheduler.run() ```
In this script, we define a `task` function that represents the task to be executed. We create an instance of the `scheduler` class and specify the desired interval (`interval`) in seconds. We then define a `schedule_task` function that schedules the `task` function to run after the specified interval and also schedules itself to run again after the same interval. This creates a recursive scheduling pattern, ensuring that the task runs every 30 minutes indefinitely. Finally, we call the `schedule_task` function to initiate the scheduling and start the scheduler with `scheduler.run()`. [citation:6][citation:11]
## Code Drills
Now it's time to put your task scheduling skills to the test! Let's go through some code drills to practice what we've learned.
1. Create a script that schedules a task to run every hour. ```python import sched import time
# Write your code here to schedule a task to run every hour ```
2. Modify the script to run the task every day at a specific time (e.g., 9:00 AM). ```python import sched import time
# Write your code here to schedule a task to run every day at 9:00 AM ```
3. Create a script that schedules multiple tasks to run at different intervals. ```python import sched import time
# Write your code here to schedule multiple tasks at different intervals ```
4. Develop a script that automates a specific administration task (e.g., cleaning up temporary files) and schedules it to run weekly. ```python import sched import time import os
# Write your code here to automate cleaning up temporary files and schedule it to run weekly ```
Take your time, experiment, and have fun with the code drills! Feel free to refer to the lecture content and the Python documentation for guidance. [citation:3][citation:6]
Remember, the `sched` module is just one way to schedule tasks in Python. There are other libraries and tools available, such as the `schedule` library and the built-in `cron` utility on Unix-based systems, which offer more advanced scheduling capabilities. [citation:9][citation:10]
By mastering task scheduling and automation with Python, you'll be able to streamline your Windows administration workflows and save valuable time. Keep exploring and automating! [citation:4][citation:11]


# Hands-on Exercise 5: Monitoring System Performance

## Lecture Content
Alright, let's dive into the world of system performance monitoring using Python! In this exercise, we'll explore how to use Python to monitor CPU usage, memory consumption, and disk space, collect performance metrics, generate reports, and set up alerts and notifications for critical thresholds. [citation:4][citation:7]
### Monitoring CPU Usage, Memory Consumption, and Disk Space
First, let's talk about monitoring CPU usage, memory consumption, and disk space using Python. We'll be using the `psutil` library, which provides cross-platform utilities for retrieving information about running processes and system utilization. Here's how you can monitor these metrics:
```python import psutil
# Monitoring CPU usage cpu_percent = psutil.cpu_percent() print(f"CPU Usage: {cpu_percent}%")
# Monitoring memory consumption memory = psutil.virtual_memory() print(f"Memory Usage: {memory.used} bytes") print(f"Memory Usage Percentage: {memory.percent}%")
# Monitoring disk space disk = psutil.disk_usage('/') print(f"Disk Usage: {disk.used} bytes") print(f"Disk Usage Percentage: {disk.percent}%") ```
In this code snippet, we use the `psutil` library to retrieve CPU usage percentage, memory consumption (in bytes and percentage), and disk space usage (in bytes and percentage). [citation:4][citation:5]
### Collecting Performance Metrics and Generating Reports
Now, let's explore how to collect performance metrics and generate reports using Python. We'll build upon the previous example and introduce the `csv` module to store the collected metrics in a CSV file. Here's an example:
```python import psutil import csv import time
def collect_metrics(): cpu_percent = psutil.cpu_percent() memory = psutil.virtual_memory() disk = psutil.disk_usage('/')
metrics = { 'timestamp': time.strftime("%Y-%m-%d %H:%M:%S"), 'cpu_percent': cpu_percent, 'memory_used': memory.used, 'memory_percent': memory.percent, 'disk_used': disk.used, 'disk_percent': disk.percent }
return metrics
def generate_report(metrics): with open('performance_report.csv', 'a', newline='') as file: writer = csv.DictWriter(file, fieldnames=metrics.keys())
if file.tell() == 0: writer.writeheader()
writer.writerow(metrics)
# Collect metrics every 5 seconds and generate a report while True: metrics = collect_metrics() generate_report(metrics) time.sleep(5) ```
In this script, we define two functions: `collect_metrics` and `generate_report`. The `collect_metrics` function retrieves the CPU usage, memory consumption, and disk space metrics using `psutil` and returns them as a dictionary. The `generate_report` function takes the collected metrics and appends them to a CSV file named `performance_report.csv`. We use the `csv` module to write the metrics as rows in the CSV file, with the keys as headers. The script runs in an infinite loop, collecting metrics every 5 seconds and generating a report. [citation:4][citation:7]
### Setting Up Alerts and Notifications for Critical Thresholds
Lastly, let's explore how to set up alerts and notifications for critical thresholds using Python. We'll extend the previous example and introduce the `logging` module to log alerts when the metrics exceed certain thresholds. Here's an example:
```python import psutil import csv import time import logging
# Configure logging logging.basicConfig(filename='performance_alerts.log', level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s')
def collect_metrics(): # ...
def generate_report(metrics): # ...
def check_thresholds(metrics): cpu_threshold = 90 memory_threshold = 80 disk_threshold = 90
if metrics['cpu_percent'] > cpu_threshold: logging.warning(f"CPU usage exceeded threshold: {metrics['cpu_percent']}%")
if metrics['memory_percent'] > memory_threshold: logging.warning(f"Memory usage exceeded threshold: {metrics['memory_percent']}%")
if metrics['disk_percent'] > disk_threshold: logging.warning(f"Disk usage exceeded threshold: {metrics['disk_percent']}%")
# Collect metrics every 5 seconds, generate a report, and check thresholds while True: metrics = collect_metrics() generate_report(metrics) check_thresholds(metrics) time.sleep(5) ```
In this extended script, we introduce the `check_thresholds` function that compares the collected metrics against predefined thresholds for CPU usage, memory usage, and disk usage. If any of the metrics exceed their respective thresholds, a warning message is logged using the `logging` module. The logged alerts are stored in a file named `performance_alerts.log`. The script continues to run in an infinite loop, collecting metrics, generating reports, and checking thresholds every 5 seconds. [citation:4][citation:7]
## Code Drills
Now it's time to put your system performance monitoring skills to the test! Let's go through some code drills to practice what we've learned.
1. Modify the script to collect and display network usage metrics using `psutil`. ```python import psutil
# Write your code here to collect and display network usage metrics ```
2. Enhance the `generate_report` function to include additional system information, such as the number of running processes and the system uptime. ```python import psutil
def generate_report(metrics): # Write your code here to include additional system information in the report ```
3. Extend the `check_thresholds` function to send email notifications when critical thresholds are exceeded. ```python import psutil import smtplib
def check_thresholds(metrics): # Write your code here to send email notifications when thresholds are exceeded ```
4. Create a script that monitors the performance of a specific process and logs its resource usage over time. ```python import psutil import logging
# Write your code here to monitor the performance of a specific process and log its resource usage ```
Take your time, experiment, and have fun with the code drills! Feel free to refer to the lecture content and the `psutil` documentation for guidance. [citation:3][citation:6]
Remember, monitoring system performance is crucial for ensuring the smooth operation of your Windows environment. By leveraging Python and libraries like `psutil`, you can automate the collection of performance metrics, generate insightful reports, and set up alerts to proactively identify and address performance issues. [citation:4][citation:7]
Keep exploring and monitoring! Happy coding! [citation:11]
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.