下载oss2上面的屏幕截图文件的代码

import os
import re
import oss2
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter.scrolledtext import ScrolledText
import pickle
from tkinter import filedialog
import subprocess


def on_entry_focus_in(event):
    # 当Entry获得焦点时,检查是否包含默认文本并删除它
    if entry_date.get() == "例:2024-01-01":
        entry_date.delete(0, tk.END)
        # 如果需要,也可以在这里将前景色改回黑色或其他颜色


def on_entry_focus_out(event):
    # 当Entry失去焦点时,如果它是空的,则添加默认文本
    if not entry_date.get():
        entry_date.insert(0, "2024-01-01")


def create_dir_if_not_exists(path):
    if not os.path.exists(path):
        os.makedirs(path)


def mac_to_name(file_name, mac_to_name_dict):
    mac_address_pattern = re.compile(r'([0-9a-fA-F]{2}[_-]){5}[0-9a-fA-F]{2}')
    match = mac_address_pattern.search(file_name)
    if match:
        mac_address = match.group(0)
        if mac_address in mac_to_name_dict:
            return file_name.replace(mac_address, mac_to_name_dict[mac_address])
    return file_name


def download_matching_files(bucket, file_name_part, download_path, mac_to_name_dict, log_text):
    file_count = 0
    for obj in oss2.ObjectIterator(bucket):
        if file_name_part in obj.key:
            file_name = mac_to_name(obj.key, mac_to_name_dict)
            file_path = os.path.join(download_path, file_name)
            create_dir_if_not_exists(os.path.dirname(file_path))  # 确保目录存在
            try:
                bucket.get_object_to_file(obj.key, file_path)
                log_text.insert(tk.END, f'下载 {obj.key} 到 {file_path}\n')
                log_text.see(tk.END)  # 自动滚动到最后一行
                log_text.update()
                file_count += 1
            except Exception as e:
                log_text.insert(tk.END, f'下载 {obj.key} 失败: {str(e)}\n')
                log_text.see(tk.END)  # 自动滚动到最后一行
                log_text.update()
    return file_count


def save_mac_to_name_dict(mac_to_name_dict, filename='mac_to_name_dict.pkl'):
    with open(filename, 'wb') as f:
        pickle.dump(mac_to_name_dict, f)


def load_mac_to_name_dict(filename='mac_to_name_dict.pkl'):
    if os.path.exists(filename):
        with open(filename, 'rb') as f:
            return pickle.load(f)
    return {}


def start_download():
    file_name_part = entry_date.get()
    if not file_name_part:
        messagebox.showerror("错误", "请输入文件名中包含的日期")
        return

    download_path = entry_download_path.get()
    if not download_path:
        messagebox.showerror("错误", "请选择保存下载文件的路径")
        return

    mac_to_name_dict = load_mac_to_name_dict()

    auth = oss2.Auth('123', '456')
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'singsongpic')

    log_text.insert(tk.END, "开始下载文件...\n")
    file_count = download_matching_files(bucket, file_name_part, download_path, mac_to_name_dict, log_text)
    messagebox.showinfo("完成", f"总共下载的文件数:{file_count}")
    log_text.insert(tk.END, f"下载完成,总共下载的文件数:{file_count}\n")


# def add_mac_to_name():
#     mac = entry_mac.get()
#     name = entry_name.get()
#     if not mac or not name:
#         messagebox.showerror("错误", "请输入MAC地址和对应的姓名")
#         return
#
#     mac_to_name_dict = load_mac_to_name_dict()
#     mac_to_name_dict[mac] = name
#     save_mac_to_name_dict(mac_to_name_dict)
#     messagebox.showinfo("完成", "MAC地址和姓名已添加")
def open_download_folder():
    """打开下载文件夹"""
    # 确保entry_download_path中有有效的路径
    if entry_download_path.get():
        path = entry_download_path.get()
        if os.path.isdir(path):
            # 使用subprocess调用系统默认的文件夹打开程序
            if os.name == 'nt':  # Windows系统
                subprocess.Popen(['explorer', path])
            else:  # Linux或macOS系统
                subprocess.Popen(['xdg-open', path])
        else:
            print("路径不是有效的文件夹")
    else:
        print("请先选择下载路径")

def choose_directory():
    download_path = filedialog.askdirectory()
    if download_path:
        entry_download_path.delete(0, tk.END)
        entry_download_path.insert(0, download_path)


# GUI部分
root = tk.Tk()
root.title("OSS屏幕文件下载器-SINGSONG专用")

tk.Label(root, text="文件名中包含的日期:").grid(row=0, column=0)
entry_date = tk.Entry(root, foreground='dim gray')  # 使用浅灰色作为前景色
entry_date.insert(0, "例:2024-01-01")  # 插入默认文本
entry_date.grid(row=0, column=1)

# 绑定FocusIn事件以便在用户点击时删除默认文本
entry_date.bind("<FocusIn>", on_entry_focus_in)

tk.Label(root, text="下载文件保存路径:").grid(row=1, column=0)
entry_download_path = tk.Entry(root)
entry_download_path.grid(row=1, column=1)
tk.Button(root, text="选择下载路径", command=choose_directory).grid(row=1, column=2)

tk.Button(root, text="下载文件", command=start_download).grid(row=2, column=0, columnspan=3)
# # 创建打开下载文件夹按钮
# tk.Button(root, text="打开下载文件夹", command=open_download_folder).grid(row=2, column=2)
# #
# tk.Label(root, text="MAC地址:").grid(row=3, column=0)
# entry_mac = tk.Entry(root)
# entry_mac.grid(row=3, column=1)

# tk.Label(root, text="对应的姓名:").grid(row=4, column=0)
# entry_name = tk.Entry(root)
# entry_name.grid(row=4, column=1)

# tk.Button(root, text="添加MAC地址和姓名", command=add_mac_to_name).grid(row=5, column=0, columnspan=3)

# 添加用于显示下载信息的文本框
log_text = ScrolledText(root, wrap=tk.WORD, width=50, height=10)
log_text.grid(row=6, column=0, columnspan=3)

root.mainloop()

 =====================================带登录界面==========================================================================

import os
import re
import oss2
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog
from tkinter.scrolledtext import ScrolledText
import pickle
import subprocess


def on_entry_focus_in(event):
    if entry_date.get() == "例:2024-01-01":
        entry_date.delete(0, tk.END)


def on_entry_focus_out(event):
    if not entry_date.get():
        entry_date.insert(0, "2024-01-01")


def create_dir_if_not_exists(path):
    if not os.path.exists(path):
        os.makedirs(path)


def mac_to_name(file_name, mac_to_name_dict):
    mac_address_pattern = re.compile(r'([0-9a-fA-F]{2}[_-]){5}[0-9a-fA-F]{2}')
    match = mac_address_pattern.search(file_name)
    if match:
        mac_address = match.group(0)
        if mac_address in mac_to_name_dict:
            return file_name.replace(mac_address, mac_to_name_dict[mac_address])
    return file_name


def download_matching_files(bucket, file_name_part, download_path, mac_to_name_dict, log_text):
    file_count = 0
    for obj in oss2.ObjectIterator(bucket):
        if file_name_part in obj.key:
            file_name = mac_to_name(obj.key, mac_to_name_dict)
            file_path = os.path.join(download_path, file_name)
            create_dir_if_not_exists(os.path.dirname(file_path))
            try:
                bucket.get_object_to_file(obj.key, file_path)
                log_text.insert(tk.END, f'下载 {obj.key} 到 {file_path}\n')
                log_text.see(tk.END)
                log_text.update()
                file_count += 1
            except Exception as e:
                log_text.insert(tk.END, f'下载 {obj.key} 失败: {str(e)}\n')
                log_text.see(tk.END)
                log_text.update()
    return file_count


def save_mac_to_name_dict(mac_to_name_dict, filename='mac_to_name_dict.pkl'):
    with open(filename, 'wb') as f:
        pickle.dump(mac_to_name_dict, f)


def load_mac_to_name_dict(filename='mac_to_name_dict.pkl'):
    if os.path.exists(filename):
        with open(filename, 'rb') as f:
            return pickle.load(f)
    return {}


def start_download():
    file_name_part = entry_date.get()
    if not file_name_part:
        messagebox.showerror("错误", "请输入文件名中包含的日期")
        return

    download_path = entry_download_path.get()
    if not download_path:
        messagebox.showerror("错误", "请选择保存下载文件的路径")
        return

    mac_to_name_dict = load_mac_to_name_dict()

    auth = oss2.Auth('1243', '56654645')
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'singsongpic')

    log_text.insert(tk.END, "开始下载文件...\n")
    file_count = download_matching_files(bucket, file_name_part, download_path, mac_to_name_dict, log_text)
    messagebox.showinfo("完成", f"总共下载的文件数:{file_count}")
    log_text.insert(tk.END, f"下载完成,总共下载的文件数:{file_count}\n")


def open_download_folder():
    if entry_download_path.get():
        path = entry_download_path.get()
        if os.path.isdir(path):
            if os.name == 'nt':
                subprocess.Popen(['explorer', path])
            else:
                subprocess.Popen(['xdg-open', path])
        else:
            print("路径不是有效的文件夹")
    else:
        print("请先选择下载路径")


def choose_directory():
    download_path = filedialog.askdirectory()
    if download_path:
        entry_download_path.delete(0, tk.END)
        entry_download_path.insert(0, download_path)


def show_login_dialog():
    login_window = tk.Toplevel(root)
    login_window.title("登录")
    login_window.geometry("300x200")

    tk.Label(login_window, text="用户名:").pack(pady=5)
    username_entry = tk.Entry(login_window)
    username_entry.pack(pady=5)

    tk.Label(login_window, text="密码:").pack(pady=5)
    password_entry = tk.Entry(login_window, show='*')
    password_entry.pack(pady=5)

    def check_login():
        username = username_entry.get()
        password = password_entry.get()
        if username == "admin" and password == "admin":  # 修改为实际用户名和密码
            login_window.destroy()
        else:
            messagebox.showerror("错误", "用户名或密码错误")

    tk.Button(login_window, text="登录", command=check_login).pack(pady=10)
    login_window.transient(root)
    login_window.grab_set()
    root.wait_window(login_window)


root = tk.Tk()
root.title("OSS屏幕文件下载器-SINGSONG专用")

show_login_dialog()

tk.Label(root, text="文件名中包含的日期:").grid(row=0, column=0)
entry_date = tk.Entry(root, foreground='dim gray')
entry_date.insert(0, "例:2024-01-01")
entry_date.grid(row=0, column=1)
entry_date.bind("<FocusIn>", on_entry_focus_in)

tk.Label(root, text="下载文件保存路径:").grid(row=1, column=0)
entry_download_path = tk.Entry(root)
entry_download_path.grid(row=1, column=1)
tk.Button(root, text="选择下载路径", command=choose_directory).grid(row=1, column=2)

tk.Button(root, text="下载文件", command=start_download).grid(row=2, column=0, columnspan=3)

log_text = ScrolledText(root, wrap=tk.WORD, width=50, height=10)
log_text.grid(row=3, column=0, columnspan=3)

root.mainloop()

 

posted @ 2024-07-08 12:05  *感悟人生*  阅读(8)  评论(0编辑  收藏  举报