Commit 06e723f2 authored by Björn's avatar Björn

adding

parent 373570bc
.config
\ No newline at end of file
.config
__pycache__
Error: "tock" not found!
Error: "g" not found!
Error: "test" not found!
## install
```bash
pip3 install python-gnupg
pip3 install configparser
```
```bash
nano ~/.bash_profile
export SMTP_SERVER=""
export SMTP_PORT=""
export SMTP_USERNAME=""
export SMTP_PASSWORD=""
export SMTP_AUTH_MODE=""
export SMTP_ENCRYPTION=""
export SMTP_FROM=""
export SMTP_TO=""
```
```bash
gpg --import <email>.pub.asc
gpg --edit-key <email>
gpg > trust
Your decision? 5 (Ultimate trust)
```
```bash
gpg --list-secret-keys --keyid-format LONG
```
```bash
sources=
remote_host=
remote_target=
remote_port=
gpg_key_id=
gpg_passphrase=
remove_older_than=s, m, h, D, W, M, Y (seconds, minutes, hours, days, weeks, months, years)
```
......@@ -2,7 +2,7 @@
#
#
#
class AddKey:
class Storagebox:
#
#
......@@ -10,4 +10,10 @@ class AddKey:
#
def __init__(self):
def add(self):
def run(self):
Storagebox()
#!/usr/bin/python3
#!/usr/bin/env python3
#
# backup
# backup
#
# usage: backup.py [-h] [--attachments ATTACHMENTS [ATTACHMENTS ...]]
# [--encrypt ENCRYPT]
# message subject
# usage: backup.py [-h] [-c CONFIG] [-d DESTINATION] [-f] command
#
# install to use:
#
# pip3 install python-gnupg
# pip3 install configparser
#
# max_age = s, m, h, D, W, M, Y (seconds, minutes, hours, days, weeks, months, years)
# positional arguments:
# command start|restore|status|files
# optional arguments:
# -h, --help show this help message and exit
# -c CONFIG, --config CONFIG
# full path to config-file
# -d DESTINATION, --destination DESTINATION
# destination for files
# -f, --force force current action
#
import argparse
......@@ -19,12 +20,15 @@ import configparser
import os
import subprocess
import paramiko
import platform
from src.sendmail import Sendmail
#
#
#
#
class BackupFiles:
class Backup:
#
#
......@@ -40,8 +44,15 @@ class BackupFiles:
# define options
parser.add_argument('-c', '--config', help='full path to config-file')
# for restore
parser.add_argument('-d', '--destination', help='destination for files')
parser.add_argument('-t', '--time', help='s, m, h, D, W, M, Y (seconds, minutes, hours, days, weeks, months, years)')
parser.add_argument('-f', '--force', help='force current action', action='store_true')
parser.add_argument('--file-to-restore', help='files to restore')
# sending email for output and error message
parser.add_argument('-s', '--sendmail', help='send log with', action='store_true')
# parse arguments
self._args = parser.parse_args()
......@@ -54,13 +65,19 @@ class BackupFiles:
self._config = configparser.RawConfigParser(allow_no_value=True)
self._config.read_file(open(config))
self._remote_port = self._config.get('default', 'remote_port', fallback='22')
self._logs = ''
#
# adding message to log-file
# adding message to log if sendmail is True
#
# @param message
#
def _log(self, message):
with open('01_01_2002.log', 'a') as f:
print(message, file=f)
if (self._args.sendmail == True):
self._logs += message
else:
print(message)
#
# generate string for source and adding all
......@@ -86,7 +103,7 @@ class BackupFiles:
# if includes is empty
if (includes == ''):
print('Error: no sources are found!')
self._log('Error: no sources are found!')
exit()
return includes
......@@ -106,22 +123,24 @@ class BackupFiles:
return 'PASSPHRASE="' + self._config.get('default', 'gpg_passphrase') + '"'
#
#
# create target with rsync
#
#
def _target(self):
return 'rsync://' + self._config.get('default', 'remote_host') + '/' + self._config.get('default', 'remote_target')
return 'rsync://' + self._config.get('default', 'remote_host') + ':' + self._remote_port + '/' + self._config.get('default', 'remote_target')
#
# create command for sftp
#
#
# @param command
#
def _sftp_command(self, command):
return "echo \"" + command + "\" | sftp -P 22 " + self._config.get('default', 'remote_host')
return "echo \"" + command + "\" | sftp -P " + self._remote_port + " " + self._config.get('default', 'remote_host')
#
# call subprocess
#
#
# @param command
#
def _command(self, command):
process = subprocess.run(command,
......@@ -173,11 +192,8 @@ class BackupFiles:
includes = self._includes()
process = self._command(self._gpg_passphrase() + ' duplicity full ' + includes + ' ' + self._gpg_key_id() + ' ' + self._target())
out = process.stdout
error = process.stderr
print(out)
print(error)
self._log(process.stdout)
self._log(process.stderr)
#
# restore
......@@ -189,20 +205,24 @@ class BackupFiles:
# if destination already exists and --force is not set
if (os.path.exists(self._args.destination) and self._args.force == False):
print('Error! Destination exists! Add --force to overwrite!')
self._log('Error! Destination exists! Add --force to overwrite!')
exit()
# adding force
if self._args.force == True:
options += ' --force'
process = self._command(self._gpg_passphrase() + ' duplicity restore ' + self._target() + ' ' + self._args.destination + options)
# adding time
if self._args.time == True:
options += ' --time ' + self._args.time
out = process.stdout
error = process.stderr
# adding time
if self._args.file_to_restore == True:
options += ' --file-to-restore ' + self._args.file_to_restore
print(out)
print(error)
process = self._command(self._gpg_passphrase() + ' duplicity restore ' + self._target() + ' ' + self._args.destination + options)
self._log(process.stdout)
self._log(process.stderr)
#
# list current files
......@@ -210,12 +230,8 @@ class BackupFiles:
#
def _files(self):
process = self._command('duplicity list-current-files ' + self._target())
out = process.stdout
error = process.stderr
print(out)
print(error)
self._log(process.stdout)
self._log(process.stderr)
#
# getting status of collection
......@@ -223,12 +239,8 @@ class BackupFiles:
#
def _status(self):
process = self._command('duplicity collection-status ' + self._target())
out = process.stdout
error = process.stderr
print(out)
print(error)
self._log(process.stdout)
self._log(process.stderr)
#
# delete old backups files in target,
......@@ -240,11 +252,9 @@ class BackupFiles:
remove_older_than = self._config.get('default', 'remove_older_than')
process = self._command('duplicity remove-older-than ' + remove_older_than + ' --force ' + self._target())
out = process.stdout
error = process.stderr
print(out)
print(error)
# add log
self._log(process.stdout)
self._log(process.stderr)
#
#
......@@ -253,6 +263,7 @@ class BackupFiles:
def run(self):
if (self._args.command == 'start'):
self._start()
self._clean()
elif (self._args.command == 'restore'):
self._restore()
elif (self._args.command == 'status'):
......@@ -260,9 +271,11 @@ class BackupFiles:
elif (self._args.command == 'files'):
self._files()
self._clean()
# send mail
if (self._args.sendmail == True):
sendmail = Sendmail(self._logs, 'Backup / ' + self._args.command + ' / ' + platform.uname()[1])
sendmail.run()
# let it rain
backup = BackupFiles()
backup = Backup()
backup.run()
#
#
#
#
class Mysqldump:
#
#
#
#
def __init__(self):
def add(self):
def run(self):
mysqldump = Mysqldump()
mysqldump.run()
#!/usr/bin/python3
#
# sending email
# send and encrpty email with gpg
#
# usage: sendmail.py [-h] [--attachments ATTACHMENTS [ATTACHMENTS ...]]
# [--encrypt ENCRYPT]
# message subject
#
# install to use:
#
# apt-get install python-pip
# pip install python-gnupg
#
# nano ~/.bash_profile
# export SMTP_SERVER=""
# export SMTP_PORT=""
# export SMTP_USERNAME=""
# export SMTP_PASSWORD=""
# export SMTP_AUTH_MODE=""
# export SMTP_ENCRYPTION=""
# export SMTP_FROM=""
# export SMTP_TO=""
#
# gpg --import <email>.pub.asc
# gpg --edit-key <email>
# gpg > trust
# Your decision? 5 (Ultimate trust)
#
import argparse
import os
import gnupg
import getpass
# stuff for sending emails
import smtplib, email
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#
#
#
......@@ -42,9 +23,11 @@ class Sendmail:
#
#
# @param message
# @param subject
# @param options { encrypt: True or False }
#
#
def __init__(self):
def __init__(self, message, subject):
self._config = {
'SMTP_PORT': 465
......@@ -61,33 +44,21 @@ class Sendmail:
'SMTP_TO'
]
# adding parser for arguments
parser = argparse.ArgumentParser()
self._message = message
self._subject = subject
# define arguments
parser.add_argument('message', help='message to send')
parser.add_argument('subject', help='subject for message')
parser.add_argument('--attachments', nargs='+', help='attach files')
parser.add_argument('--encrypt', default=False, type=lambda x: (str(x).lower() in ['true','1', 'yes']), help='encrypt with gpg')
# parsering arguments
self._args = parser.parse_args()
self._validate_arguments(self._args)
self._validate_config()
#
#
# send message
#
#
def run(self):
message = self._create_message(self._args, self._config)
if self._args.encrypt:
message = self._encrypt_message(message, self._args, self._config)
message = self._create_message(self._message)
message = self._encrypt_message(message)
self._send(message, self._config)
self._send(message)
#
#
......@@ -105,69 +76,35 @@ class Sendmail:
print('Environment variable "' + key + '" not found!')
exit()
#
#
#
#
def _validate_arguments(self, args):
# if attachments not exists and file also not, exit
if args.attachments:
for attachment in args.attachments:
if not os.path.isfile(attachment):
print('Attachment "' + attachment + '" not found!')
exit()
#
# creating message
#
#
def _create_message(self, args, config):
def _create_message(self, message):
message = email.MIMEMultipart.MIMEMultipart()
body = email.MIMEText.MIMEText(args.message)
multipart = MIMEMultipart()
body = MIMEText(message)
# attach body
message.attach(body)
if args.attachments:
for attachment in args.attachments:
message.attach(self._add_attachment(attachment))
message.add_header('Subject', args.subject)
message.add_header('From', config['SMTP_FROM'])
message.add_header('To', config['SMTP_TO'])
return message
#
# adding attachment and encode to base64
#
#
def _add_attachment(self, attachment):
message = email.MIMEBase.MIMEBase('application', 'octet-stream')
multipart.attach(body)
# adding header
message.add_header('Content-Type', 'application/octet-stream', filename=os.path.basename(attachment))
message.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment))
multipart.add_header('Subject', self._subject)
multipart.add_header('From', self._config['SMTP_FROM'])
multipart.add_header('To', self._config['SMTP_TO'])
message.set_payload(open(attachment, 'rb').read())
email.encoders.encode_base64(message)
return message
return multipart
#
# encrypt message
#
#
def _encrypt_message(self, message, args, config):
def _encrypt_message(self, message):
encrypted = email.MIMEBase.MIMEBase('multipart', _subtype='encrypted', protocol='application/pgp-encrypted')
encrypted = MIMEBase('multipart', _subtype='encrypted', protocol='application/pgp-encrypted')
encrypted.add_header('Subject', args.subject)
encrypted.add_header('From', config['SMTP_FROM'])
encrypted.add_header('To', config['SMTP_TO'])
encrypted.add_header('Subject', self._subject)
encrypted.add_header('From', self._config['SMTP_FROM'])
encrypted.add_header('To', self._config['SMTP_TO'])
# adding headers
encrypted_header = email.message.Message()
......@@ -181,14 +118,14 @@ class Sendmail:
encrypted_message.add_header('Content-Description', 'OpenPGP encrypted message')
encrypted_message.add_header('Content-Disposition', 'inline')
if (os.getlogin() == 'root'):
if (getpass.getuser() == 'root'):
gpgpath = '/root/.gnupg'
else:
gpgpath = '/home/' + os.getlogin() + '/.gnupg'
gpgpath = '/home/' + getpass.getuser() + '/.gnupg'
gpg = gnupg.GPG(gnupghome=gpgpath)
message = str(gpg.encrypt(message.as_string(), config['SMTP_TO']))
message = str(gpg.encrypt(message.as_string(), self._config['SMTP_TO']))
encrypted_message.set_payload(message)
encrypted.attach(encrypted_header)
......@@ -202,24 +139,19 @@ class Sendmail:
# @param config
# @param message
#
def _send(self, message, config):
def _send(self, message):
# Now send the message
try:
if config['SMTP_ENCRYPTION'] == 'ssl' or config['SMTP_ENCRYPTION'] == 'tls':
mailer = smtplib.SMTP_SSL(config['SMTP_SERVER'], config['SMTP_PORT'])
if self._config['SMTP_ENCRYPTION'] == 'ssl' or self._config['SMTP_ENCRYPTION'] == 'tls':
mailer = smtplib.SMTP_SSL(self._config['SMTP_SERVER'], self._config['SMTP_PORT'])
else:
mailer = smtplib.SMTP(config['SMTP_SERVER'], config['SMTP_PORT'])
mailer = smtplib.SMTP(self._config['SMTP_SERVER'], self._config['SMTP_PORT'])
except Exception as exception:
print('SMTP Error!')
print(exception)
exit()
mailer.login(config['SMTP_USERNAME'], config['SMTP_PASSWORD'])
mailer.sendmail(config['SMTP_FROM'], config['SMTP_TO'], message.as_string())
mailer.login(self._config['SMTP_USERNAME'], self._config['SMTP_PASSWORD'])
mailer.sendmail(self._config['SMTP_FROM'], self._config['SMTP_TO'], message.as_string())
mailer.close()
# let it rain
sendmail = Sendmail()
sendmail.run()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment