Making backups (with rsync)

This is the most important work system administrators have to do. In this section, we will learn about making backups using rsync. The rsync command is used for copying files and directories locally, as well as remotely, and performing data backups using rsync. For that, we are going write a script called take_backup.py and write the following code in it:

import os
import shutil
import time
from sh import rsync
def check_dir(os_dir):
if not os.path.exists(os_dir):
print (os_dir, "does not exist.")
exit(1)
def ask_for_confirm():
ans = input("Do you want to Continue? yes/no ")
global con_exit
if ans == 'yes':
con_exit = 0
return con_exit
elif ans == "no":
con_exit = 1
return con_exit
else:1
print ("Answer with yes or no.")
ask_for_confirm()
def delete_files(ending):
for r, d, f in os.walk(backup_dir):
for files in f:
if files.endswith("." + ending):
os.remove(os.path.join(r, files))

backup_dir = input("Enter directory to backup ") # Enter directory name
check_dir(backup_dir)
print (backup_dir, "saved.")
time.sleep(3)
backup_to_dir= input("Where to backup? ")
check_dir(backup_to_dir)
print ("Doing the backup now!")
ask_for_confirm()
if con_exit == 1:
print ("Aborting the backup process!")
exit(1)
rsync("-auhv", "--delete", "--exclude=lost+found", "--exclude=/sys", "--exclude=/tmp", "--exclude=/proc",
"--exclude=/mnt", "--exclude=/dev", "--exclude=/backup", backup_dir, backup_to_dir)

Run the script as follows:

student@ubuntu:~/work$ python3 take_backup.py

Output :
Enter directory to backup
/home/student/work
/home/student/work saved.
Where to backup?
/home/student/Desktop
Doing the backup now!
Do you want to Continue? yes/no
yes

Now, check Desktop/directory and you will see your work folder in that directory. There are a few options used with the rsync command, namely the following:

  • -a: Archive
  • -u: Update
  • -h: Human-readable format
  • -v: Verbose
  • --delete: Deletes extraneous files from the receiving side
  • --exclude: Exclude rule
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset