Skip to main content

A comprehensive Python automation toolkit for Windows

Project description

pyautomatic

python模块

模块列表

  • windows
  • rs1
  • pt (print的彩色输出)
  • math
  • download
  • disk
  • ntdll (目前在测试中,也是目前最硬核的)
  • [] mail
  • [] image

安装

pip install pyautomatic

使用

import pyautomatic

功能

1. windows

1.系统信息获取

# windows.windows
from pyautomatic.windows.main.windows import Windows

# 获取系统信息
sys_info = Windows.get_system_info()
print("计算机名:", sys_info.get('computer_name'))
print("总内存:", sys_info.get('total_ram'))
print("内存使用率:", sys_info.get('ram_usage_percent'), "%")

# 获取进程列表
# 按内存使用率排序(默认)
processes = Windows.get_process_list()
# 按CPU使用率排序
# processes = Windows.get_process_list(sort_by_memory=False)

for proc in processes[:5]:  # 显示前5个进程
    print(f"PID: {proc['pid']}, 名称: {proc['name']}, 内存占用: {proc['memory_mb']}MB")

# 获取系统运行时间
uptime = Windows.get_system_uptime()
print("系统启动时间:", uptime['boot_time'])
print("运行时长:", uptime['uptime_formatted'])

2.系统操作

# windows.windows
from pyautomatic.windows.main.windows import Windows

# 锁定工作站
Windows.lock_workstation()  # 锁定电脑

# 关机/重启
# 立即关机(force=True强制关闭所有程序)
Windows.system_shutdown(force=True)

# 5分钟后重启
Windows.system_shutdown(reboot=True, timer=300, reason="系统更新") #timer以秒为单位

# 取消关机计划
Windows.cancel_shutdown()

# 设置壁纸

success = Windows.set_wallpaper("C:/images/wallpaper.jpg")
print("壁纸设置成功" if success else "壁纸设置失败")

# 关闭屏幕
Windows.turn_off_screen() # trun_on_screen()打开屏幕

# 设置为纵向显示
Windows.set_screen_orientation('portrait')

# 设置分辨率为1920x1080,刷新率为60Hz
Windows.set_resolution(1920, 1080, 60)

# 获取所有可用分辨率
resolutions = Windows.get_available_resolutions()

# 恢复默认设置
Windows.restore_default_display_settings()

3.文件与注册表操作

# windows.windows or windows.reg
from pyautomatic.windows.main.windows import Windows
from pyautomatic.windows.main.reg import RegistryManager
import os

# 获取文件属性
file_props = Windows.get_file_properties("C:/Program Files/python.exe")
print("文件大小:", file_props['size_formatted'])
print("修改时间:", file_props['modified_formatted'])
print("版本号:", file_props['file_version'])

# 创建快捷方式
# 在桌面创建Python的快捷方式
Windows.create_shortcut(
    target="C:/Python39/python.exe",
    shortcut_path="C:/Users/用户名/Desktop/Python.lnk",
    description="Python解释器"
)

# 注册表读写
# 读取注册表值(例如获取IE版本)
ie_version = Windows.get_registry_value(
    key="HKEY_LOCAL_MACHINE",
    subkey="Software\\Microsoft\\Internet Explorer",
    value_name="Version"
)
print("IE版本:", ie_version)

reg = Registry()
# 读取启动程序列表(用户级)
startup_programs = reg.get_startup_programs(user_scope=True)
for name, path in startup_programs:
    print(f"启动项: {name}, 路径: {path}")

# 列出注册表键下所有值
with reg.open_key(reg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows") as key:
    values = key.list_values()
    for name, type_, value in values:
        print(f"值名称: {name}, 类型: {type_}, 内容: {value}")

4.媒体播放类

# windows.media
from pyautomatic.windows.main.media import MediaController

# 必须先初始化
media = MediaController()
# 音量管理
media.volume_up()  # 增加音量
media.volume_down()  # 降低音量
current_vol = media.get_volume()  # 获取当前音量(0-100)
print("当前音量:", current_vol)
# 播放控制
media.next_track()  # 下一首
media.previous_track()  # 上一首
# 获取播放信息
# 获取Windows Media Player播放信息
wmp_info = media._get_wmp_info()
if wmp_info:
    print(f"正在播放: {wmp_info['artist']} - {wmp_info['title']}")
    print(f"进度: {wmp_info['current_time_str']}/{wmp_info['duration_str']}")

# 获取AIMP播放信息
aimp_info = media._get_aimp_info()
# 获取foobar2000播放信息
foobar_info = media._get_foobar2000_info()

5.ui控件与样式

# windows.ui
from pyautomatic.windows.main.ui import *

# 样式管理(Style类)
# 获取颜色值(返回RGB整数)
white = ui.Style.get_color('white')
blue = ui.Style.get_color('blue')

# 获取字体信息(返回字体名、大小等元组)
title_font = ui.Style.get_font('title')  # ('Microsoft YaHei', 14, True)

# 获取预定义样式
success_style = ui.Style.get_style('success')  # {'bg_color': 'green', 'text_color': 'white', ...}

# 自定义信息存储(CustomInfo类)
info = ui.CustomInfo()
info.set('user_id', 123)  # 设置值
user_id = info.get('user_id')  # 获取值
info.remove('user_id')  # 删除值

# 基础控件(Control类)
# 创建控件(需传入父窗口等参数)
btn = ui.Control(
    parent=parent_hwnd,
    x=10, y=10,
    width=100, height=30
)
btn.create()  # 创建控件(子类需重写)

# 绑定事件
def on_click():
    print("按钮被点击")
btn.bind_event('click', on_click)

# 设置控件属性
btn.set_text("点击我")
btn.set_enabled(True)  # 启用控件
btn.set_visible(True)  # 显示控件

# 文件选择对话框
# 选择图片文件
file_path = ui.select_file(
    title="选择图片",
    filetypes=[("图片文件", "*.jpg;*.png;*.bmp")],
    initial_dir="C:/Pictures"
)
if file_path:
    print("选中文件:", file_path)

6.bluetooth

# windows.bluetooth
from pyautomatic.windows.main.bluetooth import BluetoothManager, TransferPriority

# 创建蓝牙管理器实例
bt = BluetoothManager()

# 检查蓝牙是否启用
if not bt.is_bluetooth_enabled():
    print("Enabling Bluetooth...")
    if not bt.enable_bluetooth():
        print("Failed to enable Bluetooth")
        exit(1)

# 发现附近的设备
print("Scanning for devices...")
devices = bt.discover_devices(duration=10)
if not devices:
    print("No devices found")
    exit(1)

# 显示发现的设备
print("\nFound devices:")
for i, device in enumerate(devices):
    print(f"{i+1}. {device.name} (ID: {device.id})")

# 选择要连接的设备
try:
    choice = int(input("\nSelect device number: ")) - 1
    if choice < 0 or choice >= len(devices):
        print("Invalid selection")
        exit(1)
    selected_device = devices[choice]
except ValueError:
    print("Invalid input")
    exit(1)

# 配对设备
print(f"\nPairing with {selected_device.name}...")
if not bt.pair_device(selected_device.id):
    print("Pairing failed")
    exit(1)

# 连接设备
print("Connecting to device...")
if not bt.connect_device(selected_device.id):
    print("Connection failed")
    exit(1)

# 优化连接
print("Optimizing connection...")
bt.optimize_connection(selected_device.id)

# 发送文件示例
file_path = input("\nEnter file path to send: ")
if os.path.exists(file_path):
    print(f"Sending {file_path}...")
    if bt.send_file(selected_device.id, file_path, TransferPriority.HIGH):
        print("File sent successfully")
        
        # 监控传输进度
        while True:
            stats = bt.get_transfer_stats(selected_device.id)
            if stats:
                progress = (stats['transferred'] / stats['total_size']) * 100
                speed = stats['speed'] / (1024 * 1024)  # MB/s
                print(f"\rProgress: {progress:.1f}% | Speed: {speed:.2f} MB/s", end="")
                if stats['transferred'] >= stats['total_size']:
                    break
            time.sleep(1)
        print("\nTransfer completed!")
    else:
        print("File transfer failed")
else:
    print("File not found")

# 断开连接
print("\nDisconnecting from device...")
bt.disconnect_device(selected_device.id)

7.网络操控

基础网络操作

# windows.net
from pyautomatic.windows.main.net import *
# 创建网络处理器
net_handler = net.WinNetHandler(timeout=5)

# 获取本机IP地址
local_ips = net_handler.get_local_ip()
print(f"本机IP地址: {local_ips}")

# 获取网络接口信息
interfaces = net_handler.get_network_interfaces()
for interface in interfaces:
    print(f"网络接口: {interface}")

# 检查端口状态
is_open = net_handler.check_port("www.baidu.com", 80)
print(f"端口状态: {'开放' if is_open else '关闭'}")

# Ping测试
ping_result = net_handler.ping("8.8.8.8", count=4)
print(f"Ping结果: {ping_result}")

# 开始捕获数据包
if net_handler.start_capture():
    print("开始捕获数据包...")
    time.sleep(10)  # 捕获10秒
    packets = net_handler.get_captured_packets()
    print(f"捕获到 {len(packets)} 个数据包")
    net_handler.stop_capture()

VPN管理示例

# windows.net
from pyautomatic.windows.main.net import *
# 创建VPN管理器
vpn_manager = net.VPNManager()

# 创建VPN连接
if vpn_manager.create_vpn_connection(
    name="MyVPN",
    server="vpn.example.com",
    username="your_username",
    password="your_password",
    vpn_type="L2TP"
):
    print("VPN连接创建成功")

# 连接VPN
if vpn_manager.connect_vpn("MyVPN"):
    print("VPN连接成功")
    
    # 开始流量监控
    vpn_manager.start_traffic_monitoring()
    
    # 获取VPN状态
    status = vpn_manager.get_vpn_status("MyVPN")
    print(f"VPN状态: {status}")
    
    # 获取流量统计
    time.sleep(5)  # 监控5秒
    traffic = vpn_manager.get_traffic_stats()
    print(f"流量统计: {traffic}")
    
    # 断开VPN
    vpn_manager.disconnect_vpn("MyVPN")
    print("VPN已断开")

网络安全管理示例

# windows.net
from pyautomatic.windows.main.net import *
# 创建安全管理器
security_manager = NetworkSecurityManager()

# 添加防火墙规则
if security_manager.add_firewall_rule(
    name="BlockMaliciousIP",
    direction="in",
    protocol="TCP",
    remote_addr="192.168.1.100",
    action="block"
):
    print("防火墙规则添加成功")

# 设置系统代理
if security_manager.set_system_proxy(
    server="proxy.example.com",
    port="8080",
    bypass="localhost;127.0.0.1"
):
    print("系统代理设置成功")

# 开始监控网络连接
security_manager.start_connection_monitoring()
print("开始监控网络连接...")

# 监控一段时间
time.sleep(60)  # 监控60秒

# 获取可疑连接
suspicious = security_manager.get_suspicious_connections()
if suspicious:
    print("发现可疑连接:")
    for conn in suspicious:
        print(f"- 类型: {conn['type']}")
        print(f"  连接: {conn['connection']}")
        print(f"  次数: {conn['count']}")
        
        # 自动阻止可疑IP
        if 'connection' in conn:
            ip = conn['connection'].split(':')[0]
            if security_manager.block_suspicious_ip(ip):
                print(f"已阻止可疑IP: {ip}")

# 停止监控
security_manager.stop_connection_monitoring()
print("监控已停止")

8.disk操控

from pyautomatic.windows.driver import disk
模块级函数
# 错误与权限
error_code = disk.get_last_error()
message = disk.format_error_code(error_code)
is_admin = disk.check_disk_access()

# 设备类型判断
is_physical = disk.is_physical_disk(r"\\.\PhysicalDrive0")
is_logical = disk.is_logical_volume(r"\\.\C:")

# 读写磁盘设备
handle = disk.OpenDisk(r"\\.\PhysicalDrive0", read_only=True)
sectors = disk.ReadDisk(handle, 0, 1)
# disk.WriteDisk(handle, 0, b"...")

# 数据编码 / 解码
raw = disk.hex_string_to_bytes("DE AD BE EF")
hex_text = disk.bytes_to_hex_string(raw)

# 设备枚举
physical_disks = disk.get_all_physical_disks()
logical_volumes = disk.get_all_logical_volumes()
all_devices = disk.get_all_disk_devices()

# 格式化大小
size_text = disk.format_size(1024 * 1024 * 1024)
DiskDevice 支持的方法
# 打开与关闭
dev.open(access=disk.DiskAccess.READ_ONLY, exclusive=False)
dev.close()

# 设备信息
dev.get_human_readable_size()
dev.seek(offset, disk.FILE_BEGIN)
dev.tell()

# 卷锁定与卸载
dev.lock_volume()
dev.unlock_volume()
dev.dismount_volume()

# 写保护检查
dev.is_write_protected()

# 扇区与字节读写
dev.read_sectors(start_sector, num_sectors=1)
dev.write_sectors(start_sector, data)
dev.read_bytes(offset, size)
dev.write_bytes(offset, data)
dev.verify_sectors(start_sector, num_sectors=1)

# 分区、签名与校验
dev.get_partition_info()
dev.get_disk_signature()
dev.calculate_hash("md5")

# 备份与恢复
dev.create_backup(output_file, sectors=None)
dev.restore_backup(input_file, start_sector=0)

# 填充与擦除
dev.fill_pattern(pattern, start_sector=0, num_sectors=None)
dev.secure_erase(passes=1)

# 搜索与扫描
dev.scan_for_pattern(pattern, start_sector=0, max_sectors=1000)

# 获取详细信息
dev.get_detailed_info()
可用类型
  • DiskAccess
  • DiskSectorSize
  • DiskType
  • DiskGeometry
  • PartitionInfo
快速示例
from pyautomatic.windows.driver import disk

for device_path, description in disk.get_all_disk_devices():
    print(device_path, description)

with disk.OpenDisk(r"\\.\PhysicalDrive0", read_only=True) as dev:
    print(dev.get_detailed_info())
    mbr = dev.read_sectors(0, 1)
    print(disk.bytes_to_hex_string(mbr, bytes_per_line=16))

2.rs1

1.加密

# rs1
from pyautomatic.rs1 import encrypt, decrypt
original = "Hello, World!"
password = "my_secret_password"
# 加密
encrypted = encrypt(original, password)
print("加密结果:", encrypted)

2.解密

# rs1
from pyautomatic.rs1 import encrypt, decrypt
encrypted = "wCbDTl8XOQV4ND6MHiC3pvCC6ToEtwH1zAhxRW0ORtYEKjlDbkm1PKOHmllEnUMz:dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"
password = "my_secret_password"
# 解密
decrypted = decrypt(encrypted, password)
print("解密结果:", decrypted)

3.pt

# pt
import pyautomatic.pt

print(pt.colors.red + "Hello, World!" + pt.colors.reset) # 输出红色文本,颜色根据源码来搞

更新日志

0.1.1 - 2023/1/5

初次创建

1.0.0 - 2024/11/12

完善一些模块

1.0.1 - 2025/11/18

正式发到pypi平台

1.0.2 - 2025/11/18

完善功能

1.0.3 - 2025/11/19

修复bug

1.0.4 - 2025/11/20

完善功能

1.0.5 - 2026/4/30

添加disk并进行分区

1.0.6 - 2026/5/1

正式添加disk并添加ntdll

目前代码行数为6340行,包含注释和空行,但不包括特定功能,然后后面会重新计算一下,属实是一个有点儿吃代码量的库了:|

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyautomatic-1.0.6.tar.gz (65.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyautomatic-1.0.6-py3-none-any.whl (63.9 kB view details)

Uploaded Python 3

File details

Details for the file pyautomatic-1.0.6.tar.gz.

File metadata

  • Download URL: pyautomatic-1.0.6.tar.gz
  • Upload date:
  • Size: 65.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for pyautomatic-1.0.6.tar.gz
Algorithm Hash digest
SHA256 e7b5fe60df184ccd744d20df3e47717c4dd371479fd99d1005cfac5f0cfa1457
MD5 a2848fccc045d7e3cc9aab8b1e7e4655
BLAKE2b-256 bb22267a9e38d5327a2c243a50cbb7ab6e7b0c0434a662de550e5cdf40ef28fe

See more details on using hashes here.

File details

Details for the file pyautomatic-1.0.6-py3-none-any.whl.

File metadata

  • Download URL: pyautomatic-1.0.6-py3-none-any.whl
  • Upload date:
  • Size: 63.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.13

File hashes

Hashes for pyautomatic-1.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 72d91c7d185b9059982bc56eb7679bdb23130c5e0d9a18688804a25ebdaa25ca
MD5 bfb4e35d3965bcd4aca002e11f0bc02e
BLAKE2b-256 e988a159bc86488a6f246a86c0f8ae9340b6aa5ddff9b3c1e45f191203154744

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page