Purpose: Automatically remove temporary and log files.
import os
downloads = "C:/Users/jonathan/Downloads"
for file in os.listdir(downloads):
if file.endswith(".tmp") or file.endswith(".log"):
os.remove(os.path.join(downloads, file))
Explanation: Cleans repetitive clutter, freeing space for better performance.
Purpose: Detect high CPU usage processes.
import psutil
for proc in psutil.process_iter(['pid','name','cpu_percent']):
if proc.info['cpu_percent'] > 80:
print(f"High CPU: {proc.info['name']} ({proc.info['cpu_percent']}%)")
Explanation: Helps IT staff proactively address resource hogs.
Purpose: Backup critical documents daily.
import shutil, datetime
src = "C:/Users/jonathan/Documents"
dst = f"C:/Backup/{datetime.date.today()}"
shutil.copytree(src, dst)
Explanation: Creates timestamped backups to prevent data loss.
Purpose: Monitor internet or VPN connectivity.
import os
hostname = "8.8.8.8"
response = os.system(f"ping -n 1 {hostname}")
if response != 0:
print("Network down!")
Explanation: Preempts helpdesk tickets for connectivity issues.
Purpose: Notify IT team on critical events.
import smtplib
sender = "itadmin@example.com"
receiver = "helpdesk@example.com"
message = "Subject: Alert\n\nDisk space low on Laptop-01"
with smtplib.SMTP('smtp.example.com') as server:
server.sendmail(sender, receiver, message)
Explanation: Reduces manual notification workload.
Purpose: Analyze logs for failures or security events.
import json
with open("sign_in_logs.json") as f:
logs = json.load(f)
failed_signins = [log for log in logs if log["status"]=="Failure"]
print(failed_signins)
Explanation: Useful for auditing and proactive security monitoring.
Purpose: Record PC screen for troubleshooting.
import pyautogui, datetime
filename = f"screenshot_{datetime.datetime.now().strftime('%Y%m%d_%H%M')}.png"
pyautogui.screenshot(filename)
Explanation: Visual documentation of issues for support tickets.
Purpose: Detect application errors visually.
import cv2
img = cv2.imread("screen.png", 0)
template = cv2.imread("error_template.png", 0)
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
if res.max() > 0.8:
print("Error detected! Restart app.")
Explanation: Useful for apps without API endpoints.
Purpose: Automate new hire onboarding.
import subprocess
subprocess.run(["powershell", "New-AzureADUser -DisplayName 'John Doe' -UserPrincipalName 'j.doe@example.com' -AccountEnabled $true"])
Explanation: Speeds up account creation.
Purpose: Automate daily/weekly tasks on PCs.
import subprocess
subprocess.run([
"schtasks", "/create", "/tn", "DailyBackup", "/tr", "C:\\backup.py", "/sc", "daily", "/st", "09:00"
])
Explanation: Reduces errors in manual scheduling.
Purpose: Combine all scripts into one automated loop.
import os, shutil, datetime, psutil, json, smtplib, pyautogui, cv2, subprocess
# Configurations omitted for brevity
def log_event(event):
... # JSON logging
def send_email(subject, body):
... # Email alert
def cleanup_files(): ...
def backup_documents(): ...
def monitor_processes(): ...
def network_check(): ...
def capture_screenshot(): ...
def opencv_error_detection(): ...
def parse_json_logs(): ...
def user_provisioning(): ...
def schedule_tasks(): ...
def main():
cleanup_files()
backup_documents()
network_check()
monitor_processes()
capture_screenshot()
opencv_error_detection()
parse_json_logs()
user_provisioning()
schedule_tasks()
if __name__ == "__main__":
main()
Explanation: Orchestrates all automated tasks, logs results, triggers alerts.
Purpose: Monitor multiple servers, parse metrics, log, and send HTML report.
import requests, json, smtplib, datetime
from bs4 import BeautifulSoup
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
SERVERS = [ ... ] # List of server dicts
# Functions: fetch_metrics, log_json, send_html_email
# Loop through servers, parse CPU/Memory, generate HTML report
# Send email if thresholds exceeded
Explanation: Centralized monitoring for multiple servers with visual HTML report and alerting.
Purpose: Send formatted emails via Python.
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
msg = MIMEMultipart("alternative")
msg.attach(MIMEText(text, "plain"))
msg.attach(MIMEText(html, "html"))
# Send via smtplib
Explanation: Provides rich text and fallback plain text in alerts.
HTML: Markup language defining page content.
HTTP: Protocol to transfer HTML or other data from server to client.
Python Automation: requests.get() for HTTP, BeautifulSoup for HTML parsing.
Open Task Scheduler: Win + R → taskschd.msc
Run task immediately: schtasks /run /tn "Python Automation Orchestrator"
Create scheduled task via command line:
schtasks /create /tn "DailyAutomation" /tr "C:\Python39\python.exe C:\Scripts\master_automation.py" /sc daily /st 09:00
Explanation: Automates execution of Python orchestrator across PCs or remote environments.
Task Scheduler --> Python Orchestrator --> [Disk Cleanup, Backup, Network Check, Process Monitor, Screenshot, OpenCV, JSON Logging, User Provisioning, Scheduling] --> Email Alerts
Multiple Servers (HTTP Dashboards) --> Python Fetch & Parse --> JSON Logs + HTML Table Report --> Email Alerts to Helpdesk
Explanation: Visualizes how automated scripts interact with servers, logs, and alerting systems for full IT monitoring.
This document now includes all code, explanations, and workflow diagrams for comprehensive IT automation and monitoring guidance.