본문 바로가기
자격증

[리눅스마스터 1급] 9. 시스템 백업

by LimSeongHyeon 2025. 4. 19.


개요

백업하는 대상에 따라 명령어가 제법 분리되어 있어 헷갈릴 수 있다. 때문에 시스템 백업에서 해당 명령어가 input을 어떤 것을 가지는지, input에 대한 옵션과 output에 대한 옵션은 어떻게 지정하는지에 집중해서 확인하고 그 이외의 옵션에 대해서는 man, help를 통해 찾아가면서 사용하면 될 것 같다.

tar (Tape Archiver)

tar는 백업이 주 목적이 아닌, 파일 ↔ 아카이브를 상호 변환 하기 위해 존재하는 명령어 이고 활용성이 점점 넓어져 압축이나 백업에 유용한 추가 옵션들이 부가적으로 생겨났다. tar는 man은 없고 help만 있기에 참고하도록 하자.
옵션 압축방식
-z gzip
-j bzip2
-J xz
특정 압축 방식으로 백업 혹은 복구를 원하는 경우 옵션 맨 앞에 압축방식을 지정하는 옵션을 추가해주면 된다.
ex) tar -jcvf backup.tar /source_dir

 

 

 

Full Backup (전체 백업)

 

Backup (create)

$ tar -cvf backup.tar /source_dir

 

 

Restore (extract)

$ tar -xvf backup.tar

 

 

 

 

Incremental Backup (증분 백업)

 

Backup (create)

$ tar -g snapshot.file -cvf backup-level0.tar /source_dir
$ tar --listed-incremental=snapshot.file -cvf backup-level0.tar /source_dir

 

 

 

Restore (extract)

$ tar -xvf backup-level0.tar -C
$ tar -xvf backup-level1.tar -C
$ tar -xvf backup-level2.tar -C

cpio (Copy In/Out)

tar와 cpio는 매우 유사하지만, cpio는 이름에 in-out이 존재하듯 (표준)입출력을 기반으로 하여 작동한다. 디렉토리 단위로만 아카이브가 가능했던 tar에 비해서 파일 리스트만 잘 작성하면 되기에 커스텀 자유도가 올라간 셈이다. 대신 사용 난이도가 올라간다. man에 example을 살펴보자.
더보기
EXAMPLES
       When  creating  an  archive, cpio takes the list of files to be processed from the standard input, and then sends the archive to the standard output, or to the device defined by
       the `-F' option.  Usually find or ls is used to provide this list to the standard input.  In the following example you can see the possibilities for archiving the contents of  a
       single directory.

       % ls | cpio -ov > directory.cpio

       The  `-o'  option  creates the archive, and the `-v' option prints the names of the files archived as they are added.  Notice that the options can be put together after a single
       `-' or can be placed separately on the command line.  The `>' redirects the cpio output to the file `directory.cpio'.

       If you wanted to archive an entire directory tree, the find command can provide the file list to cpio:

       % find . -print -depth | cpio -ov > tree.cpio

       This will take all the files in the current directory, the directories below and place them in the archive tree.cpio.  Again the `-o' creates an archive,  and  the  `-v'  option
       shows  you  the name of the files as they are archived.  see “Copy-out mode”.  Using the `.' in the find statement will give you more flexibility when doing restores, as it will
       save file names with a relative path vice a hard wired, absolute path.  The `-depth' option forces `find' to print of the entries in a directory before  printing  the  directory
       itself.  This limits the effects of restrictive directory permissions by printing the directory entries in a directory before the directory name itself.

       Extracting  an  archive  requires a bit more thought because cpio will not create directories by default.  Another characteristic, is it will not overwrite existing files unless
       you tell it to.

       % cpio -iv < directory.cpio

       This will retrieve the files archived in the file directory.cpio and place them in the present directory.  The `-i' option extracts the archive and the `-v' shows the file names
       as they are extracted.  If you are dealing with an archived directory tree, you need to use the `-d' option to create directories as necessary, something like:

       % cpio -idv < tree.cpio

       This  will  take  the  contents  of the archive tree.cpio and extract it to the current directory.  If you try to extract the files on top of files of the same name that already
       exist (and have the same or later modification time) cpio will not extract the file unless told to do so by the -u option.  see “Copy-in mode”.

       In copy-pass mode, cpio copies files from one directory tree to another, combining the copy-out and copy-in steps without actually using an archive.  It reads the list of  files
       to copy from the standard input; the directory into which it will copy them is given as a non-option argument.  see “Copy-pass mode”.

       % find . -depth -print0 | cpio --null -pvd new-dir

       The example shows copying the files of the present directory, and sub-directories to a new directory called new-dir.  Some new options are the `-print0' available with GNU find,
       combined with the `--null' option of cpio.  These two options act together to send file names between find and cpio, even if special characters are embedded in the  file  names.
       Another is `-p', which tells cpio to pass the files it finds to the directory `new-dir'.

 

