Skip to content

Instantly share code, notes, and snippets.

@fernandozamoraj
Last active March 31, 2017 04:46
Show Gist options
  • Save fernandozamoraj/3fe74603e8114a90f56c2ecdd8db9504 to your computer and use it in GitHub Desktop.
Save fernandozamoraj/3fe74603e8114a90f56c2ecdd8db9504 to your computer and use it in GitHub Desktop.
This script can be used to help you monitor your box's IP. That way you always know what IP to remote into.
import socket
import smtplib
import sys
from time import sleep
from email.mime.text import MIMEText
FILE_NAME = '/dev/last_known_ip.dat'
TIME_INTERVAL = 600 #600 = 10 minutes
FROM = '[email protected]'
TO = '[email protected]'
EMAIL_SERVER = 'YOUREMAILSERVER'
def get_last_known_ip():
last_ip = ''
try:
with open(FILE_NAME, 'r') as fr:
last_ip = fr.readline()
except Exception as e:
print('Error reading ' + FILE_NAME)
print(e)
return last_ip
def send_email_notification(host_ip):
try:
print('Sending email')
msg = MIMEText('The host has changed to : ' + host_ip)
msg['Subject'] = 'your box\'s ip has changed again'
msg['From'] = FROM
msg['To'] = TO
s = smtplib.SMTP(EMAIL_SERVER)
s.sendmail(FROM, TO, msg.as_string())
except Exception as e:
print('Failed to send email')
print(e)
def save_new_ip(host_ip):
try:
print('Saving new ip')
with open(FILE_NAME, 'w') as fw:
fw.write(host_ip)
except Exception as e:
print('Failed to save new ip:')
print(e)
def check_ip():
saved_ip = ''
host_ip = socket.gethostbyname(socket.gethostname())
print(host_ip)
saved_ip = get_last_known_ip()
ip_has_changed = (saved_ip != host_ip)
if(ip_has_changed):
send_email_notification(host_ip)
save_new_ip(host_ip)
else:
print('ip has not changed')
try:
while True:
check_ip()
sleep(TIME_INTERVAL)
except KeyboardInterrupt:
print("Quitting the program")
except:
print("Unexpected error: " + sys.exc_info()[0])
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment