Skip to content

Instantly share code, notes, and snippets.

@harmonbc
Created November 4, 2012 16:52
Show Gist options
  • Save harmonbc/4012577 to your computer and use it in GitHub Desktop.
Save harmonbc/4012577 to your computer and use it in GitHub Desktop.
Get public IP
#!/usr/bin/env python3
import urllib.request
import sys
import smtplib
import os
#Sending text alert
def send(body, to="#Email Address to send to", username = "#User Name @gmail.com", password="#Password"):
mail_server= smtplib.SMTP("smtp.gmail.com", 587)
mail_server.ehlo()
mail_server.starttls()
mail_server.ehlo()
mail_server.login(username, password)
mail_server.sendmail(username, to, body)
mail_server.close()
#If running a VPN quit
os.system('iwconfig > temp')
data = open("temp").read()
if "tun0" in data:
print("VPN Running, Exiting")
os.system("rm temp")
sys.exit(0)
os.system("rm temp")
#Get the last IP address
ip_file = os.open("IPAddr", os.O_RDWR | os.O_CREAT)
last_ip = os.read(ip_file, 100)
os.close(ip_file)
#Get the current IP address
f = urllib.request.urlopen("http://ifconfig.me/ip")
current_ip = f.read().decode('utf8')
#Compare the IP addresses
if(current_ip!=last_ip):
out_file = open("IPAddr", "wt")
out_file.write(current_ip)
send(current_ip)
out_file.close()
@harmonbc
Copy link
Author

harmonbc commented Nov 4, 2012

This is my first attempt at a Python script. This will update a person whenever your public IP address changes. This is used by me so I will always know my home IP address, since it is assigned dynamically. In my version I used the email field to forward a text to my phone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment