[Python] 纯文本查看 复制代码
# -*- coding: utf-8 -*-
import sys
import os
import psutil
import wmi
from pynput import keyboard
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5 import QtGui
from PyQt5.QtCore import *
import winreg
import threading
import time
from pathlib import Path
from ctypes import windll
import re
import subprocess
class MyWindow(QMainWindow):
reg_root=winreg.HKEY_CURRENT_USER
reg_path=r"SOFTWARE\bdwdn"
mode = "0"
value = ""
waittime = 5
cmd = ""
def __init__(self):
super().__init__()
self.setWindowTitle("别动我电脑")
self.setWindowIcon(QIcon('icon.ico'))
self.setGeometry(100, 100, 800, 400)
self.setFixedSize(self.size())
self.center()
self.tab_widget = QTabWidget(self)
self.tab_widget.setGeometry(10, 10, 780, 380)
self.tab_widget.currentChanged.connect(self.on_tab_changed)
self.create_tab1()
self.create_tab2()
self.create_tab3()
self.create_tab4()
self.create_tab5()
self.create_tab6()
def center(self):
frame = self.frameGeometry()
screen = QDesktopWidget().availableGeometry().center()
frame.moveCenter(screen)
self.move(frame.topLeft())
def create_tab1(self):
tab = QWidget()
self.tab_widget.addTab(tab, "存在指定进程")
layout = QVBoxLayout(tab)
self.xznrr_label = QLabel('从进程列表中选择:', tab)
self.list_widget = QListWidget(tab)
self.list_widget.itemClicked.connect(self.on_item_clicked)
self.xznrn_label = QLabel('从文件选择:', tab)
self.file_button = QPushButton('选择文件', tab)
self.file_button.clicked.connect(self.select_exefile)
self.xznr_label = QLabel('选中内容:', tab)
self.xz_textbox = QLineEdit(tab)
self.ok1_button = QPushButton('确定', tab)
self.ok1_button.clicked.connect(self.ok1_click)
layout.addWidget(self.xznrr_label)
layout.addWidget(self.list_widget)
layout.addWidget(self.xznrn_label)
layout.addWidget(self.file_button)
layout.addWidget(self.xznr_label)
layout.addWidget(self.xz_textbox)
layout.addWidget(self.ok1_button)
def create_tab2(self):
tab = QWidget()
self.tab_widget.addTab(tab, "存在指定文件")
layout = QVBoxLayout(tab)
self.file_button = QPushButton('选择文件', tab)
self.file_button.clicked.connect(self.select_file)
self.xz2_textbox = QLineEdit(tab)
self.ok2_button = QPushButton('确定', tab)
self.ok2_button.clicked.connect(self.ok2_click)
layout.addWidget(self.file_button)
layout.addWidget(self.xz2_textbox)
layout.addWidget(self.ok2_button)
def create_tab3(self):
tab = QWidget()
self.tab_widget.addTab(tab, "存在指定优盘")
layout = QVBoxLayout(tab)
self.list3_widget = QListWidget(tab)
self.list3_widget.itemClicked.connect(self.on_youpan_clicked)
self.xznr_label3 = QLabel('选中内容:', tab)
self.xz3_textbox = QLineEdit(tab)
self.ok3_button = QPushButton('确定', tab)
self.ok3_button.clicked.connect(self.ok3_click)
layout.addWidget(self.list3_widget)
layout.addWidget(self.xznr_label3)
layout.addWidget(self.xz3_textbox)
layout.addWidget(self.ok3_button)
def create_tab4(self):
tab = QWidget()
self.tab_widget.addTab(tab, "存在指定USB外设")
layout = QVBoxLayout(tab)
self.list4_widget = QListWidget(tab)
self.list4_widget.itemClicked.connect(self.on_usbdrv_clicked)
self.xznr_label4 = QLabel('选中内容:', tab)
self.xz4_textbox = QLineEdit(tab)
self.ok4_button = QPushButton('确定', tab)
self.ok4_button.clicked.connect(self.ok4_click)
layout.addWidget(self.list4_widget)
layout.addWidget(self.xznr_label4)
layout.addWidget(self.xz4_textbox)
layout.addWidget(self.ok4_button)
def create_tab5(self):
tab = QWidget()
self.tab_widget.addTab(tab, "一组键盘按键")
layout = QVBoxLayout(tab)
self.input_label = QLabel('输入内容:', tab)
self.input_label.setAlignment(Qt.AlignTop)
self.input_label.setWordWrap(True)
self.xz5_textbox = QLineEdit(tab)
self.ok5_button = QPushButton('确定', tab)
self.ok5_button.clicked.connect(self.ok5_click)
self.record_button = QPushButton("开始记录", tab)
self.record_button.clicked.connect(self.toggle_record)
layout.addWidget(self.record_button)
layout.addWidget(self.input_label)
layout.addWidget(self.xz5_textbox)
layout.addWidget(self.ok5_button)
self.is_recording = False
self.record_list = []
def create_tab6(self):
tab = QWidget()
self.tab_widget.addTab(tab, "设置")
layout = QVBoxLayout(tab)
self.xznr1_label = QLabel('当前模式:', tab)
self.setmode_textbox = QLineEdit(tab)
self.xznr0_label = QLabel('当前设定值:', tab)
self.setinfo_textbox = QLineEdit(tab)
self.xznr2_label = QLabel('等待时间:', tab)
self.time_textbox = QLineEdit(tab)
self.time_textbox.setValidator(QtGui.QIntValidator(1, 99999))
self.xznr3_label = QLabel('选择操作:', tab)
self.cmd_combobox = QComboBox(tab)
self.cmd_combobox.addItem("关机(shutdown -s -f -t 0)")
self.cmd_combobox.addItem("注销(shutdown -l /f /t 0)")
self.cmd_combobox.addItem("锁定(rundll32.exe user32.dll,LockWorkStation)")
self.cmd_combobox.addItem("断网(netsh interface set interface 以太网 disabled)(需要将“以太网”改为实际网卡名)")
self.cmd_combobox.addItem("禁用键鼠(windll.user32.BlockInput(True))(内置命令)(与按键组合不能同时使用)")
self.cmd_combobox.setCurrentIndex(0)
self.xznr4_label = QLabel('选中命令(可手工输入):', tab)
self.cmd_textbox = QLineEdit(tab)
self.ok6_button = QPushButton('确定', tab)
self.ok6_button.clicked.connect(self.ok6_click)
layout.addWidget(self.xznr1_label)
layout.addWidget(self.setmode_textbox)
layout.addWidget(self.xznr0_label)
layout.addWidget(self.setinfo_textbox)
layout.addWidget(self.xznr2_label)
layout.addWidget(self.time_textbox)
layout.addWidget(self.xznr3_label)
layout.addWidget(self.cmd_combobox)
layout.addWidget(self.xznr4_label)
layout.addWidget(self.cmd_textbox)
layout.addWidget(self.ok6_button)
self.cmd_combobox.currentTextChanged.connect(self.get_selected_command)
def get_selected_command(self):
selected_command = self.cmd_combobox.currentText()
pattern = r'((.*?))'
contents = re.findall(pattern, selected_command)
self.cmd_textbox.setText(contents[0])
cmdmode = "in" if len(contents) > 1 and contents[1] == "内置命令" else "out"
self.cmd = '["' + cmdmode + '","' + contents[0] + '"]'
def ok6_click(self):
waittime = int(self.time_textbox.text())
waittime = 5 if waittime < 1 else waittime
self.time_textbox.setText(str(waittime))
try:
key = winreg.OpenKey(self.reg_root, self.reg_path, 0, winreg.KEY_ALL_ACCESS)
except:
key = winreg.CreateKey(self.reg_root, self.reg_path)
finally:
winreg.SetValueEx(key, "time", 0, winreg.REG_SZ, str(waittime))
winreg.SetValueEx(key, "cmd", 0, winreg.REG_SZ, self.cmd)
winreg.CloseKey(key)
QMessageBox.information(None, '别动我电脑', '设置完成')
def ok1_click(self):
self.write_to_inifile(1, self.xz_textbox.text())
self.setmode_textbox.setText("存在一个指定进程")
self.setinfo_textbox.setText(self.xz_textbox.text())
def ok2_click(self):
self.write_to_inifile(2, self.xz2_textbox.text())
self.setmode_textbox.setText("存在一个指定文件")
self.setinfo_textbox.setText(self.xz2_textbox.text())
def ok3_click(self):
strValue = self.xz3_textbox.text()
strValue = strValue.split("~")[-1]
self.write_to_inifile(3, strValue)
self.setmode_textbox.setText("存在一个U盘")
self.setinfo_textbox.setText(self.xz3_textbox.text())
def ok4_click(self):
strValue = self.xz4_textbox.text()
strValue = strValue.split("~")[-1]
self.write_to_inifile(4, strValue)
self.setmode_textbox.setText("存在一个USB设备")
self.setinfo_textbox.setText(self.xz4_textbox.text())
def ok5_click(self):
self.write_to_inifile(5, self.xz5_textbox.text())
self.setmode_textbox.setText("输入一组按键")
self.setinfo_textbox.setText(self.xz5_textbox.text())
def write_to_inifile(self, m, s):
try:
key = winreg.OpenKey(self.reg_root, self.reg_path, 0, winreg.KEY_ALL_ACCESS)
except:
key = winreg.CreateKey(self.reg_root, self.reg_path)
finally:
winreg.SetValueEx(key, "mode", 0, winreg.REG_SZ, str(m))
winreg.SetValueEx(key, "value", 0, winreg.REG_SZ, s)
winreg.CloseKey(key)
QMessageBox.information(None, '别动我电脑', '设置完成')
try:
key = winreg.OpenKey(self.reg_root, self.reg_path, 0, winreg.KEY_READ)
ys, _ = winreg.QueryValueEx(key, "time")
winreg.CloseKey(key)
except:
with winreg.OpenKey(self.reg_root, self.reg_path, 0, winreg.KEY_ALL_ACCESS) as key:
winreg.SetValueEx(key, "time", 0, winreg.REG_SZ, '5')
self.time_textbox.setText('5')
try:
key = winreg.OpenKey(self.reg_root, self.reg_path, 0, winreg.KEY_READ)
cmd, _ = winreg.QueryValueEx(key, "cmd")
winreg.CloseKey(key)
except:
with winreg.OpenKey(self.reg_root, self.reg_path, 0, winreg.KEY_ALL_ACCESS) as key:
winreg.SetValueEx(key, "cmd", 0, winreg.REG_SZ, '["out","shutdown -s -f -t 0"]')
self.cmd_textbox.setText('shutdown -s -f -t 0')
def toggle_record(self):
if self.is_recording:
self.record_button.setText("开始记录")
self.listener.stop()
self.is_recording = False
self.xz5_textbox.setText(str(self.record_list))
else:
self.record_button.setText("停止记录")
self.xz5_textbox.clear()
self.record_list.clear()
self.listener = keyboard.Listener(on_press=self.on_key_press)
self.listener.start()
self.is_recording = True
def on_key_press(self, key):
try:
char = str(key)
self.record_list.append(char)
except AttributeError:
pass
self.input_label.setText(f"输入内容:{self.record_list}")
def closeEvent(self, event):
try:
self.listener.stop()
except:
pass
event.accept()
def on_youpan_clicked(self, item):
self.xz3_textbox.setText(item.text())
def on_usbdrv_clicked(self, item):
self.xz4_textbox.setText(item.text())
def on_item_clicked(self, item):
self.xz_textbox.setText(item.text())
def show_youpan(self):
ups = self.get_os_up()
self.list3_widget.clear()
for device in ups:
str_list = device['Drive Letter'] + "~" + device['Size'] + "~" + device['SerialNumber']
self.list3_widget.addItem(str_list)
def show_usbdrv(self):
usbdrv = self.get_usb_drv()
self.list4_widget.clear()
for usb in usbdrv:
str_list = usb['Name'] + "~" + usb['Manufacturer'] + "~" + usb['DeviceID']
self.list4_widget.addItem(str_list)
def show_processes(self):
process_names = [proc.info['name'] for proc in psutil.process_iter(['pid', 'name'])]
process_names.sort(key=lambda x: x.lower())
self.list_widget.clear()
if process_names:
self.list_widget.addItems(process_names)
def select_file(self):
filename, _ = QFileDialog.getOpenFileName(self, '选择文件', '.', 'All Files (*)')
self.xz2_textbox.setText(filename)
def select_exefile(self):
filename, _ = QFileDialog.getOpenFileName(self, '选择exe文件', '.', 'Executable Files (*.exe)')
filename = os.path.basename(filename)
self.xz_textbox.setText(filename)
def get_usb_drv(self):
try:
c = wmi.WMI()
except Exception as e:
return []
usb_devices = [
{prop.Name: prop.Value for prop in device.Dependent.Properties_}
for device in c.Win32_USBControllerDevice()
]
return usb_devices
def get_os_up(self):
c = wmi.WMI()
usb_storage_devices = []
for diskdrive in c.Win32_DiskDrive():
if "USB" in diskdrive.InterfaceType:
for partition in diskdrive.associators("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
usb_device = {}
for prop in diskdrive.Properties_:
usb_device[prop.Name] = prop.Value
size_in_bytes = int(diskdrive.Size)
if size_in_bytes < 1024 ** 3:
size = round(size_in_bytes / (1024 ** 2), 2)
unit = 'MB'
else:
size = round(size_in_bytes / (1024 ** 3), 2)
unit = 'GB'
usb_device['Size'] = str(size) + ' ' + unit
usb_device['Drive Letter'] = logical_disk.Caption
usb_storage_devices.append(usb_device)
return usb_storage_devices
def read_reg_config(self):
strings = {'1': '进程', '2': '文件', '3': '优盘', '4': '设备', '5': '按键'}
try:
root_key = winreg.ConnectRegistry(None, self.reg_root)
key = winreg.OpenKey(root_key, self.reg_path)
mode,_ = winreg.QueryValueEx(key, "mode")
value,_ = winreg.QueryValueEx(key, "value")
waittime,_ = winreg.QueryValueEx(key, "time")
cmd,_ = winreg.QueryValueEx(key, "cmd")
winreg.CloseKey(key)
print(mode,value,waittime)
self.mode = mode
self.value = value
self.setinfo_textbox.setText(value)
self.waittime = waittime
self.cmd = cmd
if mode in ['1','2','3','4','5'] and value:
corresponding_string = strings.get(mode)
self.setmode_textbox.setText(corresponding_string)
self.setinfo_textbox.setText(value)
self.time_textbox.setText(waittime)
self.cmd_textbox.setText(eval(cmd)[1])
return True
else:
return False
except Exception as e:
return False
def add_auto_startup(self):
if getattr(sys, 'frozen', False):
exepath = os.path.abspath(sys.executable)
else:
exepath = os.path.abspath(sys.argv[0])
key_name = os.path.basename(exepath)
reg_root=winreg.HKEY_CURRENT_USER
reg_path=r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"
try:
with winreg.OpenKey(reg_root, reg_path, 0, winreg.KEY_READ) as key:
location, _ = winreg.QueryValueEx(key, key_name)
if location == '"' + exepath + '"':
is_need_startup = False
else:
is_need_startup = True
except:
is_need_startup = True
if is_need_startup:
try:
with winreg.OpenKey(reg_root, reg_path, 0, winreg.KEY_ALL_ACCESS) as key:
winreg.SetValueEx(key, key_name, 0, winreg.REG_SZ, '"' + exepath + '"')
except:
pass
def on_tab_changed(self, index):
if index == 2:
self.show_youpan()
elif index == 3:
self.show_usbdrv()
elif index == 1:
self.show_processes()
def shutdown_computer(self):
def shutdown():
try:
delay_minutes = int(self.waittime)
delay_minutes = 1 if delay_minutes < 1 else delay_minutes
cmd = eval(self.cmd)
cmdmode = cmd[0]
command = cmd[1]
except:
delay_minutes = 5
cmdmode = "out"
command = "shutdown -s -f -t 0"
while True:
time.sleep(delay_minutes * 60)
if cmdmode == "out":
subprocess.run(command, shell=True, capture_output=True, creationflags=subprocess.CREATE_NO_WINDOW)
else:
eval(command)
thread = threading.Thread(target=shutdown)
thread.start()
return thread
def check_process_exists(self, process_name):
for process in psutil.process_iter(['name']):
if process.info['name'] == process_name:
return True
return False
def check_file_exists(self, file_path):
path = Path(file_path)
return path.is_file()
def verify_user(self):
if self.mode=="1":
while True:
if self.check_process_exists(self.value):
os._exit(0)
time.sleep(5)
elif self.mode=="2":
while True:
if self.check_file_exists(self.value):
os._exit(0)
time.sleep(5)
elif self.mode=="3":
while True:
allup = self.get_os_up()
for device in allup:
if device['SerialNumber'] == self.value:
os._exit(0)
time.sleep(5)
elif self.mode=="4":
while True:
allusb = self.get_usb_drv()
for usb in allusb:
if usb['DeviceID'] == self.value:
os._exit(0)
time.sleep(5)
elif self.mode=="5":
self.listener = keyboard.Listener(on_press=self.verify_keycode)
self.listener.start()
self.key_list = []
else:
pass
def verify_keycode(self, key):
lst = eval(self.value)
key_char = str(key)
self.key_list.append(key_char)
if len(self.key_list)>len(lst):
self.key_list.pop(0)
if self.key_list==lst:
self.listener.stop()
os._exit(0)
if __name__ == "__main__":
app = QApplication(sys.argv)
arguments = app.arguments()
win = MyWindow()
win.add_auto_startup()
if win.read_reg_config() and len(arguments)<2:
win.hide()
shutdownthread = win.shutdown_computer()
win.verify_user()
else:
win.show()
win.show_processes()
sys.exit(app.exec_())