python 10个高频率的自动化脚本(干货,速度收藏)

1. 文件操作:自动备份文件

场景:每日自动备份重要文件到指定目录。


import shutil

import datetime

def backup_file(src, dst_folder):

now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')

dst_path = f"{dst_folder}/backup_{now}_{src.split('/')[-1]}"

shutil.copy2(src, dst_path)

print(f"Backup created at {dst_path}")

# 示例用法

backup_file("/path/to/important_file.txt", "/path/to/backup_folder")

2. 定时任务:定时发送邮件提醒

场景:每天早上9点自动发送邮件提醒。

 

import smtplib

from email.mime.text import MIMEText

from email.header import Header

import schedule

import time

def send_email():

sender = 'your_email@example.com'

receiver = 'receiver@example.com'

password = 'your_password'

subject = 'Daily Reminder'

body = 'This is your daily reminder.'

msg = MIMEText(body, 'plain', 'utf-8')

msg['From'] = Header("Reminder", 'utf-8')

msg['To'] = Header("Receiver", 'utf-8')

msg['Subject'] = Header(subject, 'utf-8')

try:

server = smtplib.SMTP_SSL('smtp.example.com', 465)

server.login(sender, password)

server.sendmail(sender, [receiver], msg.as_string())

print("Email sent successfully!")

except Exception as e:

print(f"Error sending email: {e}")

finally:

server.quit()

schedule.every().day.at("09:00").do(send_email)

while True:

schedule.run_pending()

time.sleep(1)

3. 数据抓取:网页内容爬虫

场景:抓取网站新闻标题。


import requests

from bs4 import BeautifulSoup

def scrape_news_titles(url):

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

titles = soup.find_all('h2') # 假设新闻标题在标签中

for title in titles:

print(title.text.strip())# 示例用法

scrape_news_titles('https://news.example.com/latest-news')

4. 图片批量重命名

场景:整理图片库,按日期重命名图片。


import os

from datetime import datetime

def rename_files(dir_path):

for i, filename in enumerate(os.listdir(dir_path)):

if filename.endswith('.jpg') or filename.endswith('.png'):

timestamp = datetime.now().strftime('%Y%m%d%H%M%S')

new_filename = f"img_{timestamp}_{i}.{filename.split('.')[-1]}"

os.rename(os.path.join(dir_path, filename), os.path.join(dir_path, new_filename))

# 示例用法

rename_files('/path/to/images/folder')

5. 日志文件分析

场景:统计错误日志中错误出现次数。


def analyze_logs(log_path, error_keyword):

error_count = 0

with open(log_path, 'r') as file:

for line in file:

if error_keyword in line:

error_count += 1

print(f"Error '{error_keyword}' occurred {error_count} times.")

# 示例用法

analyze_logs('/var/log/application.log', 'Error 500')

6. 文件夹同步

场景:将本地目录与远程服务器的目录同步。

示例代码(使用rsync命令,通过ssh同步):


import subprocess

def sync_folders(local_dir, remote_host, remote_dir, username):

# 构建rsync命令

cmd = f"rsync -avz --progress -e 'ssh' {local_dir}/' {username}@{remote_host}:{remote_dir}"

try:

subprocess.run(cmd, shell=True, check=True)

print("Sync completed successfully.")

except subprocess.CalledProcessError as e:

print(f"Error during sync: {e}")

# 示例用法

sync_folders('/local/path', 'remote.host.com:/remote/path', 'user')

7. 数据库备份

场景:定期将数据库备份到本地或云存储。

示例代码(MySQL数据库备份到本地文件):


import os

import subprocess

def mysql_backup(database, user, password, backup_path):

backup_file = f"{backup_path}/{database}_backup_{datetime.now().strftime('%Y%m%d%H%M%S')}.sql"

cmd = f'mysqldump -u{user} -p{password} {database} > {backup_file}'

subprocess.run(cmd, shell=True)

print(f"Backup saved to {backup_file}")

# 示例用法

mysql_backup('mydb', 'dbuser', 'dbpassword', '/path/to/backups')

8. API监控

场景:定时检测API响应状态并通知异常。

示例代码(使用requests和SMTP发送邮件通知):

 

import requests

import smtplib

from email.mime.text import MIMEText

from datetime import datetime

def monitor_api(url, expected_status, email_sender, email_receiver, email_password):

response = requests.get(url)

if response.status_code != expected_status:

message = f"API [{url}] returned {response.status_code} at {datetime.now()}"

msg = MIMEText(message)

msg['Subject'] = "API Monitor Alert"

msg['From'] = email_sender

msg['To'] = email_receiver

with smtplib.SMTP_SSL('smtp.example.com', 465) as server:

server.login(email_sender, email_password)

server.sendmail(email_sender, email_receiver, msg.as_string())

print("Alert email sent.")

else:

print("API check passed.")

# 示例用法

monitor_api('https://api.example.com/health', 200, 'sender@example.com', 'receiver@example.com', 'password')

9. 性能测试

场景:模拟高并发请求进行压力测试。

示例代码(使用locust库):


from locust import HttpUser, task, between

class WebsiteUser(HttpUser):

wait_time = between(5, 15)

@task

def load_test(self):

self.client.get("/")

# 通过命令行执行Locust

# locust -f performance_test.py --host=https://targetsite.com --users=1000 --spawn-rate=100

10. CI/CD流水线脚本

场景:自动部署代码到生产环境。

示例代码(使用fabric库进行SSH操作):


from fabric import Connection

from invoke import run

def deploy_production(host, username, local_archive):

c = Connection(host, user=username)

remote_path = '/var/www/releases/'

with c.cd(remote_path):

c.put(local_archive)

run(f"tar -xzf {os.path.basename(local_archive)}")

run("rm -f {local_archive}")

run("ln -nfs $(ls -t -1 {remote_path} | head -n1) current")

# 示例用法

deploy_production('production.server.com', 'deployuser', '/path/to/app.tar.gz')

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:【文末自行领取】

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值