Skip to content

Commit

Permalink
Rebirth
Browse files Browse the repository at this point in the history
  • Loading branch information
iordic committed Sep 22, 2017
1 parent 07e973b commit 1063a50
Show file tree
Hide file tree
Showing 15 changed files with 352 additions and 32 deletions.
72 changes: 72 additions & 0 deletions .idea/markdown-navigator.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions .idea/markdown-navigator/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/preferred-vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 11 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# IPSender
Simple commandline tool to send public ip through e-mail. Thought to run as service.
Simple commandline tool to send public ip through e-mail.
Thought to run as service.

## How to use?
* Configure "mail.json" with your login credentials.
* Password requires base64 encoding, use codepass.py for this and encode your password.
![codepass](/img/screenshot.png)
* Set receiver address where program sends the IP.
* If you aren't using gmail, change smtp config.
* Configure _config.json_ with your login credentials.
See configuration section.
* Execute _ipsender.py_ and it will do the job. :)

## TO DO
- [x] Send e-mails to multiple addresses.
- [ ] Use encryption for the password field.
- [x] PEP8 Style
## Configuration
To configure credentials and server configuration, type:
```
python ipsender.py -c
```
And then fill the questions.
12 changes: 12 additions & 0 deletions data/config_template.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"login" : {
"user" : "[email protected]",
"password" : "3uNKNIrecDo=",
"key" : "XgKx/Uc5gq4="
},
"sender" : "[email protected]",
"receiver" : "[email protected]",
"protocol" : "smtp",
"server" : "smtp.gmail.com",
"port" : "587"
}
32 changes: 32 additions & 0 deletions data/message.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"messages" : [
{
"lang" : "en",
"text" : {
"subject" : "Current IP",
"ip" : "The public IP is: ",
"user" : "The logged user is: ",
"name" : "Computer name: ",
"os" : "Operating System: ",
"version" : "Version: ",
"release" : "Release: ",
"machine" : "Architecture: ",
"processor" : "Processor: "
}
},
{
"lang" : "es",
"text" : {
"subject" : "IP actual",
"ip" : "La IP publica es: ",
"user" : "El usuario identificado es: ",
"name" : "Nombre del ordenador: ",
"os" : "Sistema Operativo: ",
"version" : "Version: ",
"release" : "Release: ",
"machine" : "Arquitectura: ",
"processor" : "Procesador: "
}
}
]
}
86 changes: 64 additions & 22 deletions ipsender.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,75 @@
# Designed to run automatically (like a service).
# Jordi Castelló.
#
import smtplib, urllib2, json, base64
import smtplib
import urllib2
import sys
import platform
import base64
import getopt
import getpass
from email.mime.text import MIMEText
from parsers.Configuration import Configuration
from parsers.Message import Message
from tools.Obfuscator import Obfuscator

# Configuration constants
LANGUAGE = 'en' # Set desired language (ensure that exists in the JSON file).
CONFIGURATION_FILE = './data/config.json'
MESSAGE_FILE = './data/message.json'


def main(args):
if len(args) > 1: # If there aren't arguments execute normal script.
try:
opts, args = getopt.getopt(args[1:], "c", ["configure"])
for o, a in opts:
if o in ('-c', '--configure'):
configure()
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
else:
send_mail(LANGUAGE)


def send_mail(language):
""" Send an email with the IP from machine, all data values
are extracted from "mail.json" file. """
# Extract JSON file data:
with open('mail.json') as json_file:
data = json.load(json_file)
# data:
user = data['login']['user']
password = data['login']['pass']
password = base64.b64decode(password) # Decode password
sender = data['sender']
receivers = data['receivers']

server = data['smtp']
port = data['smtport']
server = server + ':' + port # Concatenate server and port
pubip = extract_public_ip() # Obtain public IP
msg = data['language'][language]['message'] + pubip
configuration = Configuration(CONFIGURATION_FILE)
message = Message(MESSAGE_FILE, language)
# Extract password
cpassword = base64.b64decode(configuration.password)
key = base64.b64decode(configuration.key)
obf = Obfuscator(cpassword, key) # Decrypt password
password = str(obf.cpassword) # Get decrypted password string
# Concatenate server and port
server = configuration.server + ':' + configuration.port
# Obtain information from computer
user = getpass.getuser()
# platform.uname() = (system, node, release, version, machine, processor)
platform_info = platform.uname()
public_ip = extract_public_ip() # Obtain public IP
msg = message.name + platform_info[1]
msg += '\n' + message.user + user
msg += '\n' + message.os + platform_info[0]
msg += '\n' + message.version + platform_info[2]
msg += '\n' + message.release + platform_info[3]
msg += '\n' + message.machine + platform_info[4]
msg += '\n' + message.processor + platform_info[5]
msg += '\n\n' + message.ip + public_ip
# Formatting e-mail:
mime_message = MIMEText(msg, "plain")
mime_message["From"] = sender
mime_message["To"] = receivers
mime_message["Subject"] = data['language'][language]['subject']
mime_message["From"] = configuration.sender
mime_message["To"] = configuration.receiver
mime_message["Subject"] = message.subject
# Sending e-mail:
server = smtplib.SMTP(server)
server.starttls()
server.login(user, password)
server.sendmail(sender, receivers.split(','), mime_message.as_string())
server.login(configuration.user, password)
server.sendmail(configuration.sender, configuration.receiver,
mime_message.as_string())
server.quit()


