Share
Explore

Using PYTHON to gather computer system information

Hands-on Exercise 1: Gathering System Information
To provide a comprehensive report on all hardware attributes of a computer, we can use the `wmi` module for Windows, along with other modules such as `psutil` for cross-platform support. Below is a Python script that gathers information about the RAM memory, hard drive space, CPU specifications, and I/O ports. This script can be extended to include additional hardware attributes as needed.
### Comprehensive Hardware Report Script
import wmi import psutil
def get_ram_info(): """Get information about RAM""" ram = psutil.virtual_memory() return { 'total': ram.total, 'available': ram.available, 'percent': ram.percent, 'used': ram.used, 'free': ram.free }
def get_disk_info(): """Get information about disk""" partitions = psutil.disk_partitions() disk_info = [] for partition in partitions: usage = psutil.disk_usage(partition.mountpoint) disk_info.append({ 'device': partition.device, 'mountpoint': partition.mountpoint, 'fstype': partition.fstype, 'total': usage.total, 'used': usage.used, 'free': usage.free, 'percent': usage.percent }) return disk_info
def get_cpu_info(): """Get information about CPU""" cpu_info = { 'physical_cores': psutil.cpu_count(logical=False), 'total_cores': psutil.cpu_count(logical=True), 'max_frequency': psutil.cpu_freq().max, 'min_frequency': psutil.cpu_freq().min, 'current_frequency': psutil.cpu_freq().current, 'cpu_usage': psutil.cpu_percent(interval=1) } return cpu_info
def get_io_ports(): """Get information about I/O ports (USB)""" c = wmi.WMI() usb_info = [] for usb in c.Win32_USBController(): usb_info.append({ 'device_id': usb.DeviceID, 'name': usb.Name, 'manufacturer': usb.Manufacturer, 'status': usb.Status }) return usb_info
def get_network_info(): """Get information about network interfaces""" c = wmi.WMI() network_info = [] for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=True): network_info.append({ 'description': interface.Description, 'mac_address': interface.MACAddress, 'ip_address': interface.IPAddress, 'ip_subnet': interface.IPSubnet, 'default_ip_gateway': interface.DefaultIPGateway }) return network_info
def main(): """Main function to gather all hardware info""" print("Gathering RAM information...") ram_info = get_ram_info() print(ram_info)
print("\nGathering Disk information...") disk_info = get_disk_info() for disk in disk_info: print(disk)
print("\nGathering CPU information...") cpu_info = get_cpu_info() print(cpu_info)
print("\nGathering USB Ports information...") usb_info = get_io_ports() for usb in usb_info: print(usb)
print("\nGathering Network information...") network_info = get_network_info() for network in network_info: print(network)
if __name__ == "__main__": main()
### Explanation of the Script - **RAM Information**: Uses `psutil.virtual_memory()` to get total, available, used, and free RAM. - **Disk Information**: Uses `psutil.disk_partitions()` and `psutil.disk_usage()` to get information about all disk partitions. - **CPU Information**: Uses `psutil.cpu_count()` and `psutil.cpu_freq()` to get the number of cores and CPU frequency. - **USB Ports**: Uses `wmi` to get information about USB controllers. - **Network Interfaces**: Uses `wmi` to get details about network interfaces.
### Additional Attributes You can extend this script to gather more hardware attributes such as: - **Graphics Card Information**: Use `wmi` to get details about the graphics card. - **Battery Status**: For laptops, use `psutil.sensors_battery()`. - **BIOS Information**: Use `wmi` to get BIOS version and manufacturer.
Feel free to expand the script based on the specific requirements or additional hardware components you need to report on.

megaphone

Lab Exercise 2

