Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make tar backup using python

I have directory /home/user1 , user2 . I want to loop through all usernames home dir and then make the tar.gz file and then store it in /backups directory.

I am new to python so confused how to start

like image 498
Mahakaal Avatar asked Dec 22 '22 14:12

Mahakaal


1 Answers

This should work:

import os
import tarfile

home = '/home/'
backup_dir = '/backup/'

home_dirs = [ name for name in os.listdir(home) if os.path.isdir(os.path.join(home, name)) ]

for directory in home_dirs:
    full_dir = os.path.join(home, directory)
    tar = tarfile.open(os.path.join(backup_dir, directory+'.tar.gz'), 'w:gz')
    tar.add(full_dir)
    tar.close()
like image 112
amillerrhodes Avatar answered Jan 05 '23 00:01

amillerrhodes