自动化是现代效率的推动力,而Python则是自动化的最佳伙伴。这门语言以其丰富的解决方案而闻名,能够无缝地简化各种任务。凭借广泛的库支持、内置函数以及活跃的社区贡献,Python成为简化工作流程的终极利器。
本文,我们将介绍 10 个你必须尝试的惊人Python自动化脚本。
你是否曾发现自己在处理多个文本片段时,难以跟踪你复制的内容?是否曾想过拥有一个工具,可以记录你一天内复制的所有内容?
这个自动化脚本可以监控你复制的所有内容,轻松地将每个复制的文本存储在一个简洁的图形界面中,这样你就不必在无尽的标签页中搜索,避免丢失一些有价值的信息。

这个自动化脚本利用 Pyperclip 库的功能,无缝捕获复制的数据,并集成 Tkinter 来直观跟踪和管理已复制的文本。
import tkinter as tk
from tkinter import ttk
import pyperclip
X = []
root = tk.Tk()
root.geometry('500x500')
root.title('Clipboard Manager')
root.configure(bg='#f0f0f0')
frame = tk.Frame(root, bg='#f0f0f0')
frame.pack(padx=10, pady=10)
label = tk.Label(frame, text='Clipboard Contents:', bg='#f0f0f0')
label.grid(row=0, column=0)
scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
listbox = tk.Listbox(root, width=150, height=150, yscrollcommand=scrollbar.set)
listbox.pack(pady=10)
scrollbar.config(command=listbox.yview)
def update_listbox():
new_item = pyperclip.paste()
if new_item not in X:
X.append(new_item)
listbox.insert(tk.END, new_item)
listbox.insert(tk.END, '---------------------------------')
listbox.yview(tk.END)
root.after(1000, update_listbox)
def copy_to_clipboard(event):
selected_item = listbox.get(listbox.curselection())
if selected_item:
pyperclip.copy(selected_item)
update_listbox()
listbox.bind('<Double-Button-1>', copy_to_clipboard)
root.mainloop()
每个开发人员都曾面临过在自己的Python代码中寻找 bugs 的痛苦和挫折,最终发现自己被困在一个错误的迷宫中。作为开发人员,我们理解编写清晰高效代码的重要性,但是手动分析代码质量可能是一项很有压力的任务。
图片源于网络
这个自动化脚本利用 Pylint 和 Flake8 Python 包对你的代码质量进行全面审查。通过将你的代码与编码标准进行比较,识别逻辑错误,确保你的代码符合行业最佳实践,并保证无错误。
import os
import subprocess
def analyze_code(directory):
python_files = [file for file in os.listdir(directory) if file.endswith('.py')]
if not python_files:
print('No Python files found in the specified directory.')
# Analyze each Python file using pylint and flake8
for file in python_files:
print(f'Analyzing file: {file}')
file_path = os.path.join(directory, file)
# Run pylin
print('\nRunning pylint...')
pylint_command = f'pylint {file_path}'
subprocess.run(pylint_command, shell=True)
# Run flake8
print('\nRunning flake8...')
falke8_command = f'flake8 {file_path}'
subprocess.run(falke8_command, shell=True)
if __name__ == '__main__':
directory = '../test'
analyze_code(directory)
注意:请事先安装
pylint和flake8这两个包,并且将其添加到系统环境变量的 Path 中。否则可能出现这两个命令不是内部或外部命令的情况。
文件篡改,也称为数据篡改,是未经授权故意更改信息的行为,包括销毁、操纵或编辑数据。
世界各地的许多威胁者滥用文件篡改技术,在关键系统文件中引入各种漏洞或后门,破坏安全性并启用未经授权的访问。
为了降低这种风险,必须验证文件的完整性,确保它们保持原始状态未被更改。这个自动化脚本可以帮助您测试任何文件并识别其是否被篡改。
import hashlib
import os
def calculate_sha256(file_path):
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdigest()
def check_integrity(file_path, expected_checksum):
actual_checksum = calculate_sha256(file_path)
return actual_checksum == expected_checksum
if __name__ == '__main__':
file_path = input('Enter the full path of the file: ')
expected_checksum = input('Enter the expected SHA-256 checksum: ')
if os.path.isfile(file_path):
if check_integrity(file_path, expected_checksum):
print('File integrity verified: The file has not been tampered with.')
else:
print('File integrity failed: The file may been tampered with.')
else:
print('Error: File does not exist.')
PS:Windows 环境下,可以通过命令行工具(CertUtil 命令)查询文件的“SHA-256校验和”,通过查询文件被篡改前后的哈希校验和,可以确定文件是否被篡改。
交易是指金融工具的买卖,如股票、债券、货币、商品或衍生品,目的是盈利。期货交易员整天都在看不同的仪表板,试图找出一个完美的买卖决策。
这个自动化脚本可以帮助交易员和投资者更好地了解想要投资的任何股票。它利用 Prophet Python库根据历史股票数据(从Yahoo Finance获取)预测未来股价。
import streamlit as st
from datetime import date
import yfinance as yf
from prophet import Prophet
from prophet.plot import plot_plotly
from plotly import graph_objects as go
START = '2015-01-01'
TODAY = date.today().strftime('%Y-%m-%d')
st.title('Stock Forecast App')
stocks = ('MSFT', 'TSLA', 'GOOG', 'AAPL', 'NVDA')
selected_stock = st.selectbox('Select dataset for prediction', stocks)
n_years = st.slider('Years of prediction:', 1, 4)
period = n_years * 365
@st.cache_data
def load_data(ticker):
data = yf.download(ticker, start=START, end=TODAY)
data.reset_index(inplace=True)
return data
data_load_state = st.text('Loading data...')
data = load_data(selected_stock)
data_load_state.text('Loading data... done!')
st.subheader('Rwa data')
st.write(data.tail())
# Plot raw data
def plot_raw_data():
fig = go.Figure()
fig.add_trace(go.Scatter(x=data['Date'], y=data['Open'], name='stock_open'))
fig.add_trace(go.Scatter(x=data['Date'], y=data['Close'], name='stock_close'))
fig.layout.update(title_text='Time Series data with Rangeslider', xaxis_rangeslider_visible=True)
st.plotly_chart(fig)
plot_raw_data()
# Predict forecast with Prophet.
df_train = data[['Date', 'Close']]
df_train = df_train.rename(columns={'Date': 'ds', 'Close': 'y'})
m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period)
forecast = m.predict(future)
# Show and plot forecast
st.subheader('Forecast data')
st.write(forecast.tail())
st.write(f'Forecast plot for {n_years} years')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)
st.write('Forecast components')
fig2 = m.plot_components(forecast)
st.write(fig2)
请在终端下通过命令(streamlit run smart_trade.py)运行该脚本,执行命令后会得到两个地址:
任意复制其中一个到浏览器中都可以查看脚本运行效果:
收集图像数据是计算机视觉项目中的一个关键挑战。正如 Andrew Ng 所说,如果你能收集到一个大型数据集,那么算法就不重要了。数据在提高模型的性能和准确性方面起着关键作用。
这个自动化脚本可以帮助你在几分钟内用几行代码从网上批量下载数据。
from simple_image_download import simple_image_download as simp
response = simp.Downloader()
try:
response.download(keywords='Dog', limit=20, verbose=True)
print('Images downloaded successfully.')
except Exception as e:
print('An error occurred: ', e)
PS:这个脚本是通过
simple_image_download包从谷歌下载图像,因此由于 SSL 证书验证的问题,导致在国内基本无法成功下载到图像。
让我们来谈谈网络安全!
在计算机网络中,端口是一个通信端点,允许不同的进程或服务通过网络连接和交换数据。端口通过数值来标识,并与特定的协议相关联。
开放端口就像建筑物中的窗户或门——每个端口都为网站和外部网络之间的通信提供了一个潜在的入口。然而,未采取适当安全措施而保持端口开放,可能会使网站容易受到网络攻击。
这个自动化脚本将以网站 URL 作为输入,检查该网站的任何开放端口。无论你是在红队执行任务,还是在蓝队坚守阵地,这个脚本都能成为你的一个有用工具。
import sys
import socket
from prettytable import PrettyTable
# Dictionary mapping common ports to vulnerabilities (Top 15)
vulnerabilities = {
80: "HTTP (Hypertext Transfer Protocol) - Used for unencrypted web traffic",
443: "HTTPS (HTTP Secure) - Used for encrypted web traffic",
22: "SSH (Secure Shell) - Used for secure remote access",
21: "FTP (File Transfer Protocol) - Used for file transfers",
25: "SMTP (Simple Mail Transfer Protocol) - Used for email transmission",
23: "Telnet - Used for remote terminal access",
53: "DNS (Domain Name System) - Used for domain name resolution",
110: "POP3 (Post Office Protocol version 3) - Used for email retrieval",
143: "IMAP (Internet Message Access Protocol) - Used for email retrieval",
3306: "MySQL - Used for MySQL database access",
3389: "RDP (Remote Desktop Protocol) - Used for remote desktop connections (Windows)",
8080: "HTTP Alternate - Commonly used as a secondary HTTP port",
8000: "HTTP Alternate - Commonly used as a secondary HTTP port",
8443: "HTTPS Alternate - Commonly used as a secondary HTTPS port",
5900: "VNC (Virtual Network Computing) - Used for remote desktop access",
# Add more ports and vulnerabilities as needed
}
def display_table(open_ports):
table = PrettyTable(["Open Port", "Vulnerability"])
for port in open_ports:
vulnerability = vulnerabilities.get(port, "No known vulnerabilities associated with common services")
table.add_row([port, vulnerability])
print(table)
def scan_top_ports(target):
open_ports = []
top_ports = [21, 22, 23, 25, 53, 80, 110, 143, 443, 3306, 3389, 5900, 8000, 8080, 8443] # Top 15 ports
for port in top_ports:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1) # Adjust timeout as needed
result = sock.connect_ex((target, port))
if result == 0:
open_ports.append(port)
sock.close()
except KeyboardInterrupt:
sys.exit()
except socket.error:
pass
return open_ports
def main():
target = input("Enter the website URL or IP address to scan for open ports: ")
open_ports = scan_top_ports(target)
if not open_ports:
print("No open ports found on the target.")
else:
print("Open ports and associated vulnerabilities:")
display_table(open_ports)
if __name__ == "__main__":
main()
让我们扫描 itsecgames.com,一个极易受到攻击的网络应用程序!
作为一个数字自由职业者,最糟糕的事情之一就是你需要记住很多密码,因为每天你都在注册新的网站。
这个自动化脚本可以帮助你管理所有密码,并通过不同的加密技术仅对你可访问,这样就能保证密码安全。
这个脚本最棒的部分是它是一个网页应用,这意味着主需要较少的更改,你就可以将其部署到云存储上,并在任何地方访问所有密码,而无需担心安全问题。
import streamlit as st
import csv
from cryptography.fernet import Fernet
from cryptography.fernet import InvalidToken
# Custom encryption key (hardcoded)
## If you are planning to use this script on a shared platform make sure to save this key in a separate secured file.
CUSTOM_ENCRYPTION_KEY = b'u7wGgNdDFefqpr_kGxb8wJf6XRVsRwvb3QgITsD5Ft4='
# Function to encrypt password
def encrypt_password(password):
cipher_suite = Fernet(CUSTOM_ENCRYPTION_KEY)
encrypted_password = cipher_suite.encrypt(password.encode())
return encrypted_password
# Function to decrypt password
def decrypt_password(encrypted_password):
if isinstance(encrypted_password, bytes):
try:
cipher_suite = Fernet(CUSTOM_ENCRYPTION_KEY)
decrypted_password = cipher_suite.decrypt(encrypted_password)
return decrypted_password.decode()
except InvalidToken:
return "Invalid Token"
else:
return None
# Function to save website name and password to CSV file
def save_credentials(website_name, password):
encrypted_password = encrypt_password(password)
with open('credentials.csv', 'a', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow([website_name, encrypted_password.decode()]) # Ensure storing string representation
# Function to retrieve password from CSV file
def retrieve_password(website_name):
with open('credentials.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
if row[0] == website_name:
encrypted_password = row[1].encode()
return encrypted_password
return None
# Streamlit UI
st.title("Password Manager")
# Input fields for website name and password
website_name = st.text_input("Enter website name:")
password = st.text_input("Enter password:", type="password")
# Save button to save website name and password
if st.button("Save"):
if website_name and password:
save_credentials(website_name, password)
st.success("Website name and password saved successfully.")
else:
st.error("Please fill in all fields.")
# Retrieve button to retrieve password
if st.checkbox("Retrieve Password"):
website_name = st.selectbox("Select website name:",
options=[""] + [row[0] for row in csv.reader(open('credentials.csv', 'r'))])
key = st.text_input("Enter Your Encryption Key:", type="password")
if st.button("Retrieve Password"):
if key == str(CUSTOM_ENCRYPTION_KEY.decode()):
if website_name:
encrypted_password = retrieve_password(website_name)
if encrypted_password:
decrypted_password = decrypt_password(encrypted_password)
st.success(f"Password for **{website_name}** -> **{decrypted_password}**")
else:
st.error("Password not found in database.")
elif key == "":
pass
else:
st.error("Invalid Encryption Key!!!")
电子邮件列表是在线互动的货币,每位订阅者都是你数字部落的重要成员。它们是有效数字营销的核心。
作为数字影响者,与粉丝保持互动很重要,但手动操作是一项艰巨的任务,使用工具则可能会花费大量金钱。
这个自动化脚本利用 Gmail 自身的 SMTP 服务器在几分钟内批量发送邮件,让你可以完全自定义和掌控全局。
import smtplib
import ssl
# SMTP server details
smtp_server = 'smtp.gmail.com'
smtp_port = 465
# Sender and recipient details
from_address = ''
to_address = ['', ''] ## Recepients List
# Authentication details
username = '' ## Sender Email
password = '' ## Sender Password
# Email message details
subject = '🎉 Exclusive Offer Inside! Get 10% Off Your Next Purchase'
body = '''\
Dear Customer,
We are thrilled to offer you an exclusive discount on your next purchase as a token of our appreciation for being a valued customer. Use the coupon code below during checkout to enjoy a 10% discount on your order:
Coupon Code: DISCOUNT10
Whether you're looking for stylish apparel, trendy accessories, or high-quality products, now is the perfect time to shop and save! Explore our latest collection and treat yourself to something special.
Hurry! This offer is valid for a limited time only. Don't miss out on the chance to save on your favorite items.
Shop now: https://xyz.com
Thank you for choosing WinzoShop. We look forward to serving you again soon!
Best regards,
Winzo Shop
'''
# Create an SSL/TLS context
context = ssl.create_default_context()
# Connect to the SMTP server using SSL/TLS
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
# Enable debugging to print the server's responses
server.set_debuglevel(1)
# Login to the SMTP server
server.login(username, password)
# Create the email message
message = f'From: {from_address}\r\nSubject: {subject}\r\nTo: {to_address}\r\n\r\n{body}'
message = message.encode() # Convert the message to bytes
# Send the email
server.sendmail(from_address, to_address, message)
请确保不向收件人发送垃圾邮件,否则你将被 Gmail 加入黑名单。尽量将你的电子邮件限制在每天 100 封以内。
README.md 文件是你项目的门户,提供必要的信息,吸引访客进一步探索。它被认为是你仓库中最重要的文件之一,但创建它也相当耗时。
这个自动化脚本将根据输入的仓库名称、链接和描述,轻松生成 README.md 文件,为你节省数小时的时间。
def generate_markdown_file():
# Prompting user for inputs
repository_name = input("\n Enter the name of your GitHub repository: ")
project_description = input("Enter a short description of your project: ")
installation_instructions = input("Enter installation instructions for your project: ")
usage_instructions = input("Enter usage instructions for your project: ")
contributors = input("Enter the contributors to your project (separated by commas): ")
_license = select_license()
# Generating badges
stars_badge = "[](https://github.com/{}/stargazers)".format(repository_name, repository_name)
forks_badge = "[](https://github.com/{}/network/members)".format(repository_name, repository_name)
issues_badge = "[](https://github.com/{}/issues)".format(repository_name, repository_name)
license_badge = "[](https://github.com/{}/blob/master/LICENSE)".format(repository_name, repository_name)
# Generating Markdown content
markdown_content = f"""
# {repository_name}
{project_description}
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [Contributors](#contributors)
- [License](#license)
- [Badges](#badges)
- [GitHub Repository](#github-repository)
## Installation
```
{installation_instructions}
```
## Usage
```
{usage_instructions}
```
## Contributors
{contributors}
## License
This project is licensed under the {_license} License - see the [LICENSE](LICENSE) file for details.
## Badges
{stars_badge} {forks_badge} {issues_badge} {license_badge}
## GitHub Repository
[Link to GitHub repository](https://github.com/{repository_name})
"""
# Writing content to Markdown file
markdown_file_name = f"{repository_name}_README.md"
with open(markdown_file_name, "w") as markdown_file:
markdown_file.write(markdown_content)
print(f"Markdown file '{markdown_file_name}' generated successfully!")
def select_license():
licenses = {
"MIT": "MIT License",
"Apache": "Apache License 2.0",
"GPL": "GNU General Public License v3.0",
# Add more licenses as needed
}
print("Select a license for your project:")
for key, value in licenses.items():
print(f"{key}: {value}")
while True:
selected_license = input("Enter the number corresponding to your selected license: ")
if selected_license in licenses:
return licenses[selected_license]
else:
print("Invalid input. Please enter a valid license number.")
if __name__ == "__main__":
generate_markdown_file()
你的下载文件夹是否一片混乱?
你是否发现自己在需要时拼命寻找关键文件?
你是否多次尝试整理文件夹,却总是未能如愿?
这个自动化脚本可以在几分钟内帮助你整理文件夹。你只需指定需要清理的路径,该脚本会根据文件扩展名自动将所有文件分到不同的文件夹中。
不仅如此!它还可以通过比较文件的哈希值来检测和处理重复文件。
import os
import hashlib
import shutil
def get_file_hash(file_path):
with open(file_path, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest()
def organize_and_move_duplicates(folder_path):
# Create a dictionary to store destination folders based on file extensions
extension_folders = {}
# Create the "Duplicates" folder if it doesn't exist
duplicates_folder = os.path.join(folder_path, 'Duplicates')
os.makedirs(duplicates_folder, exist_ok=True)
# Create a dictionary to store file hashes
file_hashes = {}
# Iterate through files in the folder
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
# Get the file extension
_, extension = os.path.splitext(filename)
extension = extension.lower() # Convert extension to lowercase
# Determine the destination folder
if extension in extension_folders:
destination_folder = extension_folders[extension]
else:
destination_folder = os.path.join(folder_path,
extension[1:]) # Remove the leading dot from the extension
os.makedirs(destination_folder, exist_ok=True)
extension_folders[extension] = destination_folder
# Calculate the file hash
file_hash = get_file_hash(file_path)
# Check for duplicates
if file_hash in file_hashes:
# File is a duplicate, move it to the "Duplicates" folder
shutil.move(file_path, os.path.join(duplicates_folder, filename))
print(f"Moved duplicate file {filename} to Duplicates folder.")
else:
# Store the file hash
file_hashes[file_hash] = filename
# Move the file to the destination folder
shutil.move(file_path, destination_folder)
print(f"Moved {filename} to {destination_folder}")
if __name__ == "__main__":
folder_path = input("Enter the path to the folder to organize: ")
organize_and_move_duplicates(folder_path)
感谢你的阅读,希望坚持学习的你有所收获!今天的你是否比昨天的你更近一步呢?留言告诉我🫣🫣🫣
推荐阅读👇👇👇
Python高级编程:Functools模块的8个高级用法,强烈建议添加到你的开发工具箱中!
Python编程技巧:那些年后悔没有早知道string模块的这些宝藏功能~~~
Python效率秘籍:掌握这8个内存优化技巧,让你的代码飞起来!!!
成为Python高手:掌握这5个核心技能,迈入编程精英行列!
Python高级技术:10个显著优化你代码的Python OOP 技术
- END -
🌟 喜欢这篇文章吗?给个赞支持一下吧!🌟
如果你发现今天的内容对你有帮助,不妨点个赞并关注我,第一时间接收更多关于Python、数据分析和机器学习的深入分析和最新趋势。我们一起探索数据的力量,解锁AI的潜能。您的每一次互动都是对我的极大鼓励,也是我们共同成长的动力!
👇👇👇 关注并开启星标提醒,让知识与技能的火花不断在你的职业道路上燃烧吧!
原文作者:数据派探险家;如有侵权,请联系管理员删除。