Let's expand the disk information retrieval section to be more comprehensive, combining it with the existing code structure. The detailed implementation will gather and print out information about each logical disk, including the disk name, total size, and free space, as specified in the provided code snippet.
### Comprehensive Python Script to Report on Hardware Attributes
```python import wmi import psutil
def get_ram_info(): """Get information about RAM""" ram = psutil.virtual_memory() return { 'total': ram.total, 'available': ram.available, 'percent': ram.percent, 'used': ram.used, 'free': ram.free }
def get_disk_info(): """Get information about logical disks""" c = wmi.WMI() disks = [] for disk in c.Win32_LogicalDisk(DriveType=3): disks.append({ 'name': disk.Name, 'total_size': int(disk.Size) // (1024**3), # GB 'free_space': int(disk.FreeSpace) // (1024**3) # GB }) return disks
def get_cpu_info(): """Get information about CPU""" cpu_info = { 'physical_cores': psutil.cpu_count(logical=False), 'total_cores': psutil.cpu_count(logical=True), 'max_frequency': psutil.cpu_freq().max, 'min_frequency': psutil.cpu_freq().min, 'current_frequency': psutil.cpu_freq().current, 'cpu_usage': psutil.cpu_percent(interval=1) } return cpu_info
def get_io_ports(): """Get information about I/O ports (USB)""" c = wmi.WMI() usb_info = [] for usb in c.Win32_USBController(): usb_info.append({ 'device_id': usb.DeviceID, 'name': usb.Name, 'manufacturer': usb.Manufacturer, 'status': usb.Status }) return usb_info
def get_network_info(): """Get information about network interfaces""" c = wmi.WMI() network_info = [] for interface in c.Win32_NetworkAdapterConfiguration(IPEnabled=True): network_info.append({ 'description': interface.Description, 'mac_address': interface.MACAddress, 'ip_address': interface.IPAddress, 'ip_subnet': interface.IPSubnet, 'default_ip_gateway': interface.DefaultIPGateway }) return network_info
def print_info(title, info): """Helper function to print formatted information""" print(f"\n{title}") print("=" * len(title)) if isinstance(info, list): for item in info: for key, value in item.items(): print(f"{key}: {value}") print("-" * 20) else: for key, value in info.items(): print(f"{key}: {value}")
def main(): """Main function to gather all hardware info""" print("Gathering system information...")
ram_info = get_ram_info() print_info("RAM Information", ram_info)
disk_info = get_disk_info() print_info("Disk Information", disk_info)
cpu_info = get_cpu_info() print_info("CPU Information", cpu_info)
usb_info = get_io_ports() print_info("USB Ports Information", usb_info)
network_info = get_network_info() print_info("Network Information", network_info)
if __name__ == "__main__": main() ```
### Explanation
- **RAM Information**: Gathered using `psutil.virtual_memory()`. - **Disk Information**: Uses `wmi.WMI()` to get logical disk information including name, total size, and free space. - **CPU Information**: Gathered using `psutil` to get the number of cores and frequency. - **USB Ports**: Uses `wmi` to get information about USB controllers. - **Network Interfaces**: Uses `wmi` to get details about network interfaces.
### Helper Function
- **print_info**: This helper function formats and prints the gathered information. It handles both dictionaries and lists of dictionaries.
This script provides a comprehensive overview of the computer's hardware attributes and can be extended to include other hardware components as needed.


