[BASH] Skripta koja radi backup

C, C++, Java, PHP, Ruby...

Moderator/ica: Moderatori/ce

Pravila foruma
U naslovu teme unutar uglatih zagrada navesti o kojem jeziku je riječ. Primjer: [Java]
tbagaric
Postovi: 18
Pridružen/a: 09 lip 2009, 19:38
Spol: M
Lokacija: Zagreb

[BASH] Skripta koja radi backup

Post Postao/la tbagaric »

Pozz,

molim HITNO da mi se javi netko tko zna pisati posnovne skripte u Bashu. Treba mi skripta koja ce raditi backup jedan dan u tjednu u određeno vrijeme... Radi brzeg kontakta molim da mi se javite na mail ludi.anonimac@hotmail.com

HVALA!!!
Avatar
4ndY
Moderator
Postovi: 4060
Pridružen/a: 15 svi 2008, 18:05
Spol: M
OS: Fedora/KDE
Lokacija: Hamburg, DE
Kontakt:

Re: [BASH] Skripta koja radi backup

Post Postao/la 4ndY »

Nisi ništa specificirao: što trebaš backupirati, na koje odredište i u kojem formatu.

Evo ultra jednostavne skripte (odnosno rsynca) s kojom ja radim backup home direktorija:

Kod: Označi sve

#!/bin/bash

user=`/usr/bin/whoami`
backup_location=/media/Backup
ignore_items=backup-skip.txt
log=backup-log.txt

echo "Backup home directory $user" >> $log
echo `date` >> $log

# rsync options: 
# --ignore-existing
# --delete-after

rsync -qhbaz -P --progress --delete-after --exclude-from=$ignore_items /home/$user $backup_location --log-file=$log
gdje se u "backup-skip.txt" nalazi sve što treba preskočiti, npr.

Kod: Označi sve

                                                                                                                                                      
Downloads
.wine
.wine64
.thumbnails
*cache*
*Cache*  
I to se stavi kao cron job da bi dobio automatsko pokretanje...
A neutron walks into a bar; he asks the bartender, 'How much for a beer?' The bartender looks at him, and says 'For you, no charge.'
tbagaric
Postovi: 18
Pridružen/a: 09 lip 2009, 19:38
Spol: M
Lokacija: Zagreb

Re: [BASH] Skripta koja radi backup

Post Postao/la tbagaric »

Majstore ako mi mozes pomoci, javi se na ludi.anonimac@hotmail.com pa cu ti reci sve sto treba...
hvala na odgovoru!
Avatar
4ndY
Moderator
Postovi: 4060
Pridružen/a: 15 svi 2008, 18:05
Spol: M
OS: Fedora/KDE
Lokacija: Hamburg, DE
Kontakt:

Re: [BASH] Skripta koja radi backup

Post Postao/la 4ndY »

tbagaric je napisao/la:Majstore ako mi mozes pomoci, javi se na ludi.anonimac@hotmail.com pa cu ti reci sve sto treba...
hvala na odgovoru!
:zvizdi

"...ako mi možeš pomoći" implicira na to da ja znam o čem se radi, a ne znam jer nisi rekao. Osim toga, sredstvo je komunikacije ovaj forum jer nemam interesa volontirati za specifične slučajeve privatnim kanalima bez da šira zajednica od toga ima koristi. Uostalom, kako svi imaju uvid u problem na forumu, možda se javi netko s boljim rješenjem (u što ne sumnjam jer ima ljudi ovdje koji puno više koriste ovakve skripte i imaju više iskustva nego ja).

Lijep pozdrav. ;)
A neutron walks into a bar; he asks the bartender, 'How much for a beer?' The bartender looks at him, and says 'For you, no charge.'
tbagaric
Postovi: 18
Pridružen/a: 09 lip 2009, 19:38
Spol: M
Lokacija: Zagreb

Re: [BASH] Skripta koja radi backup

Post Postao/la tbagaric »

OK, treba mi za fax. Cekam da dobijem tocan zadatak i tad cu saznati tocne detalje sto se trazi... Hoces biti tu oko 14.30?
csx

Re: [BASH] Skripta koja radi backup

Post Postao/la csx »

to je pravi student ruga_se
Lutherus

Re: [BASH] Skripta koja radi backup

Post Postao/la Lutherus »

nije elegantna kao od 4Andya ali radi svoj posao

Kod: Označi sve

#!/usr/bin/bash
#
# Description: A simple backup script. Archive a directory, 
#              hang on to a finite number of archives.
#
# Author: Lutherus
# 
# License: GPL
#
# Installation: If you want this to run as a cron job, put
#               it somewhere like '/etc/cron.daily' or
#               '/etc/cron.weekly'. Mileage may vary.
#
#               If you just want to run it manual, execute
#               the script with something like 'sh /path/to/script.sh'.
#
#               Don't forget to customize in the configuration section 
#               below before you run it. :)
##

########################################################
# Configuration                                        #
#                                                      #
# This section consists of variable definitions.       #
# When you define a variable in BASH, you don't use    #
# the '$' sign in front of it. If you reference it     #
# later though, you'll need it (for example, comparing #
# two variables in an if-statement.                    #
########################################################

