Python脚本

1.对目录下的文件进行分类,并根据文件后缀,将相应文件移动或拷贝至对应目录

import sys
import os  
import shutil  
  
def get_file_extension(filename):   
    _, file_extension = os.path.splitext(filename)  
    if file_extension.startswith('.'):  
        return file_extension[1:]  # 去除点号  
    else:
        return file_extension
  
def sort_files(directory_path):  
    for filename in os.listdir(directory_path):  
        if os.path.isfile(os.path.join(directory_path, filename)):  
            file_extension = get_file_extension(filename)  
            if not file_extension:  # 如果文件名没有扩展名,则跳过或特别处理  
                continue  
            destination_directory = os.path.join(directory_path, file_extension)  
            if not os.path.exists(destination_directory):  
                os.makedirs(destination_directory)  
        #    shutil.move(os.path.join(directory_path, filename), os.path.join(destination_directory, filename))  
            shutil.copy(os.path.join(directory_path, filename), os.path.join(destination_directory, filename))  
  

#directory_path = '/path/to/your/directory'  
#sort_files(directory_path)
sort_files(sys.argv[1])

 

2.获取某个文件夹下的空目录,记录空目录绝对路径 (并删除)

import os  
import sys
  
def remove_empty_folders_to_file(directory_path, output_file):  
    with open(output_file, 'w') as f:  
        pass  # 如果文件不存在,这将创建它;如果已存在,则清空内容  
  
    # 遍历目录  
    for root, dirs, files in os.walk(directory_path, topdown=False):  
        for folder in dirs:  
            folder_path = os.path.join(root, folder)    
            if not os.listdir(folder_path):  
                # 如果为空,则写入到文件中  
                with open(output_file, 'a') as f:  
                    f.write(folder_path + '\n')  # 写入路径并添加换行符
# 删除
# os.rmdir(folder_path) #directory_to_clean = '/path/to/your/directory' #output_file_path = '/path/to/your/output_file.txt' #remove_empty_folders_to_file(directory_to_clean, output_file_path) remove_empty_folders_to_file(sys.argv[1], sys.argv[2])

 

3.杀死指定进程 

import os  
import psutil  
import sys  
  
def get_running_processes(process_name):  
#    return [{'pid': p.pid, 'name': p.name(), 'username': p.username()} for p in psutil.process_iter() if p.name().lower() == process_name.lower()]  
    processes = []
    for p in psutil.process_iter():
        if p.name().lower() == process_name.lower():  
           processes.append({'pid': p.pid, 'name': p.name(), 'username': p.username()})
    if not processes:
        return []
    else:
        return processes
  
def kill_process_by_name(process_name):  
    for p in psutil.process_iter():  
        if p.name().lower() == process_name.lower():  
            try:  
                p.kill()  
                print(f"Process {process_name} with PID {p.pid} killed.")  
            except psutil.NoSuchProcess:  
                print(f"Process {process_name} with PID {p.pid} no longer exists.")  
            except Exception as e:  
                print(f"Failed to kill process {process_name} with PID {p.pid}: {e}")  
   
if len(sys.argv) > 1:  
    process_name = sys.argv[1]  
    running_processes = get_running_processes(process_name)  
#    print(running_processes)  
    if not running_processes:  
        print("process not running!!!")  
    else:  
        print(running_processes) 
        kill_process_by_name(process_name)  
else:  
    print("Usage: python script.py <process_name>")

 

import os  
import psutil  
import sys  
  
def get_running_processes(process_name):  
    return [{'pid': p.pid, 'name': p.name(), 'username': p.username()} for p in psutil.process_iter() if p.name().lower() == process_name.lower()]  
  
def kill_process_by_name(process_name):  
    processes = get_running_processes(process_name)  
    for proc in processes:  
        try:  
            p = psutil.Process(proc['pid'])  
            p.kill()  
            print(f"Process {process_name} with PID {proc['pid']} killed.")  
        except psutil.NoSuchProcess:  
            print(f"Process {process_name} with PID {proc['pid']} no longer exists.")  
        except Exception as e:  
            print(f"Failed to kill process {process_name} with PID {proc['pid']}: {e}")  
  
if __name__ == "__main__":  
    if len(sys.argv) == 2:  
        process_name = sys.argv[1]  
        running_processes = get_running_processes(process_name)  
        if not running_processes:  
            print("process not running!!!")  
        else:  
            #print(running_processes)
            print("Running processes:")  
            for process in running_processes:  
                print(f"PID: {process['pid']}, Name: {process['name']}")    
            kill_process_by_name(process_name)    
    else:  
        print("Usage: python script.py <process_name>")

 

 

4.监控服务器磁盘剩余空间,并发送邮件提醒

import psutil  
import smtplib  
from email.mime.text import MIMEText  
from email.mime.multipart import MIMEMultipart  
  
def send_email(subject, body, sender, recipient, smtp_server, smtp_port, username, password):  
    msg = MIMEMultipart()  
    msg['From'] = sender  
    msg['To'] = recipient  
    msg['Subject'] = subject  
    msg.attach(MIMEText(body, 'plain'))  
  
    try:  
        server = smtplib.SMTP_SSL(smtp_server, smtp_port)    
        server.login(username, password)  
        server.sendmail(sender, recipient, msg.as_string())  
        server.quit()  
        print("Email sent successfully!")  
    except Exception as e:  
        print(f"Failed to send email: {e}")  
  
def check_disk_space(minimum_threshold_gb):  
    disk = psutil.disk_usage('/')  
    free_space_gb = disk.free / (1024 ** 3)  
  
    if free_space_gb < minimum_threshold_gb:  
        # 发送电子邮件的代码  
        subject = "磁盘空间告警: 磁盘空闲空间过低"  
        body = (f"警告: root 空闲空间小于 {minimum_threshold_gb} GB. "   
               f"当前空闲空间为 {free_space_gb:.2f} GB."  )
        sender = 'xxx@qq.com'  # 替换邮箱地址  
        recipient = 'xxx@163.com'  # 替换为接收者的邮箱地址  
        smtp_server = 'smtp.qq.com'  # 替换为SMTP服务器地址  
        smtp_port = 465  # 根据SMTP服务器设置进行更改 
        username = 'xxx@qq.com'  # SMTP账户用户名  
        password = '授权码'  # SMTP账户密码或应用密码 
  
        send_email(subject, body, sender, recipient, smtp_server, smtp_port, username, password)  
    else:  
        print(f"root 有足够磁盘空间: {free_space_gb:.2f} GB (阈值为 {minimum_threshold_gb} GB).")  
  

check_disk_space(30)  

 

5.检查网站状态

import requests  
  
def check_website_status(url):  
    try:  
        response = requests.get(url)  
        if response.status_code == 200:  
            print(f"The website {url} is up and running.")  
        else:  
            print(f"The website {url} is not available. Status code: {response.status_code}")  
    except requests.RequestException as e:   
        print(f"An error occurred while checking {url}. Error: {e}")  
  

if __name__ == "__main__":  
    website_url = "http://www.test.com"  
    check_website_status(website_url)

 

posted @ 2024-08-24 09:33  一窗明月半帘风  阅读(17)  评论(0编辑  收藏  举报