Backup (copy-out)

 

단일 디렉터리를 아카이브

$ ls | cpio -ov > directory.cpio

 

 

하위 디렉터리 포함 아카이브

$ find . -print -depth | cpio -ov > tree.cpio

 

 

Restore (copy-in)

 

백업 파일 복원

$ cpio -iv < backup.cpio

 

 

백업 파일 내의 파일 목록 출력

$ cpio -ivt < backup.cpio

 

 

Copy (copy-pass)

 

아카이브 하지 않고 그대로 복사

$ find . -depth -print0 | cpio --null -pvd new-dir

 


dump / restore

dump는 파일 시스템(특히 파티션) 단위로 백업할 때 사용한다. 때문에 보통 내보낼 백업 파일 이름과 파일시스템을 옵션으로 사용한다. 또한 restore는 dump로 백업된 파일을 복구하는데 사용된다. man에 example이 없으므로 옵션 조합을 익숙하게 만들자.
더보기
File System Check

아래 3가지 방법 중 하나를 선택해서 사용하면 된다. 개인적으로 df -T가 가장 보기 편하게 나온다고 생각한다.

$ lsblk -f
NAME   FSTYPE LABEL UUID MOUNTPOINT
vda                      
└─vda1                   /etc/hosts
vdb
$ df -T
Filesystem     Type    1K-blocks     Used Available Use% Mounted on
overlay        overlay 535578480 46225420 462073752  10% /
tmpfs          tmpfs       65536        0     65536   0% /dev
shm            tmpfs       65536        0     65536   0% /dev/shm
/dev/vda1      ext4    535578480 46225420 462073752  10% /etc/hosts
$ blkid
/dev/vda1: UUID="c586475a-8228-44c9-944e-c1d7f9d8fa45" BLOCK_SIZE="4096" TYPE="ext4" PARTUUID="dd644516-01"

 

Backup (dump)
$ dump -0uf fullbackup.dump /dev/sda1
옵션 설명
-0 ~ -9 백업 레벨 지정 (-0: Full Backup, -1 이상: Incremental Backup)
-f [파일명] 백업 파일을 저장할 파일명 또는 디바이스 지정
-u 백업 후 /etc/dumpdates 파일 업데이트 (다음 증분 백업용 기록)
-h 하드링크 처리 방식 지정
-b 블록 크기 지정

 

 

Restore (restore)
$ restore -rf fullbackup.dump
$ restore -if fullbackup.dump # 대화모드 복원
옵션 설명
-r 전체 복구 (Restore entire dump)
-i 대화식 복구 (Interactive: 파일을 선택적으로 복구)
-t 아카이브 목록 보기 (test, no extract)
-x 지정한 파일만 복구 (extract specific files)
-f [파일명] 복구할 dump 파일 지정

 


dd (Dataset Definition)

땅볼슛 dd는 블록 단위로 데이터를 복사하거나 변환한다. 사용 대상에는 파일, 디스크, 파티션, 장치 등이 있다.
블록 단위로 데이터를 복사한다는 말은 블록 단위, 블록 개수 등을 지정할 수 있음을 의미한다. 주로 디스크 복제, 부트로더 설치에 사용된다.
더보기
EXAMPLES
       The following command:

           dd if=/dev/rmt0h  of=/dev/rmt1h

       copies from tape drive 0 to tape drive 1, using a common historical device naming convention.

       The following command:

           dd ibs=10  skip=1

       strips the first 10 bytes from standard input.

       This example reads an EBCDIC tape blocked ten 80-byte EBCDIC card images per block into the ASCII file x:

           dd if=/dev/tape of=x ibs=800 cbs=80 conv=ascii,lcase
파라미터 의미
if input file
of output file
bs block size (한 번에 읽고 쓰는 크기)
count 몇 블록을 처리할지 지정
skip 입력 파일에서 처음 몇 블록을 건너뛸지
seek 출력 파일에서 처음 몇 블록을 건너뛸지
더보기
dd에서의 단위표

 

단위 의미 크기(Byte 기준)
b block 512 bytes
c character 1 byte
w word 2 bytes
kB kilobyte (SI) 1000 bytes
K 또는 k kibibyte (binary) 1024 bytes
MB megabyte (SI) 1,000,000 bytes
M mebibyte (binary) 1,048,576 bytes
GB gigabyte (SI) 1,000,000,000 bytes
G gibibyte (binary) 1,073,741,824 bytes
TB terabyte (SI) 1,000,000,000,000 bytes
T tebibyte (binary) 1,099,511,627,776 bytes

 

디스크 전체 백업
$ dd if=/dev/sda of=/backup/sda_backup.img bs=1M count=1K

 

빈 파일 생성
$ dd if=/dev/zero of=emptyfile.img bs=1M count=1K
/dev/zero는 실제 파일이 아닌 요청한 만큼 0으로 채워진 파일을 반환해주는 특수 장치이다.

 

요약
사용은 대부분 비슷하게 if - of - bs - count로 구성되며. 백업되는 총 사이즈는 bs * count 이다.

 


rsync (Remote Synchronization)

rsync의 주요 기능은 로컬 ↔ 로컬 혹은 로컬 ↔ 원격에서 변경된 파일만 백업하는 기능이다. 네트워크 전송에 최적화 되어 원격으로 백업이 가능하다는 점이 다른 명령어와 차별되는 점이다.
더보기
USAGE
       You use rsync in the same way you use rcp. You must specify a source and a destination, one of which may be remote.

       Perhaps the best way to explain the syntax is with some examples:

              rsync -t *.c foo:src/

       This would transfer all files matching the pattern *.c from the current directory to the directory src on the machine foo. If any of the files already exist on the remote system
       then the rsync remote-update protocol is used to update the file by sending only the differences in the data.  Note that the expansion of wildcards on the commandline (*.c) into
       a list of files is handled by the shell before it runs rsync and not by rsync itself (exactly the same as all other posix-style programs).

              rsync -avz foo:src/bar /data/tmp

       This  would recursively transfer all files from the directory src/bar on the machine foo into the /data/tmp/bar directory on the local machine. The files are transferred in "ar‐
       chive" mode, which ensures that symbolic links, devices, attributes, permissions, ownerships, etc. are preserved in the transfer.  Additionally,  compression  will  be  used  to
       reduce the size of data portions of the transfer.

              rsync -avz foo:src/bar/ /data/tmp

       A  trailing  slash  on the source changes this behavior to avoid creating an additional directory level at the destination.  You can think of a trailing / on a source as meaning
       "copy the contents of this directory" as opposed to "copy the directory by name", but in both cases the attributes of the containing directory are transferred to the  containing
       directory on the destination.  In other words, each of the following commands copies the files in the same way, including their setting of the attributes of /dest/foo:

              rsync -av /src/foo /dest
              rsync -av /src/foo/ /dest/foo

       Note  also  that host and module references don’t require a trailing slash to copy the contents of the default directory.  For example, both of these copy the remote directory’s
       contents into "/dest":

              rsync -av host: /dest
              rsync -av host::module /dest

       You can also use rsync in local-only mode, where both the source and destination don’t have a ’:’ in the name. In this case it behaves like an improved copy command.

       Finally, you can list all the (listable) modules available from a particular rsync daemon by leaving off the module name:

              rsync somehost.mydomain.com::

       See the following section for more details.
옵션 설명
-a archive 모드: 퍼미션, 소유자, 심볼릭 링크까지 유지 (-rlptgoD 묶음)
-v verbose (진행 상황 출력)
-z 압축 전송 (네트워크 절약)
-P 진행 상황 표시 + 부분 전송 지원 (--progress --partial)
-r 디렉터리 재귀 복사 (디렉터리 하위까지)
-u 소스 파일이 더 새로울 때만 복사
--delete 소스에 없는 파일은 목적지에서도 삭제
-e ssh SSH를 통해 복사 (보안 전송)

 

로컬 → 로컬
$ rsync -av /home/user/ /backup/user/

 

로컬 원격(SSH)
$ rsync -avz /home/user/ username@remote:/backup/user/

 

원격(SSH)  → 로컬
$ rsync -avz username@remote:/backup/user/ /home/user/

 

삭제 동기화
$ rsync -av --delete /home/user/ /backup/user/

정리

