#!/bin/env python
# Directory backup on SMB (samba) share via VPN or locally for EM-SERIOUS.ORG
# Author : Stephen LARROQUE <lrq3000@gmail.com>
# DESCRIPTION : Zip-date the specified directory by user and send it to a remote (via vpn) or local filesharing server to the fictious servers of the fictious enterprise called EM-SERIOUS.ORG by using SMB shares. If no connection could be made, the backup is stored in the same folder as the script and user is notified.
# License : LGPL v3 -> for complete instructions see http://www.gnu.org/licenses/lgpl-3.0.html
import smb, nmb, getpass, os, zipfile, time;
import easygui as gui
import sys
#######################################################
################### FUNCTIONS ########################
#######################################################
def makeArchive(fileList, archive):
"""
'fileList' is a list of file names - full path each name
'archive' is the file name for the archive with a full path
"""
try:
a = zipfile.ZipFile(archive, 'w', zipfile.ZIP_DEFLATED)
for f in fileList:
print "archiving file %s" % (f)
a.write(f)
a.close()
return True
except: return False
-
def dirEntries(dir_name, subdir, *args):
'''Return a list of file names found in directory 'dir_name'
If 'subdir' is True, recursively access subdirectories under 'dir_name'.
Additional arguments, if any, are file extensions to match filenames. Matched
file names are added to the list.
If there are no additional arguments, all files found in the directory are
added to the list.
Example usage: fileList = dirEntries(r'H:\TEMP', False, 'txt', 'py')
Only files with 'txt' and 'py' extensions will be added to the list.
Example usage: fileList = dirEntries(r'H:\TEMP', True)
All files and all the files in subdirectories under H:\TEMP will be added
to the list.
'''
fileList = []
for file in os.listdir(dir_name):
dirfile = os.path.join(dir_name, file)
if os.path.isfile(dirfile):
if not args:
fileList.append(dirfile)
else:
if os.path.splitext(dirfile)[1][1:] in args:
fileList.append(dirfile)
# recursively access file names in subdirectories
elif os.path.isdir(dirfile) and subdir:
print "Accessing directory:", dirfile
fileList.extend(dirEntries(dirfile, subdir, *args))
return fileList
def SMBSEND (servername, serverip, login, password, group, filepath, zipname):
-
print 'Connecting to server ' + serverip + ' with name ' + servername;
fileshare = smb.SMB(servername, serverip, my_name = "ClientBackup", host_type = nmb.TYPE_SERVER, sess_port = nmb.NETBIOS_SESSION_PORT);
print 'Success !';
if (login == ''):
if (fileshare.is_login_required()) :
print "Login is required to connect to this SMB sharing server !";
sys.exit();
else :
print 'Identification...';
fileshare.login(login, password)
print 'Success !';
print 'Connecting to domain ' + fileshare.get_server_os() + ' lanname ' + fileshare.get_server_lanman() + ' running OS ' + fileshare.get_server_os();
-
#print 'Listing shares...'
#print fileshare.list_shared();
-
print 'Checking path exists...';
if ( fileshare.list_path( group, os.path.join(filepath, '\*') ) ):
print "Dir exists !";
print 'Succeed';
print 'Sending file to server...';
src_path = zipname;
dest_service = group;
dest_path = os.path.join(filepath, zipname);
fh = open(src_path, 'rb');
fileshare.stor_file(dest_service, dest_path, fh.read);
fh.close();
print 'Success !';
def VPNCONNECT ():
print os.name
if (os.name == "nt"):
import vpnwin.py;
Connect("vpn.em-serious.org");
elif (os.name == "posix"):
import vpnlin.py;
connection = "EMSERIOUSVPN";
conn.up();
else:
gui.msgbox('Your OS is not supported for the automatic VPN setup, you have to configure it manually before using this script ! If you already set a VPN tunnel, make sure it is activated.', 'ERROR : OS not supported for automatic VPN setup', image="error_button.gif");
#######################################################
####################### MAIN ##########################
#######################################################
-
if __name__ == '__main__':
# Ask user his login, password and group
msg = "Enter your login informations";
title = "Backup files to sharing server";
fieldNames = ["Group","Login","Password"];
fieldValues = []; # we start with blanks for the values
fieldValues = gui.multpasswordbox(msg, title, fieldNames);
group = fieldValues[0];
login = fieldValues[1];
passwd = fieldValues[2];
# Ask user what file to choose
folder = gui.diropenbox(msg="Please select the folder that you want to include in the backup", title="Select a folder to backup");
-
# Get current date and time (we'll use the date and time to name the zip)
currentdatetime = time.strftime('%y-%m-%d_%H-%M-%S',time.localtime());
# Zip it !
zipname = currentdatetime + r'.zip'; # The temporary zip will be placed in the same folder as the script
makeArchive(dirEntries(folder, True), zipname);
# Zipping done !
-
# Sending the backup
try :
# Trying to send the backup locally (if the VPN is already set and activated, it will work too)
SMBSEND('PARIS2', 'mainserver.bonyridup.com', login, passwd, group, os.path.join('Backup', login), zipname);
gui.msgbox("Backup successfully sent to the local SMB sharing server !", title="Backup done !", ok_button="OK");
os.remove(zipname); # removing the local zip backup as it is now stored on the distant server
except : # If no local connection could be made
try :
# Try to connect via VPN and resending the backup
VPNCONNECT();
SMBSEND('PARIS2', 'mainserver.bonyridup.com', login, passwd, group, os.path.join('Backup', login), zipname);
gui.msgbox("Backup successfully sent to the distant SMB sharing server via VPN!", title="Backup done !", ok_button="OK");
os.remove(zipname);
except :
# If nothing worked, we leave the backup on the client in the same folder as the script, and we notify the user
gui.msgbox("ERROR : Backup could NOT be sent, the backup is saved locally, in the same folder as this script. Please keep it in a safe place.", title="ERROR : Backup not sent !", ok_button="OK", image="error_button.gif");