A Collection of Python Automation Scripts: Clipboard Manager, Code Quality Checker, File Integrity Verifier, Smart Trading Forecast, Image Downloader, Port Scanner, Password Manager, Email Sender, README Generator, and File Organizer
This article presents a curated set of Python automation scripts covering clipboard management, code quality analysis, file integrity verification, stock price forecasting, bulk image downloading, network port scanning, encrypted password storage, bulk email sending, README.md generation, and folder organization, each with explanations and complete source code.
This document provides a series of practical Python automation scripts, each accompanied by a brief description and the full source code.
1. Clipboard Manager
An application that monitors the system clipboard using pyperclip and displays copied text in a Tkinter GUI, allowing users to retrieve any previously copied snippet.
import tkinter as tk
from tkinter import ttk
import pyperclip
X = []
root = tk.Tk()
root.title("Clipboard Manager")
root.geometry("500x500")
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()2. Code Quality Checker
This script runs Pylint and Flake8 on every Python file in a given directory, printing the analysis results to help maintain clean, standards‑compliant code.
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.")
return
for file in python_files:
file_path = os.path.join(directory, file)
print(f"Analyzing file: {file}")
print("\nRunning pylint...")
subprocess.run(f"pylint {file_path}", shell=True)
print("\nRunning flake8...")
subprocess.run(f"flake8 {file_path}", shell=True)
if __name__ == "__main__":
directory = r"C:\Users\abhay\OneDrive\Desktop\Part7"
analyze_code(directory)3. File Integrity Checker
Computes the SHA‑256 hash of a file and compares it to an expected checksum to detect tampering.
import hashlib
import os
def calculate_sha256(file_path):
sha256 = hashlib.sha256()
with open(file_path, 'rb') as file:
for chunk in iter(lambda: file.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 path to 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 check failed: The file may have been tampered with.")
else:
print("Error: File not found.")4. Smart Trading Forecast
Uses Facebook's Prophet library together with yfinance and Streamlit to fetch historical stock data and forecast future prices for selected tickers.
import streamlit as st
from datetime import date
import yfinance as yf
from prophet import Prophet
from prophet.plot import plot_plotly
import plotly.graph_objs 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
def load_data(ticker):
data = yf.download(ticker, START, 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('Raw data')
st.write(data.tail())
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()
df_train = data[['Date', 'Close']].rename(columns={"Date": "ds", "Close": "y"})
model = Prophet()
model.fit(df_train)
future = model.make_future_dataframe(periods=period)
forecast = model.predict(future)
st.subheader('Forecast data')
st.write(forecast.tail())
st.write(f'Forecast plot for {n_years} years')
fig1 = plot_plotly(model, forecast)
st.plotly_chart(fig1)
st.write('Forecast components')
fig2 = model.plot_components(forecast)
st.write(fig2)5. Automatic Image Downloader
Downloads a specified number of images for a given keyword using the simple_image_download package.
from simple_image_download import simple_image_download as simp
response = simp.simple_image_download
keyword = "Dog"
try:
response().download(keyword, 20)
print("Images downloaded successfully.")
except Exception as e:
print("An error occurred:", e)6. Port Scanner
Scans a target host for a list of common ports and reports any open ports together with known vulnerabilities.
import socket
from prettytable import PrettyTable
vulnerabilities = {
80: "HTTP (unencrypted web traffic)",
443: "HTTPS (encrypted web traffic)",
22: "SSH (secure remote access)",
21: "FTP (file transfer)",
25: "SMTP (email transmission)",
23: "Telnet (remote terminal)",
53: "DNS (domain resolution)",
110: "POP3 (email retrieval)",
143: "IMAP (email retrieval)",
3306: "MySQL (database access)",
3389: "RDP (remote desktop)",
8080: "HTTP Alternate",
8000: "HTTP Alternate",
8443: "HTTPS Alternate",
5900: "VNC (remote desktop)"
}
def display_table(open_ports):
table = PrettyTable(["Open Port", "Vulnerability"])
for port in open_ports:
vuln = vulnerabilities.get(port, "No known vulnerabilities")
table.add_row([port, vuln])
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]
for port in top_ports:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
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()7. Password Manager
A Streamlit‑based web app that stores website credentials encrypted with a hard‑coded Fernet key, allowing users to save and retrieve passwords securely.
import streamlit as st
import csv
from cryptography.fernet import Fernet, InvalidToken
CUSTOM_ENCRYPTION_KEY = b'u7wGgNdDFefqpr_kGxb8wJf6XRVsRwvb3QgITsD5Ft4='
def encrypt_password(password):
cipher = Fernet(CUSTOM_ENCRYPTION_KEY)
return cipher.encrypt(password.encode())
def decrypt_password(enc):
if isinstance(enc, bytes):
try:
cipher = Fernet(CUSTOM_ENCRYPTION_KEY)
return cipher.decrypt(enc).decode()
except InvalidToken:
return "Invalid Token"
return None
def save_credentials(site, pwd):
enc = encrypt_password(pwd)
with open('credentials.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([site, enc.decode()])
def retrieve_password(site):
with open('credentials.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
if row[0] == site:
return row[1].encode()
return None
st.title("Password Manager")
website_name = st.text_input("Enter website name:")
password = st.text_input("Enter password:", type="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.")
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()):
enc = retrieve_password(website_name)
if enc:
dec = decrypt_password(enc)
st.success(f"Password for **{website_name}** -> **{dec}**")
else:
st.error("Password not found in database.")
else:
st.error("Invalid Encryption Key!!!")8. Email Bulk Sender
Sends mass emails through Gmail's SMTP server using SSL, with customizable subject and body.
import smtplib
import ssl
smtp_server = 'data.STUDIO.com'
smtp_port = 465
from_address = 'Winzo Shop'
to_address = ['', '']
username = ''
password = ''
subject = '🎉 Exclusive Offer Inside! Get 10% Off Your Next Purchase'
body = '''
Your promotional content here.
'''
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
server.set_debuglevel(1)
server.login(username, password)
message = f'From: {from_address}\r\nSubject: {subject}\r\nTo: {to_address}\r\n\r\n{body}'
server.sendmail(from_address, to_address, message.encode())9. README.md Generator
Interactively creates a README file for a GitHub repository, including badges for stars, forks, issues, and license.
def generate_markdown_file():
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()
stars_badge = f"[](https://github.com/{repository_name}/stargazers)"
forks_badge = f"[](https://github.com/{repository_name}/network/members)"
issues_badge = f"[](https://github.com/{repository_name}/issues)"
license_badge = f"[](https://github.com/{repository_name}/blob/master/LICENSE)"
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})
"""
markdown_file_name = f"{repository_name}_README.md"
with open(markdown_file_name, "w") as f:
f.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"}
print("Select a license for your project:")
for key, value in licenses.items():
print(f"{key}: {value}")
while True:
selected = input("Enter the number corresponding to your selected license: ")
if selected in licenses:
return licenses[selected]
else:
print("Invalid input. Please enter a valid license number.")
if __name__ == "__main__":
generate_markdown_file()10. OrganizeIT 2.0
Organizes a folder by moving files into subfolders based on their extensions and places duplicate files (identified by matching SHA‑256 hashes) into a dedicated "Duplicates" directory.
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):
extension_folders = {}
duplicates_folder = os.path.join(folder_path, 'Duplicates')
os.makedirs(duplicates_folder, exist_ok=True)
file_hashes = {}
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
_, ext = os.path.splitext(filename)
ext = ext.lower()
if ext in extension_folders:
dest = extension_folders[ext]
else:
dest = os.path.join(folder_path, ext[1:])
os.makedirs(dest, exist_ok=True)
extension_folders[ext] = dest
file_hash = get_file_hash(file_path)
if file_hash in file_hashes:
shutil.move(file_path, os.path.join(duplicates_folder, filename))
print(f"Moved duplicate file {filename} to Duplicates folder.")
else:
file_hashes[file_hash] = filename
shutil.move(file_path, dest)
print(f"Moved {filename} to {dest}")
if __name__ == "__main__":
folder_path = input("Enter the path to the folder to organize: ")
organize_and_move_duplicates(folder_path)Each script can be run independently and serves as a ready‑to‑use utility for common automation tasks.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.