|
| 1 | +import subprocess |
| 2 | +import sys |
| 3 | +import time |
| 4 | +import socket |
| 5 | +from getpass import getpass |
| 6 | +import smtplib |
| 7 | +from email.mime.text import MIMEText |
| 8 | +from email.mime.multipart import MIMEMultipart |
| 9 | + |
| 10 | + |
| 11 | +user_email = input("Enter your email: ") |
| 12 | +user_password = getpass() |
| 13 | +smtp_server = "smtp.gmail.com" |
| 14 | +smtp_port = 587 # Port 587 for TLS |
| 15 | + |
| 16 | + |
| 17 | +def send_text_email(subject, message, recipient_email, sender_email, sender_password, smtp_server, smtp_port): |
| 18 | + # Create a text/plain message |
| 19 | + msg = MIMEMultipart() |
| 20 | + msg['From'] = sender_email |
| 21 | + msg['To'] = recipient_email |
| 22 | + msg['Subject'] = subject |
| 23 | + |
| 24 | + # Attach the text message |
| 25 | + msg.attach(MIMEText(message, 'plain')) |
| 26 | + |
| 27 | + # Connect to the SMTP server |
| 28 | + try: |
| 29 | + server = smtplib.SMTP(smtp_server, smtp_port) |
| 30 | + server.starttls() |
| 31 | + server.login(sender_email, sender_password) |
| 32 | + text = msg.as_string() |
| 33 | + server.sendmail(sender_email, recipient_email, text) |
| 34 | + server.quit() |
| 35 | + except Exception as e: |
| 36 | + print(f"Email could not be sent: {str(e)}") |
| 37 | + |
| 38 | + |
| 39 | +def run_then_notify(command): |
| 40 | + try: |
| 41 | + start_time = time.time() |
| 42 | + completed_process = subprocess.run( |
| 43 | + command, |
| 44 | + text=True, |
| 45 | + shell=True, |
| 46 | + stdout=sys.stdout, |
| 47 | + stderr=subprocess.STDOUT, |
| 48 | + stdin=sys.stdin |
| 49 | + ) |
| 50 | + |
| 51 | + end_time = time.time() |
| 52 | + execution_time = end_time - start_time |
| 53 | + |
| 54 | + notif_subject = '[Run completed] Your command finished execution' |
| 55 | + notif_message = f"Command '{command}' completed\n\ |
| 56 | + \twith exit code {completed_process.returncode}\n\ |
| 57 | + \tin {execution_time:.2f} seconds\n\ |
| 58 | + \n\ |
| 59 | + This is an automated message sent from your device {socket.gethostname()}" |
| 60 | + |
| 61 | + send_text_email( |
| 62 | + subject=notif_subject, |
| 63 | + message=notif_message, |
| 64 | + recipient_email=user_email, |
| 65 | + sender_email=user_email, |
| 66 | + sender_password=user_password, |
| 67 | + smtp_server=smtp_server, |
| 68 | + smtp_port=smtp_port |
| 69 | + ) |
| 70 | + |
| 71 | + except Exception as e: |
| 72 | + print(f"Error: {e}") |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + if len(sys.argv) != 2: |
| 77 | + print("Usage: python run_then_notify.py 'your_command_here'") |
| 78 | + sys.exit(1) |
| 79 | + |
| 80 | + command = sys.argv[1] |
| 81 | + run_then_notify(command) |
0 commit comments