Expand All @@ -50,6 +87,11 @@ def extract_public_ip():
return public_ip


def configure():
""" Create the config.json file needed. This method is called
when the script is executed with '-c' or '--configure' argument """
config = Configuration(CONFIGURATION_FILE)
config.configure()

if __name__ == "__main__":
LANGUAGE = "en" # Set desired language (ensure that exists in the JSON file).
send_mail(LANGUAGE)
main(sys.argv)
65 changes: 65 additions & 0 deletions parsers/Configuration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import json
import os
import getpass
import base64
from tools.Obfuscator import Obfuscator


class Configuration:
def __init__(self, f):
self.file = f
if os.path.isfile(self.file):
self.load_data()
else:
raise Exception('File not found: config.json, try using -c parameter.')

def load_data(self):
""" Load the json data in the config.json file. """
try:
with open(self.file, 'r') as json_file:
self.data = json.load(json_file)
self.user = self.data['login']['user']
self.password = self.data['login']['password']
self.key = self.data['login']['key']
self.sender = self.data['sender']
self.receiver =self.data['receiver']
self.protocol = self.data['protocol']
self.server = self.data['server']
self.port = self.data['port']
except IOError as err:
print "Can't open file"

def update_file(self):
""" Replaces config.json file with the new data. """
with open(self.file, 'w') as json_file:
json.dump(self.data, json_file)

def configure(self):
""" Configuration method for creating the config.json file or replace it. """
with open('./data/config_template.json', 'r') as template:
json_data = json.load(template)
print '\nLogin configuration:'
print '===================='
json_data['login']['user'] = raw_input('Enter username: ')
password = getpass.getpass('Enter password: ')
o = Obfuscator(password)
json_data['login']['password'] = base64.b64encode(o.cpassword)
json_data['login']['key'] = base64.b64encode(o.key)
del o
print '\nE-mail options:'
print '================='
json_data['sender'] = raw_input('Enter the sender address: ')
json_data['receiver'] = raw_input('Enter the receiver address: ')
print '\nServer options:'
print '==============='
server = raw_input('Enter the server address (blank for smtp.gmail.com): ')
if server != '':
json_data['server'] = server
protocol = raw_input('Enter the protocol (blank for smtp): ')
if protocol != '':
json_data['protocol'] = protocol
port = raw_input('Enter the port (blank for 587): ')
if port != '':
json_data['port'] = port
self.data = json_data
self.update_file()
30 changes: 30 additions & 0 deletions parsers/Message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import json


class Message:
def __init__(self, f, lang='en'):
with open(f) as json_file:
data = json.load(json_file)
language_position = self.check_language(lang, data)
if language_position < 0:
self.language = 'en'
language_position = 0
else:
self.language = lang
self.subject = data['messages'][language_position]['text']['subject']
self.ip = data['messages'][language_position]['text']['ip']
self.user = data['messages'][language_position]['text']['user']
self.name = data['messages'][language_position]['text']['name']
self.os = data['messages'][language_position]['text']['os']
self.version = data['messages'][language_position]['text']['version']
self.release = data['messages'][language_position]['text']['release']
self.machine = data['messages'][language_position]['text']['machine']
self.processor = data['messages'][language_position]['text']['processor']

def check_language(self, lang, data):
""" Check if language exists on json file. If exists
return the language position. If not return -1. """
for i in range(0, len(data['messages'])):
if data['messages'][i]['lang'] == lang:
return i
return -1
Empty file added parsers/__init__.py
Empty file.
2 changes: 2 additions & 0 deletions runtests.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
:: Run all script tests from tests folder
python -m unittest discover tests
Empty file added tests/__init__.py
Empty file.
24 changes: 24 additions & 0 deletions tests/test_obfuscator_unittest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import unittest
from tools.Obfuscator import Obfuscator


class TestObfuscator(unittest.TestCase):

def setUp(self):
pass

def test_mix_keys(self):
""" Check the password encryption and decryption. """
# Password encryption
first = Obfuscator('1234')
first_key = first.key
first_cpassword = first.cpassword
# Password decryption
second = Obfuscator(first_cpassword, first_key)
# Decrypted password should be same as first password
expected = first.password
actual = second.cpassword
self.assertEqual(expected, actual)

if __name__ == '__main__':
unittest.main()
Loading

0 comments on commit 1063a50

Please sign in to comment.