명령어 주요 기능 설명 요약
tar
(Tape Archiver)
여러 파일을 하나의 아카이브 파일로 묶거나 풀어줌 (압축은 옵션) 파일/디렉터리 전체를 트리 구조로 쉽게 백업
- $ tar -cvf backup.tar /source_dir
- $ tar -g snapshot -cvf backup0.tar /source_dir
- $ tar -xvf backup.tar
cpio
(Copy In/Out)
파일 목록을 받아 아카이브하거나, 아카이브에서 추출 파일 목록을 표준 입력/출력으로 다루는 구조
- $ ls | cpio -ov > directory.cpio
- $ find . -print -depth | cpio -ov > tree.cpio
- $ cpio -iv < backup.cpio
dump / restore 파일시스템 전체를 백업하고 복구 파일 단위가 아닌 파일시스템 단위 백업
- $ dump -0uf fullbackup.dump /dev/sda1
- $ restore -rf fullbackup.dump
- $ restore -if fullbackup.dump
dd
(Dataset Definition)
디바이스나 파일을 블록 단위로 복사 파일/디스크/파티션 등을 로우 데이터 그대로 복제
- $ dd if=? of=? bs=? count=?
- $ dd if=/dev/zero of= bs=? count=?
rsync
(Remote Synchronization)
로컬/원격 시스템 간에 파일 및 디렉토리 동기화 네트워크 전송에 최적화
- $ rsync -av /source /destination
- $ rsync -avz /source user@remote:/destination
- $ rsync -avz user@remote:/source /destination

문제

cpio

 

기본 케이스

1) cpio를 이용하여 /home 디렉터리에 있는 파일을 home.cpio로 백업하는 명령어를 작성하세요.
2) cpio를 이용하여 백업된 home.cpio를 복원하는 명령어를 작성하세요.

[조건] 백업, 복원 모두 표준 입출력을 사용하여 작성한다.
더보기

1) $ find /home | cpio -o > home.cpio

2) $ cpio -i < home.cpio

 

파일명 지정

1) /home 디렉터리를 home.cpio 파일로 백업하며 진행 과정을 상세히 출력한다.
2) 백업된 home.cpio를 확인한다.
3) home.cpio를 복원하며 진행 과정을 상세히 출력한다.

[조건] 백업, 복원 모두 표준 입출력을 사용하지 않고 파일을 지정하여 작성한다.
더보기

1) $ find /home | cpio -ovF home.cpio

2) $ cpio -tF home.cpio

3) $ cpio -ivF home.cpio

 

데이터 형식 지정

1) cpio를 이용하여 /home 디렉터리에 있는 파일을 SVR4 portable format with no CRC 데이터 형식으로 지정하고, home.cpio로 백업하는데, 진행 과정을 상세히 출력하는 명령어를 작성하세요.

2) cpio를 이용하여 백업된 home.cpio를 SVR4 portable format with no CRC 데이터 형식으로 지정하고, 진행 과정을 상세이 출력하여 복원하는 명령어를 작성하세요. (단, 필요한 경우 디렉터리를 생성한다.)

[조건] 백업, 복원 모두 표준 입출력을 사용하여 작성한다.
더보기

1) $ find /home | cpio -ocv > home.cpio

2) $ cpio -icdv < home.cpio

 


 

dump / restore
1) dump 명령어를 이용하여 디렉터리 /home 파일을 home.xdump 파일로 백업하는 명령어를 작성하세요.
2) restore 명령어를 이용하여 위에서 백업한 파일을 복원하는 명령어를 작성하세요. 
더보기

1) $ dump -f home.xdump /home

2) $ restore -f home.xdump /home

 


 

dd
/dev/sda1을 /dev/sdb1으로 백업하는 명령어를 작성하세요.

[조건]
1) 블록사이즈는 1MB 단위로 진행한다.
2) 총 백업사이즈는 1GB로 진행한다.
더보기

$ dd if=/dev/sda1 of=/dev/sdb1 bs=1M count=1K

 


 

rsync
원격지(192.168.12.5)의 디렉터리(/home)를 로컬의 /backup 디렉터리에 백업하는 명령어를 작성하세요.

[조건]
1) 백업 진행 상황을 확인할 수 있어야 한다.
2) 접속은 root 권한으로 접속하며 허가권 및 타임스탬프 등 정보는 그대로 유지한다.
3) /backup 디렉터리 이하에 바로 /home 내부 파일들이 존재하여야 한다.
더보기

$ rsync -avz root@192.168.12.5:/home/ /backup