-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublic_ip_handler.py
executable file
·54 lines (44 loc) · 1.77 KB
/
public_ip_handler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
__author__ = 'Hamza Merzic'
__license__ = 'Creative Commons Attribution-ShareAlike 3.0 Unported License'
__version__ = '1.0'
__maintainer__ = 'Hamza Merzic'
import subprocess
import smtplib
from email.mime.text import MIMEText
import datetime
# Your own accounts' information.
to = '[email protected]' # Email to send to.
gmail_user = '[email protected]' # Email to send from. (MUST BE GMAIL)
gmail_password = 'senderspassword' # Gmail password.
smtpserver = smtplib.SMTP('smtp.gmail.com', 587) # Server to use.
smtpserver.ehlo() # Says 'hello' to the server
smtpserver.starttls() # Start TLS encryption
smtpserver.ehlo()
smtpserver.login(gmail_user, gmail_password) # Log in to server
today = datetime.date.today() # Get current time/date
arg = 'touch ~/stored_ip; cat ~/stored_ip'
# Run 'arg' in a 'hidden terminal'.
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate() # Get data from 'p terminal'.
# Get previous ip.
previous_ip = str(data[0])
arg = "curl -s checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//\'" # Linux command to retrieve public ip address.
p = subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate()
# Get current ip.
current_ip = str(data[0])
if previous_ip == current_ip:
smtpserver.quit()
exit()
# Create the text, subject, 'from', and 'to' of the message.
msg = MIMEText("Your public ip is " + current_ip[:-1] + ".")
msg['Subject'] = "RaspberryPi's public IP on %s" % today.strftime('%b %d %Y')
msg['From'] = gmail_user
msg['To'] = to
# Send the message.
smtpserver.sendmail(gmail_user, [to], msg.as_string())
# Close the smtp server.
smtpserver.quit()
# Store the new IP.
arg = "echo " + current_ip[:-1] + " > ~/stored_ip"
p = subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)