Operations 9 min read

10 Practical Python Automation Scripts for Daily Operations

This article presents ten ready‑to‑use Python scripts that automate common operational tasks such as file backup, scheduled email reminders, web scraping, bulk image renaming, log analysis, folder synchronization, database backup, API monitoring, performance testing, and CI/CD deployment.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
10 Practical Python Automation Scripts for Daily Operations

1. Automatic File Backup – A script that copies a specified file to a backup folder with a timestamped name.

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}")
# Example usage
backup_file("/path/to/important_file.txt", "/path/to/backup_folder")

2. Scheduled Email Reminder – Sends a daily reminder email at 09:00 using schedule and smtplib.

import smtplib
from email.mime.text import MIMEText
from email.header import Header
import schedule
import time

def send_email():
    sender = '[email protected]'
    receiver = '[email protected]'
    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. Web‑page News Title Scraper – Retrieves all h2 elements from a news page.

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')  # assume titles are in h2 tags
    for title in titles:
        print(title.text.strip())
# Example usage
scrape_news_titles('https://news.example.com/latest-news')

4. Bulk Image Renaming – Renames all JPG/PNG files in a directory with a timestamp and index.

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))
# Example usage
rename_files('/path/to/images/folder')

5. Log File Error Counter – Counts occurrences of a specific error keyword in a log file.

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.")
# Example usage
analyze_logs('/var/log/application.log', 'Error 500')

6. Folder Synchronization via rsync – Synchronizes a local directory to a remote server using rsync over SSH.

import subprocess

def sync_folders(local_dir, remote_host, remote_dir, username):
    # Build rsync command
    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}")
# Example usage
sync_folders('/local/path', 'remote.host.com', '/remote/path', 'user')

7. MySQL Database Backup – Dumps a MySQL database to a timestamped SQL file.

import os
import subprocess
from datetime import datetime

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}")
# Example usage
mysql_backup('mydb', 'dbuser', 'dbpassword', '/path/to/backups')

8. API Monitoring and Alert – Checks an API endpoint and sends an email alert if the status code differs from the expected one.

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.")
# Example usage
monitor_api('https://api.example.com/health', 200, '[email protected]', '[email protected]', 'password')

9. Performance Load Test with Locust – Simulates concurrent users to stress‑test a web service.

from locust import HttpUser, task, between

class WebsiteUser(HttpUser):
    wait_time = between(5, 15)

    @task
    def load_test(self):
        self.client.get("/")
# Run with: locust -f performance_test.py --host=https://targetsite.com --users=1000 --spawn-rate=100

10. CI/CD Deployment Script (Fabric) – Deploys a built archive to a production server via SSH.

from fabric import Connection
from invoke import run
import os

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")
# Example usage
deploy_production('production.server.com', 'deployuser', '/path/to/app.tar.gz')
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAutomationOperationsDevOpsScripting
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.