# The directory in which backups are to be archived.
# Ex. '~/backups' 
DEST='dest'

# The directory to backup.
# Ex. '~/stuff'
SRC='src'

# Set the archive compression.
# Choices are 'gzip', and 'bzip2'.
#
# 'gzip' is faster, 'bzip2' has better compression.
CMPRS='gzip'

# A prefix to use for the archive files.
NAME='test'

# Number of backups to keep.
NUM='5'

######################################################
# Making the backup.                                 #
#                                                    #
# In this section we will build up a command to run. #
# By the end of this section, the variable $CMD      #
# should be equal to something like                  #
# 'tar cjf test-date.tar.bz2'.                   #
######################################################

# Run the UNIX date program, and create a new variable
# named 'DATE' with a value equal to whatever UNIX date
# returned (something like '10/12/07').
DATE=$(date +%x)

# Slashes aren't going to look very nice in our filename,
# use a "regular expression" (aka regex) to replace them
# with dashes.
#
# Don't worry about this part too much, regex's are certainly
# useful, but not required for BASH programming.
DATE=${DATE//\//\-}

# Append the date we just got onto the 'NAME' variable.
NAME+=-$DATE

# This variable is where we're going to build our command.
CMD='tar c'

# If compression is set to "gzip", use the 'z' option.
# Otherwise use the 'j' option ("bzip2").
#
# Also, append the rest of the stuff to our command.
if [ $CMPRS == 'gzip' ];
then
    CMD+='zf '"$DEST"/"$NAME"'.tar.gz '"$SRC"
else
    CMD+='jf '"$DEST"/"$NAME"'.tar.bz2 '"$SRC"
fi

# Run the command (make the backup).
$CMD

#####################################################
# Cleanup.                                          #
#                                                   #
# The point of this script is to automate things.   #
# If we keep creating new archives, we're going to  #
# run out of hard disk space eventually. Therefore, #
# we need to do some garbage collection. :)         #
#####################################################

# Iterate through our archive directory.
# Count up how many files we have, and
# collect names and dates.
#
# Note: This part uses arrays. If you have no prior
#       programming experience, these may trip you
#       up. I suggest googling a tutorial on them
#       (C, C++, Java, they're all pretty similar).
N=0

for FILE2 in $DEST/*
do
  FNAMES[$N]=$FILE2
  
  # This uses the UNIX stat program.
  # Again, you don't really need to know about this.
  DATES[$N]=$(stat -c %Y "$FILE2")

  # Increase our file counter by one.
  let N+=1
done

# If we're not over our backup limit, just call it quits.
# Otherwise sort our filenames by date, and delete the oldest
# until we're under our limit again.
K=0
if [ $N -le $NUM ];
then
    #echo "Under the limit, not deleting anything."
    exit
else
    # Sorting time!
    let K=0 # An index variable.

    # While the index ('K') is less than the number of filenames
    # we collected, do this loop.
    while [ $K -lt $N ];
    do
      # Index and value of the maximum.
      let MI=0
      let MAX=0

      # Another index.
      let l=0

      # Iterate through our files and find the oldest.
      while [ $l -lt $N ];
      do
	if [ ${DATES[$l]} -gt $MAX ];
	then
	    let MAX=${DATES[$l]}
	    let MI=$l
	fi

	# Increment 'l'
	let l+=1
      done

      # Add the max from that time arround to a new
      # array. Set the old value to something silly.
      FNAMES2[$K]=${FNAMES[$MI]}
      DATES2[$K]=${DATES[$MI]}
      DATES[$MI]=-10
    
      # Increment 'K'.
      let K+=1
    done
fi

# Count up to the number of backups we want to keep,
# then start deleting.
W=0
while [ $W -lt $N ];
do
    if [ $W -ge $NUM ];
    then
	#echo "Deleting "${FNAMES2[$W]}"
	rm "${FNAMES2[$W]}"
    fi
    
    let W+=1
done  
A jel baš mora biti BASH?Ili može bitit i python?

Kod: Označi sve

#!/usr/bin/env python

# Backup files - As published in Python Cookbook
# by O'Reilly with some bug-fixes.

# Credit: Python Cookbook
import sys,os, shutil, filecmp

MAXVERSIONS=100
BAKFOLDER = '.bak'

def backup_files(tree_top, bakdir_name=BAKFOLDER):
    """ Directory back up function. Takes the top-level
    directory and an optional backup folder name as arguments.
    By default the backup folder is a folder named '.bak' created
    inside the folder which is backed up. If another directory
    path is passed as value of this argument, the backup versions
    are created inside that directory instead. Maximum of
    'MAXVERSIONS' simultaneous versions can be maintained

    Example usage
    -------------
    
    The command
    $ python backup.py ~/programs
    
    will create backups of every file inside ~/programs
    inside sub-directories named '.bak' inside each folder.
    For example, the backups of files inside ~/programs will
    be found in ~/programs/.bak, the backup of files inside
    ~/programs/python in ~/programs/python/.bak etc.

    The command
    $ python backup.py ~/programs ~/backups

    will create backups of every file inside ~/backups/programs
    folder. No .bak folder is created. Instead backups of
    files in ~/programs will be inside ~/backups/programs,
    backups of files in ~/programs/python will be inside
    ~/backups/programs/python etc.
    
    """
    
    top_dir = os.path.basename(tree_top)
    tree_top += os.sep
    
    for dir, subdirs, files in os.walk(tree_top):

        if os.path.isabs(bakdir_name):
            relpath = dir.replace(tree_top,'')
            backup_dir = os.path.join(bakdir_name, top_dir, relpath)
        else:
            backup_dir = os.path.join(dir, bakdir_name)

        if not os.path.exists(backup_dir):
            os.makedirs(backup_dir)

        # To avoid recursing into sub-directories
        subdirs[:] = [d for d in subdirs if d != bakdir_name]
        for f in files:
            filepath = os.path.join(dir, f)
            destpath = os.path.join(backup_dir, f)
            # Check existence of previous versions
            for index in xrange(MAXVERSIONS):
                backup = '%s.%2.2d' % (destpath, index)
                abspath = os.path.abspath(filepath)
                
                if index > 0:
                    # No need to backup if file and last version
                    # are identical
                    old_backup = '%s.%2.2d' % (destpath, index-1)
                    if not os.path.exists(old_backup): break
                    abspath = os.path.abspath(old_backup)
                    
                    try:
                        if os.path.isfile(abspath) and filecmp.cmp(abspath, filepath, shallow=False):
                            continue
                    except OSError:
                        pass
                
                try:
                    if not os.path.exists(backup):
                        print 'Copying %s to %s...' % (filepath, backup)
                        shutil.copy(filepath, backup)
                except (OSError, IOError), e:
                    pass

if __name__=="__main__":
    if len(sys.argv)<2:
        sys.exit("Usage: %s [directory] [backup directory]" % sys.argv[0])
        
    tree_top = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[1])))
    
    if len(sys.argv)>=3:
        bakfolder = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[2])))
    else:
        bakfolder = BAKFOLDER
        
    if os.path.isdir(tree_top):
        backup_files(tree_top, bakfolder)  
csx je napisao/la:to je pravi student ruga_se
još da čovjek sa foia pa još k tome student tkisasona pa da toni navrati pogledati malo na forum......
tbagaric
Postovi: 18
Pridružen/a: 09 lip 2009, 19:38
Spol: M
Lokacija: Zagreb

Re: [BASH] Skripta koja radi backup

Post Postao/la tbagaric »

ma trebam pomoć, znam osnove, ali muci me to sto traziti neke naprednije stvrei o kojima nemam blage veze.... hval svim dobrovoljcima. mogli bi se dogovoriti za neku pivcinu poslije ... :D
Avatar
4ndY
Moderator
Postovi: 4060
Pridružen/a: 15 svi 2008, 18:05
Spol: M
OS: Fedora/KDE
Lokacija: Hamburg, DE
Kontakt:

Re: [BASH] Skripta koja radi backup

Post Postao/la 4ndY »

csx je napisao/la:to je pravi student ruga_se
To zbilja nema smisla... :roll:
Jedini je slučaj, kad bi imalo smisla nekom "pomoći" (čitaj: napraviti umjesto njega) da izvrši neku faklutetsku/školsku obavezu, postojanje nekog opravdnog razloga (makar mi malo njih pada na pamet).

Druga je stvar nekog savjetovati i uputiti, ali je ključno da i taj ima interesa za svoj problem, a ne da se registrira na forum i direktno pita: hoće li netko to učiniti umjesto mene, ja sam lijen to i pogledati, a kamo li probati sam riješiti. :roll: Takav nikad neće proširiti dalje znanje jer ga nije ni usvojio.

Postoji još jedna ok solucija: da osobu to uistinu ne zanima (nije područje interesa), ali ima moralno pravo tražiti takvo što jer je aktivni doprinositelj zajednici u drugim područjima i segemntima (može li se to reći za 4 posta?)
A neutron walks into a bar; he asks the bartender, 'How much for a beer?' The bartender looks at him, and says 'For you, no charge.'
tbagaric
Postovi: 18
Pridružen/a: 09 lip 2009, 19:38
Spol: M
Lokacija: Zagreb

Re: [BASH] Skripta koja radi backup

Post Postao/la tbagaric »

gle, ne zanimaju me skripte i ne zanima me centos kao distribucija.... koristim linux u neke druge svrhe, ne koristim skripte, ali to je predamnom i moram rijesiti zadatak. NE DA MI SE ČITATI MAN-OVE i GOOGLATI, JER RADIM 10H NA DAN DA BI SI PLATIO ŠKOLARINU, ZATO MOLIM NEKOGA DA MI POMOGNE, AKO TI SE NE DA ONDA OTIĐI ODAVDE I NEMOJ ME PLJUVATI PO FORUMU... AKO HOCES PPOMOCI, ONDA POMOZI.
Odgovori