Skip to content

Instantly share code, notes, and snippets.

@shahjugal
Created September 29, 2023 11:21
Show Gist options
  • Save shahjugal/d919a7201d40f64defa0c6f703b2fda1 to your computer and use it in GitHub Desktop.
Save shahjugal/d919a7201d40f64defa0c6f703b2fda1 to your computer and use it in GitHub Desktop.
Send my new Static IP Address to me whenever changes
## Add it in task scheduler. as python as binary and arguemeent as location of this script.
import requests
import smtplib
import os
from plyer import notification
# Email configuration
smtp_server = 'smtp-mail.outlook.com' # SMTP server address
smtp_port = 587 # SMTP server port
smtp_username = 'xxx@outlook.com' # Your email address
smtp_password = 'qAZ123WSX@!' # Your email password
recipient_emails = ['asdf@gmail.com', 'asd@ads.com', 'asd@gmail.com', 'info@asd.com', 'asd@asd.com'] # Recipient's email address
# File to store the previous IP address
ip_file_path = 'previous_ip.txt'
# Function to get the current external IP address
def get_external_ip():
try:
response = requests.get('https://api64.ipify.org?format=json')
data = response.json()
return data['ip']
except Exception as e:
print(f"Error getting external IP: {str(e)}")
return None
# Function to send an email to multiple recipients
def send_email(subject, message, recipients):
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
msg = f'Subject: {subject}\n\n{message}'
server.sendmail(smtp_username, recipient_emails, msg)
server.quit()
print("Email sent successfully to:", recipient_emails)
except Exception as e:
print(f"Error sending email: {str(e)}")
# Function to send a desktop notification
def send_notification(title, message):
notification.notify(
title=title,
message=message,
app_name="IP Monitor"
)
# Function to read the previous IP address from a file
def read_previous_ip():
if os.path.exists(ip_file_path):
with open(ip_file_path, 'r') as file:
return file.read().strip()
return None
# Function to write the current IP address to a file
def write_current_ip(ip):
with open(ip_file_path, 'w') as file:
file.write(ip)
# Get the previous IP address
previous_ip = read_previous_ip()
# Get the current IP address
current_ip = get_external_ip()
# Check if the IP address has changed
if current_ip and current_ip != previous_ip:
email_message = f"Your new static IP address is: {current_ip}"
send_email("IP Address Change", email_message, recipient_emails)
send_notification("IP Address Change", email_message)
write_current_ip(current_ip)
elif current_ip is None:
print("Could not fetch the current IP address. No notifications sent.")
else:
print("IP address has not changed. No notifications sent.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment