#!/usr/bin/python ''' ************************************************************************ * codetest.py - (C) 2015 James Nonnemaker - james (AT) nonnemaker.us * * This program is merely to demonstrate my python coding skills/style * It actually does function, it is designed to run on cPanel/WHM web * servers. It will get a list of all the users on the system and * as long as their plan is not "no_backup" it will create a back up * of their www directory (only) to a temporary location and ftp it to * a remote server. It will then e-mail the user. * * I am aware a much better version of this feature is built into cPanel * this is merely a sample program. ************************************************************************ ''' remote_server = "10.3.4.5" remote_login = "backup" remote_pass = "$3cret" remote_dir = "/home/backups" import time import os, sys import tarfile import random import ftplib from ftplib import FTP import smtplib import socket fileend = time.strftime("%m%d%Y") dirs = os.listdir("/var/cpanel/users/") for file in dirs: print "Working with " + file + "..." f = open(path + file) for line in iter(f): line = line.rstrip() data = line.split("=") if data[0] == "PLAN": plan = data[1] if data[0] == "USER": user = data[1] if data[0] == "CONTACTEMAIL": email = data[1] if data[0] == "DNS": dns = data[1] f.close() if plan == "no_backup": print "Backup prohibited by plan type" else: print "Starting backup...." ftperror = "" filerand = str(random.randrange(100, 999, 2)) backupfname = user + "-" + fileend + "-" + filerand + ".tgz" backupfile = "/tmp/backup/" + backupfname backupdir = "/home/" + user + "/www/" tar = tarfile.open(backupfile, "w:gz") tar.add(backupdir, arcname=backupfile) tar_output = tar.getnames() tar.close() try: ftp = FTP(remote_server) ftp.login(user=remote_login, passwd=remote_pass) ftp.cwd(remote_dir) ftp.storbinary('STOR '+backupfname, open(backupfile, 'rb')) ftp.quit() except ftplib.all_errors: ftperror = "1" os.unlink(backupfile) email_text = "Your website, " + dns + ", was backed up. "; if not ftperror: email_text = email_text + " The backup was successful.\n\n" if ftperror: email_text = email_text + " *** The backup was NOT successful. ***\n\n" email_text = email_text + "The following files were backed up:\n " + str(tar_output) if email: mail_from = "root@" + socket.gethostname() mail_to = [email] mail_subject = "Backup for: " + dns email_message = """\ From: %s To: %s Subject: %s %s """ % (mail_from, ", ".join(mail_to), mail_subject, email_text) server = smtplib.SMTP("127.0.0.1") server.sendmail(mail_from, mail_to, email_message) server.quit() os.remove(backupfile) print "Done..." #if no_backup #for file