megaphone
Lab 3: Managing Files and Directories
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.
### 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.
### Script: Managing Files and Directories
Here's a Python script that demonstrates how to use these functions in a more structured and functional way:
```python import os import shutil
def get_current_directory(): """Returns the current working directory.""" return os.getcwd()
def list_directory_contents(path='.'): """Returns a list of files and directories in the specified path.""" return os.listdir(path)
def create_directory(path): """Creates a new directory at the specified path.""" try: os.mkdir(path) return f"Directory '{path}' created successfully." except FileExistsError: return f"Directory '{path}' already exists." except Exception as e: return str(e)
def delete_file(path): """Deletes a file at the specified path.""" try: os.remove(path) return f"File '{path}' deleted successfully." except FileNotFoundError: return f"File '{path}' not found." except Exception as e: return str(e)
def delete_directory(path): """Deletes an empty directory at the specified path.""" try: os.rmdir(path) return f"Directory '{path}' deleted successfully." except FileNotFoundError: return f"Directory '{path}' not found." except OSError: return f"Directory '{path}' is not empty." except Exception as e: return str(e)
def rename_file_or_directory(src, dst): """Renames a file or directory from the source path to the destination path.""" try: os.rename(src, dst) return f"'{src}' renamed to '{dst}' successfully." except FileNotFoundError: return f"'{src}' not found." except Exception as e: return str(e)
def copy_file(src, dst): """Copies a file from the source path to the destination path.""" try: shutil.copy(src, dst) return f"'{src}' copied to '{dst}' successfully." except FileNotFoundError: return f"'{src}' not found." except Exception as e: return str(e)
def main(): print("Current Directory:", get_current_directory()) path = input("Enter the directory path to list contents (default is current directory): ") or '.' print("Directory Contents:", list_directory_contents(path)) dir_to_create = input("Enter the directory path to create: ") if dir_to_create: print(create_directory(dir_to_create)) file_to_delete = input("Enter the file path to delete: ") if file_to_delete: print(delete_file(file_to_delete)) dir_to_delete = input("Enter the directory path to delete: ") if dir_to_delete: print(delete_directory(dir_to_delete)) src_to_rename = input("Enter the source path to rename: ") dst_to_rename = input("Enter the destination path to rename to: ") if src_to_rename and dst_to_rename: print(rename_file_or_directory(src_to_rename, dst_to_rename)) src_to_copy = input("Enter the source file path to copy: ") dst_to_copy = input("Enter the destination file path to copy to: ") if src_to_copy and dst_to_copy: print(copy_file(src_to_copy, dst_to_copy))
if __name__ == "__main__": main() ```
### Explanation
- **Modular Functions**: Each function is responsible for a specific task, making the code easy to understand and maintain. - **Error Handling**: Each function includes basic error handling to manage common issues such as file not found or directory not empty. - **Interactive Main Function**: The `main` function interacts with the user, allowing them to specify paths for various operations.
This structured approach ensures that each operation is handled separately, and it makes the script more readable and maintainable.


megaphone

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
Hello Windows administration wizards! In this exercise, we’ll dive into automating user management tasks using Python. We'll be leveraging the `win32api` and `win32net` modules from the `pywin32` library to interact with the Windows API.
### Creating, Modifying, and Deleting User Accounts
First, let's talk about managing user accounts using Python. We'll use the `win32net` module to create, modify, and delete user accounts.
#### Code Snippet for User Account Management
```python 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}")
# Example usage create_user("johndoe", "P@ssw0rd") modify_user("johndoe", "John Doe") delete_user("johndoe") ```
### Managing User Groups and Permissions
Next, 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.
#### Code Snippet for Group Management
```python import win32net
def add_user_to_group(username, group_name): """Adds a user to a specified group.""" user_group_info = { "domainandname": username } try: 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}")
def remove_user_from_group(username, group_name): """Removes a user from a specified group.""" user_group_info = { "domainandname": username } try: 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}")
# Example usage add_user_to_group("johndoe", "Administrators") remove_user_from_group("johndoe", "Administrators") ```
### Generating Reports on User Activities and Login History
Finally, let's 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.
#### Code Snippet for Generating Reports
```python import win32evtlog
def generate_login_report(): """Generates a report on user login activities.""" 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]
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)
# Example usage generate_login_report() ```
### 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
def create_user(username, password): 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}")
create_user("janedoe", "S3cur3P@ss") ```
2. **Modify the full name of the user "janedoe" to "Jane Doe".** ```python import win32net
def modify_user(username, new_full_name): 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}")
modify_user("janedoe", "Jane Doe") ```
3. **Add the user "janedoe" to the "Users" group.** ```python import win32net
def add_user_to_group(username, group_name): user_group_info = { "domainandname": username } try: 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}")
add_user_to_group("janedoe", "Users") ```
### Conclusion
By following this structured exercise, you should now be able to automate various user management tasks using Python. Keep practicing to master these skills and explore additional functionalities provided by the `pywin32` library. Happy coding!
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.