#!/usr/bin/perl ###################################################################### # codetest.pl - (C) 2015 James Nonnemaker - james (AT) nonnemaker.us # # This program is merely to demonstrate my perl 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.20.30.40"; $remote_login = "backupuser"; $remote_pass = "h@ckm3"; $remote_dir = "/home/backups"; my (undef,undef,undef,$mday,$mon,$year) = localtime; $year = $year+1900; $mon++; if (length($mon) == 1) {$mon = "0$mon";} if (length($mday) == 1) {$mday = "0$mday";} $fileend = "$mon$mday$year"; use Net::FTP; $dir = "/var/cpanel/users"; opendir DIR,$dir; my @dir = readdir(DIR); close DIR; foreach (@dir) { if (($_ ne '.') and ($_ ne '..')) { $thisun = $_; print "Working with $thisun...\n"; open(DATA, "$dir/$thisun") or die("Could not open file."); foreach $line () { chomp($line); @linesplit = split(/=/, $line); if ($linesplit[0] eq 'PLAN') { $plan = $linesplit[1]; } if ($linesplit[0] eq 'USER') { $user = $linesplit[1]; } if ($linesplit[0] eq 'CONTACTEMAIL') { $email = $linesplit[1]; } if ($linesplit[0] eq 'DNS') { $dns = $linesplit[1]; } } if ($plan eq 'no_backup') { print "Plan forbids backup.\n"; } if ($plan ne 'no_backup') { print "Starting backup\n"; $filerand = time(); $tar_output = `tar -zcvf /tmp/backup/$user-$fileend-$filerand.tgz /home/$user/www/* 2>&1`; $ftp_err = ""; $ftp = Net::FTP->new($remote_server) or $ftp_err = $@; $ftp->login($remote_login, $remote_pass) or $ftp_err = $ftp->message; $ftp->cwd($remote_dir) or $ftp_err = $ftp->message; $ftp->binary; $ftp->put("/tmp/backup/$user-$fileend-$filerand.tgz") or $ftp_err = $ftp->message; $ftp->quit; if (!$ftp_err) { print "Backup successful.\n"; } else { print "Backup failed! $ftp_err\n"; } unlink("/tmp/backup/$user-$fileend-$filerand.tgz"); $email_text = "Your website, $dns, was backed up. "; if (!$ftp_err) { $email_text .= " The backup was successful.\n\n"; } if ($ftp_err) { $email_text .= " *** The backup was NOT successful. ***\n\n"; } $email_text .= "The following files were backed up:\n $tar_output"; if ($email) { open(MAIL, "|/usr/sbin/sendmail -t"); print MAIL "To: $email\n"; print MAIL "From: root\n"; print MAIL "Subject: Backup for: $dns\n\n"; print MAIL $email_text; close(MAIL); } } print "Done...\n"; close(INFO); } }