ip2e/ip2e-daemon.py

292 lines
8.6 KiB
Python
Raw Normal View History

2015-10-27 12:25:17 +01:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# --------------------------------------------------------------
# ip2e (IP to email) - Run ip2e daemon. |
# Created by clamsawd (clamsawd@openmailbox.org) |
# Licensed by GPL v.3 |
# Last update: 16-02-2016 |
2015-10-27 12:25:17 +01:00
# |
# Compatible with Python 3.x |
# --------------------------------------------------------------
2015-12-01 19:07:37 +01:00
version="1.3.1"
2015-10-27 12:25:17 +01:00
#Import python-modules
2015-10-30 17:35:01 +01:00
import urllib
import urllib.request
2015-10-27 12:25:17 +01:00
import os
import sys
2015-10-29 11:31:16 +01:00
import time
2015-10-29 21:21:16 +01:00
import smtplib
import random
2015-10-27 12:25:17 +01:00
#Check if your system use Python 3.x
if sys.version_info<(3,0):
print ("")
print ("You need python 3.x to run this program.")
print ("")
2015-11-15 16:42:14 +01:00
exit()
2015-10-27 12:25:17 +01:00
#Function to clear screen
def ClearScreen():
if sys.platform == "cygwin":
print (300 * "\n")
elif os.name == "posix":
2015-10-27 12:25:17 +01:00
os.system("clear")
elif os.name == "nt":
os.system("cls")
else:
print ("Error: Unable clear screen")
2015-10-29 16:37:32 +01:00
2015-10-27 12:25:17 +01:00
#Detect system & PATH of user folder
2016-02-16 15:53:39 +01:00
if os.path.exists("/storage/sdcard0"):
HOMESCARD0="/storage/sdcard0/Android/data"
os.chdir(HOMESCARD0)
LogFile=HOMESCARD0+"/ip2e/ip2e.log"
LockFile=HOMESCARD0+"/ip2e/ip2e.lock"
print ("Android (Posix) detected")
elif os.name == "posix":
2015-10-27 12:25:17 +01:00
os.chdir(os.environ["HOME"])
2015-11-09 11:08:13 +01:00
LogFile=os.environ["HOME"]+"/.ip2e/ip2e.log"
LockFile=os.environ["HOME"]+"/.ip2e/ip2e.lock"
2016-02-16 15:53:39 +01:00
print ("Unix (Posix) detected")
2015-10-27 12:25:17 +01:00
elif os.name == "nt":
os.chdir(os.environ["USERPROFILE"])
2015-11-09 11:08:13 +01:00
LogFile=os.environ["USERPROFILE"]+"\\.ip2e\\ip2e.log"
LockFile=os.environ["USERPROFILE"]+"\\.ip2e\\ip2e.lock"
2015-10-27 12:25:17 +01:00
print ("Windows detected")
if not os.path.exists(".ip2e"):
os.makedirs(".ip2e")
os.chdir(".ip2e")
if os.path.exists(".ip2e"):
os.chdir(".ip2e")
#Check if exists 'ip2e.conf'
if os.path.isfile("ip2e.conf"):
print ("ip2e.conf exists")
2015-11-01 12:56:13 +01:00
else:
ClearScreen()
print ("")
print ("* The configuration file doesn't exist")
print ("")
print ("* You can create it if you run 'ip2e-config.py'")
print ("")
PauseExit=input("+ Press ENTER to exit ")
2015-11-15 16:42:14 +01:00
exit()
2015-10-27 12:25:17 +01:00
#Check if exists 'IP.log'
if os.path.isfile("IP.log"):
print ("IP.log exists")
2015-11-01 12:56:13 +01:00
else:
print ("IP.log created")
ip2eIPcf=open('IP.log','w')
2015-10-27 12:25:17 +01:00
ip2eIPcf.close()
ip2eIPcf=open('IP.log','a')
ip2eIPcf.write('0.0.0.0')
2015-10-27 12:25:17 +01:00
ip2eIPcf.close()
#Import variables from ip2e.conf
exec(open("ip2e.conf").read())
2015-10-27 12:25:17 +01:00
2015-10-30 08:45:47 +01:00
#Import native OS color scheme
try:
def GreenColor():
if os.name == "posix":
GreenColor = (chr(27)+"[1;32m")
print (GreenColor+"", end="")
elif os.name == "nt":
os.system("color 2")
def RedColor():
if os.name == "posix":
RedColor = (chr(27)+"[1;31m")
print (RedColor+"", end="")
elif os.name == "nt":
os.system("color 4")
def OrangeColor():
if os.name == "posix":
OrangeColor = (chr(27)+"[1;33m")
print (OrangeColor+"", end="")
elif os.name == "nt":
os.system("color 6")
def EndColor():
if os.name == "posix":
EndColor = (chr(27)+"[0m")
print (EndColor+"", end="")
elif os.name == "nt":
print ("", end="")
except:
print ("")
print ("* Error importing native color scheme")
print ("")
PauseExit=input("+ Press ENTER to exit ")
2015-11-15 16:42:14 +01:00
exit()
2015-10-29 16:31:45 +01:00
#Check if ip2e-daemon is running.
if os.path.isfile("ip2e.lock"):
readLock=open('ip2e.lock', 'r')
LockN=readLock.read()
readLock.close()
ClearScreen()
print ("Checking "+LockFile+"...")
time.sleep(4)
readLock2=open('ip2e.lock', 'r')
LockN2=readLock2.read()
readLock2.close()
if LockN != LockN2:
ClearScreen()
print ("")
print ("* ip2e-daemon is already running.")
print ("")
PauseExit=input("+ Press ENTER to exit ")
exit()
if not os.path.isfile("ip2e.lock"):
createLock=open('ip2e.lock','w')
createLock.write(str(random.randrange(135790)))
createLock.close()
#Function to lock process.
def LockProcess():
createLock=open('ip2e.lock','w')
createLock.write(str(random.randrange(135790)))
createLock.close()
2015-11-16 15:28:43 +01:00
#Function to sleep 'N' seconds.
def TimeSleep(N):
Time=1
2015-11-16 15:28:43 +01:00
while Time < N:
createLock=open('ip2e.lock','w')
createLock.write(str(random.randrange(135790)))
createLock.close()
time.sleep(1)
Time=Time + 1
2015-11-09 11:21:01 +01:00
#Check if exists a previous log.file
2015-10-29 18:47:09 +01:00
if os.path.isfile("ip2e.log"):
createlog=open('ip2e.log','w')
createlog.close()
2015-10-29 18:47:09 +01:00
2015-10-27 12:25:17 +01:00
#Run ip2e daemon
ClearScreen()
LockProcess()
2015-10-29 18:47:09 +01:00
editlog=open('ip2e.log','a')
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
2015-10-30 08:45:47 +01:00
GreenColor()
print ("[ip2e-daemon] ["+CurrentTime+"] Initialized ip2e-daemon v"+version+" (Ctrl+C to stop)")
2015-11-09 11:08:13 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] Log in "+LogFile)
EndColor()
2015-10-29 18:47:09 +01:00
editlog.write("[ip2e-daemon] ["+CurrentTime+"] Initialized ip2e-daemon v"+version+"\n")
2015-10-30 08:45:47 +01:00
OrangeColor()
print ("[ip2e-daemon] ["+CurrentTime+"] Waiting 60 seconds...")
EndColor()
2015-10-29 18:47:09 +01:00
editlog.write("[ip2e-daemon] ["+CurrentTime+"] Waiting 60 seconds...\n")
editlog.close()
2015-11-16 15:28:43 +01:00
TimeSleep(60)
2015-10-27 12:25:17 +01:00
PublicIP = 1
while PublicIP <= 2:
GetCurrentIP = 1
while GetCurrentIP <= 2:
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
LockProcess()
OrangeColor()
2015-10-30 08:45:47 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] IP Updating...")
EndColor()
2015-10-29 18:47:09 +01:00
editlog=open('ip2e.log','a')
editlog.write("[ip2e-daemon] ["+CurrentTime+"] IP Updating...\n")
2015-11-09 11:21:01 +01:00
#Check & get the new IP
2015-10-30 17:31:42 +01:00
try:
LockProcess()
2015-10-30 17:31:42 +01:00
response = urllib.request.urlopen('http://icanhazip.com')
#response = urllib.request.urlopen('http://ip.appspot.com/')
#response = urllib.request.urlopen('http://ident.me')
NewIPRaw = response.read()
NewIP = NewIPRaw.strip().decode('utf-8')
2015-10-27 12:25:17 +01:00
GetCurrentIP += 2
2015-10-30 17:31:42 +01:00
except:
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
LockProcess()
RedColor()
2015-10-30 08:45:47 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] Error getting IP")
2015-10-30 09:33:52 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] Retrying in 10 seconds...")
EndColor()
2015-10-29 18:47:09 +01:00
editlog.write("[ip2e-daemon] ["+CurrentTime+"] Error getting IP\n")
2015-10-30 09:33:52 +01:00
editlog.write("[ip2e-daemon] ["+CurrentTime+"] Retrying in 10 seconds...\n")
2015-11-16 15:28:43 +01:00
TimeSleep(10)
2015-11-09 11:21:01 +01:00
#Read IP log file & get the current IP
readfileIP=open('IP.log', 'r')
CurrentIPRaw=readfileIP.read()
CurrentIP=CurrentIPRaw.strip()
readfileIP.close()
LockProcess()
2015-11-09 11:21:01 +01:00
#Check if the IP has been renewed
2015-10-27 12:25:17 +01:00
if CurrentIP == NewIP:
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
LockProcess()
GreenColor()
2015-10-30 08:45:47 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] IP has not changed")
EndColor()
2015-10-29 18:47:09 +01:00
editlog.write("[ip2e-daemon] ["+CurrentTime+"] IP has not changed\n")
2015-10-27 12:25:17 +01:00
else:
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
LockProcess()
GreenColor()
2015-10-30 08:45:47 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] New IP - From "+CurrentIP+" to "+NewIP)
EndColor()
2015-10-29 18:47:09 +01:00
editlog.write("[ip2e-daemon] ["+CurrentTime+"] New IP - From "+CurrentIP+" to "+NewIP+"\n")
SendEmailOK = 1
while SendEmailOK <= 2:
LockProcess()
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
2015-10-29 21:21:16 +01:00
#Sending email using smtplib
SmtpSubject = "[ip2e-daemon] ["+CurrentTime+"] IP has changed"
2015-10-29 21:26:12 +01:00
SmtpHeader = "From: "+FromEmail+"\n"+"To: "+ToEmail+"\n"+"Subject: "+SmtpSubject+"\n"
2015-10-29 21:21:16 +01:00
SmtpBodyMessage = SmtpHeader+"\n"+"[ip2e] New IP is "+NewIP+"\n\n"
2015-10-30 09:33:52 +01:00
#Check sending errors
2015-10-29 22:01:25 +01:00
try:
server = smtplib.SMTP(SmtpFromEmail)
server.ehlo()
server.starttls()
server.ehlo()
server.login(FromEmailUser,FromEmailPass)
2015-10-29 21:21:16 +01:00
server.sendmail(FromEmail, ToEmail, SmtpBodyMessage)
server.quit()
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
MailMessage="[ip2e-daemon] ["+CurrentTime+"] Email was sent successfully"
LockProcess()
GreenColor()
2015-10-30 08:45:47 +01:00
print (MailMessage+" ("+ToEmail+")")
EndColor()
2015-10-30 09:33:52 +01:00
editlog.write(MailMessage+" ("+ToEmail+")\n")
SendEmailOK += 2
2015-10-30 09:33:52 +01:00
except:
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
LockProcess()
RedColor()
2015-10-30 09:33:52 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] Failed to connect ("+SmtpFromEmail+")")
print ("[ip2e-daemon] ["+CurrentTime+"] Check your settings or your connection")
EndColor()
2015-10-30 09:33:52 +01:00
editlog.write("[ip2e-daemon] ["+CurrentTime+"] Failed to connect ("+SmtpFromEmail+")\n")
editlog.write("[ip2e-daemon] ["+CurrentTime+"] Check your settings or your connection\n")
MailMessage="[ip2e-daemon] ["+CurrentTime+"] Failed to send email"
RedColor()
2015-10-30 08:45:47 +01:00
print (MailMessage+" ("+ToEmail+")")
2015-10-30 09:33:52 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] Retrying in 10 seconds...")
EndColor()
2015-10-30 09:33:52 +01:00
editlog.write(MailMessage+" ("+ToEmail+")\n")
editlog.write("[ip2e-daemon] ["+CurrentTime+"] Retrying in 10 seconds...\n")
2015-11-16 15:28:43 +01:00
TimeSleep(10)
2015-11-09 11:21:01 +01:00
#Remove the previous IP log file & create a new.
ip2eIPcf=open('IP.log','w')
ip2eIPcf.write(NewIP)
2015-11-01 15:47:02 +01:00
ip2eIPcf.close()
2015-11-09 11:21:01 +01:00
#Wait 10 minutes until the next checking
2015-10-29 11:31:16 +01:00
CurrentTime = time.strftime("%H:%M")
LockProcess()
GreenColor()
2015-10-30 08:45:47 +01:00
print ("[ip2e-daemon] ["+CurrentTime+"] Next update in 10 minutes...")
EndColor()
2015-10-29 18:47:09 +01:00
editlog.write("[ip2e-daemon] ["+CurrentTime+"] Next update in 10 minutes...\n")
editlog.close()
2015-11-16 15:28:43 +01:00
TimeSleep(600)