[问题解决型]Linux利用tar备份系统

简介:

由于装openstack,很多依赖的东西,而设计环境变量等,一旦搞错,重装系统,搞得很麻烦,想办法备份一下系统。进行还原。方法如下:

tar -zcvpf /home/full-backup.tar.gz / --exclude=/mnt/ --exclude=/proc/ --exclude=/sys/ 这个命令是把根目录下的所有内容备

tar -zcvpf /home/full-backup.tar.gz / --exclude=/mnt/ --exclude=/proc/ --exclude=/sys/

这个命令是把根目录下的所有内容备份到full-bakup.tar.gz的备份文档中
-z表示进行压缩gzip格式

-c(建立一个备份文档

-v显示压缩过程

-p保留文件的权限

--directory‘指定不备份的文件夹
增量备份

1.首先创建完全备份:tar -czvf -g zeng aa.tar.gz /var

待/var中的数据变化后

2.再做增量备份 : tar -czvf -g zeng aa.tar.gz.1 /var
差异备份

1. find /var -mtime -1 -print filelist

产生要备份的档案的列表 -1表示是一天的时间

2.tar -czv -T filelist -f /backup.tar.gz

依据文件列表进行备份. -T选项可以指定包含要备份的档案的列表

参见:http://it.china-b.com/linux/xtgl/20090525/21931_1.html

另外参考:http://zhidao.baidu.com/question/204995317.html

1.==============================================

另外,这里有比较完整的介绍和说明:http://wiki.ubuntu.org.cn/UbuntuHelp:BackupYourSystem/TAR/zh

tar -cvzf /backup.tgz --exclude=/proc --exclude=/lost+found --exclude=/backup.tgz --exclude=/mnt --exclude=/sys /

原文如下:(仅供学习,所有权归原作者)

文章出处: 

https://help.ubuntu.com/community/BackupYourSystem/TAR

  1. title

译注:文章已经经过改动。

目录

[隐藏]

[编辑] 用TAR来备份系统

IconsPage?action=AttachFile&do=get&target=note.png 这篇文章已经被改动过了,以便更好地刊登到wiki上。完整的版本可以看这里the original forum post.
IconsPage?action=AttachFile&do=get&target=stop.png 如果你没有正确使用程序来备份,那你的资料可能就会被你抹去了。所以请在读完后再动手

[编辑] 介绍

这篇文章是HOWTO系列中 备份系统 的一部分.

IconsPage?action=AttachFile&do=get&target=info.png This guide to backup your system using tar to create compressed archives is based upon a post from the Ubuntu Community Forums written by Heliode. See the original forum thread for discussion:http://www.ubuntuforums.org/showthread.php?t=35087 .

[编辑] 为备份系统做准备

IconsPage?action=AttachFile&do=get&target=IconHint2.png Just a quick note. You are about to back up your entire system. Don't forget to empty your Wastebasket, remove any unwanted files in your /home directory, and cleanup your desktop.
  • Depending on why you're backing up, you might want to:
  • Delete all your emails
  • Clear your browser search history
  • Wipe your saved browser personal details
IconsPage?action=AttachFile&do=get&target=IconNote.png If you are not worried about the security concerns, this step is not necessary. Many users explicitly want backups of their email and browser settings.
  • Unmount any external media devices, and remove any CDs/DVDs not needed for the backup process.
  • This will lessen the amount of exclusions you need to type later in the process.

[编辑] Backing up

IconsPage?action=AttachFile&do=get&target=terminal.png

  • Some directories require root or superuser permissions to successfully backup. Gain superuser access by opening a terminal and entering:

sudo -s -H

  • Go to the root of your file system:

cd /

IconsPage?action=AttachFile&do=get&target=IconHint2.png We use the file system root in our example, but you use any target destination you want. You can use remote or removable drives as your backup destination.
  • Create a backup of your system:

tar -cvzf /backup.tgz --exclude=/proc --exclude=/lost+found --exclude=/backup.tgz --exclude=/mnt --exclude=/sys /

  • IconsPage?action=AttachFile&do=get&target=info.png Now, lets explain this a little bit:
  • 'tar' is the program used to do a backup
  • c - create a new backup archive
  • v - verbose mode, tar will print what it's doing to the screen
  • z - compress the backup file with 'gzip' to make it smaller
  • f <filename> - specifies where to store the backup, /backup.tgz is the file used in this example
  • Now come the directories we want to exclude. We don't want to backup everything since some directories aren't very useful to include.
  • Make sure you don't include the file itself, or else you'll get weird results.
  • Don't include the /mnt folder if you have other partitions mounted there.
  • If you have Partitions in /mnt that require backup, you will need to exclude the folders you do not want backed up.<
    >
IconsPage?action=AttachFile&do=get&target=example.png --exclude=/mnt/<unwanted_partition>
  • Make sure you don't have anything mounted in /media.
  • Remove CDs/DVDs and removable media that you don't need backed up. You can selectively exclude directories in /media if you want removable devices backed up.
  • After all of the options is the directory we want to backup. Since we want to backup everything we use / for the root directory.
  • If you want to exclude all other file systems you can use the --one-file-system option in addition to or instead of --exclude.
  • With the --one-file-system option, only the "local" file system is backed up. <
    >
IconsPage?action=AttachFile&do=get&target=info.png The "local" file system is the file system you have specified, not the file systems mounted under it in the file hierarchy. Use df to see which file systems you have mounted.

IconsPage?action=AttachFile&do=get&target=example.png

tar -cvzf /backup.tgz --one-file-system --exclude=/lost+found --exclude=/backup.tgz /
  • Relax while Tar creates a backup of your system. This make take awhile depending on the amount of data that is being backed up and the speed of your processor. When the process is complete you will have a file named backup.tgz in the root directory of your file system. This file may be burned to a CD/DVD, moved to another partition/drive, or even stored on another machine.
  • IconsPage?action=AttachFile&do=get&target=stop.png Files that are bigger than 2GB are not supported by some implementations of ISO9660 and may not be restorable. So don't simply burn a DVD with a huge .iso file on it. Split it up using the command split or use a different way to get it onto the DVD. See man split for further information on split.
  • A possible workaround is the following:

sudo tar --create --bzip2 --exclude /tmp --one-file-system --sparse / | growisofs -use-the-force-luke -Z /dev/hda=/proc/self/fd/0

  • Note that this only backs up one file system. You might want to use --exclude instead of --one-file-system to filter out the stuff you don't want backed up. This assumes your DVD drive is /dev/hda. This will not create a mountable DVD. To restore it you will reference the device file:

sudo tar --extract --bzip2 --file /dev/hda

IconsPage?action=AttachFile&do=get&target=IconHint2.png At the end of the process you might get a message along the lines of 'tar: Error exit delayed from previous errors' or something, but in most cases you can just ignore that.
  • Another workaround would be to Bzip2 to compress your backup. Bzip2 provides a higher compression ratio at the expense of speed. If compression is important to you, just substitute the z in the command with j, and change the file name to backup.tar.bz2.

That would make the command look like this:

tar -cvpjf /backup.tar.bz2 --exclude=/proc --exclude=/lost+found --exclude=/backup.tar.bz2 --exclude=/mnt --exclude=/sys /

[编辑] Backup over a network

  • It is possible to use netcat to transfer the backup between computers.
  • On the receiving end you'll setup netcat to write the backup file like this:

nc -l -p 1024 > backup.tar.bz2

  • Then you pipe the tar command without the f flag through netcat on the sending end like this:

tar -cvj <all those other options> / | nc -q 0 <receiving host> 1024

  • In the above commands 1024 is just a random port number, anything from 1024 and up should work.
  • If all goes well the backup will be piped through the network without touching the file system being read.
  • You can also use SSH:

tar zcvf - /home | ssh <backuphost> "( cat > home_bkp.tar.gz )"

  • IconsPage?action=AttachFile&do=get&target=info.png In this example:
  • The directory to backup is /home
  • The backup destination is home_bkp.tar.gz on the machine called <backuphost>.
  • The hyphen before /home tells tar to send output to stdout rather than to a file.
  • Adding the 'p' option to tar would preserve file permissions.

[编辑] Restoring

IconsPage?action=AttachFile&do=get&target=warning.png Please, for goodness sake, be careful here. If you don't understand what you are doing here you might end up overwriting stuff that is important to you, so please take care!

For the purpose of this tutorial we will assume your backup file is stored in the file system root. We will also assume that you have already gained superuser access through sudo.

  • Restore your backup:

tar -xvpzf /backup.tgz -C /

  • If you used bz2:

tar -xvpjf backup.tar.bz2 -C /

  • IconsPage?action=AttachFile&do=get&target=info.png A brief explanation:
  • The x option tells tar to extract the file.
  • The -C <directory> option tells tar to change to a specific directory before extracting. " / " in this example.
  • The p option preserves all file permissions. This is default action for tar when used by the superuser.
IconsPage?action=AttachFile&do=get&target=warning.png This will overwrite every single file on your partition with the one in the archive.
  • The restoration process may take awhile, depending on the size of the archive and the speed of your computer.
  • Once the extraction is complete, re-create the directories which were excluded.

mkdir /proc /lost+found /mnt /sys

  • Reboot and everything should be restored to the state of your system when you made the backup.
IconsPage?action=AttachFile&do=get&target=IconNote.png It may not be exactly the way it was when you made the backup, because files created after the backing up won't be deleted.

[编辑] Restoring over a network

  • If you used nc to backup to another computer the commands to restore are:
  • On the receiving side:
  • Mount the disk (if you are running from a LiveCD)and type:

nc -l -p 1024 | tar -xvpjf - -C /mnt/disk

  • On the sender side, the side that has the backup file:

cat backup.tar.bz2 | nc -q 0 <receiving host> 1024

  • The - character will tell tar to accept the input from stdin, the pipe.
  • The backup file will be expanded without being saved on the disk on the receiver, like when the backup was made.
  • "-xvpjf is for a .bz2 file, change j to z if you used a tar.gz backup.

[编辑] Reformatted Partitions

  • If you had to format partitions, update the /etc/fstab and /boot/grub/menu.lst files after restoring the backup.
  1. Mount the reformatted partitions on a LiveCD.
  2. Open a terminal and type
    blkid
  3. Making note of the UUIDs, edit the /etc/fstab and /boot/grub/menu.lstfiles in the restored root partition.
    sudo nano /mnt/disk/etc/fstab
    sudo nano /mnt/disk/boot/grub/menu.lst
    Change the UUIDs to match the results of your blkid command.

[编辑] Restoring GRUB

  • In most cases restoring GRUB should not be necessary.
  • If when you boot the system you are left on a grub shell, just do this

find /boot/grub/stage1

root (hd?,?)
setup (hd?)

substitute the ? with the results of your findcommand.

press esc to restart the system.

2.==============================

参见:https://help.ubuntu.com/community/BackupYourSystem/TAR

tar -cvpzf backup.tar.gz --exclude=/backup.tar.gz --exclude=/proc --exclude=/lost+found --exclude=/sys --exclude=/mnt --exclude=/media --exclude=/dev / 

Backing Up

To get started, please open up a terminal, in Ubuntu this can be done by Applications Menu -> Accessories ->Terminal. Some directories require root or superuser permissions to read and write (needed for backup), for an explanation on why see FilePermissions. To gain temporary root permission, simply preface any command you want to issue with sudo, as explained in RootSudo.

For this example, we will change directories to root. This is where the backup will be made. This is an arbitrary decision, you should create the backup elsewhere. For instance to a mounted external hard drive, another partition or disk connected internally, even a folder in your home directory could be used. In all cases, ensure the location your saving the archive to has enough space. Simply use the cd command to navigate there.

cd / 

The following is an exemplary command of how to archive your system.

tar -cvpzf backup.tar.gz --exclude=/backup.tar.gz --exclude=/proc --exclude=/lost+found --exclude=/sys --exclude=/mnt --exclude=/media --exclude=/dev / 

To understand what is going on, we will dissect each part of the command.

  • tar - is the command that creates the archive. It is modified by each letter immediately following, each is explained bellow.

    • c - create a new backup archive.

    • v - verbose mode, tar will print what it's doing to the screen.

    • p - preserves the permissions of the files put in the archive for restoration later.

    • z - compress the backup file with 'gzip' to make it smaller.

    • f <filename> - specifies where to store the backup, backup.tar.gz is the filename used in this example. It will be stored in the current working directory, the one you set when you used the cd command.

  • --exclude=/example/path - The options following this model instruct tar what directories NOT to backup. We don't want to backup everything since some directories aren't very useful to include. The first exclusion rule directs tar not to back itself up, this is important to avoid errors during the operation. After, we proceed to exclude the /proc, /lost+found, /sys, /mnt, /media and /dev directories in root. /proc and /sys are virtual filesystems that provide windows into variables of the running kernel, so you do not want to try and backup or restore them. /dev is a tmpfs whose contents are created and deleted dynamically by udev, so you also do not want to backup or restore it.

    • It is important to note that these exclusions are recursive. This means that all folders located within the one excluded will be ignored as well. In the example, excluding the /media folder excludes all mounted drives and media there.

    • If there are certain partitions you wish to backup located in /media, simply remove the exclusion and write a new one excluding the partitions you don't want backed up stored within it. For example:

      • --exclude=/media/unwanted_partition 
  • / - After all options is the directory to backup. Since we want to backup everything on the system we use / for the root directory. Like exclusions, this recursively includes every folder below root not listed in the exclusions or other options.

See tips before operation for additional information.

Once satisfied with the command, execute it and wait until it has completed. The duration of the operation depends on the amount of files and compression choses. Once completed, check the directory you set to find the archive. In our example, backup.tar.gz would be located in the / directory once completed. This archive can then be moved to any other directory for long term storage.

Note: At the end of the process you might get a message along the lines of 'tar: Error exit delayed from previous errors' or something, but in most cases you can just ignore that.

 

Additional Tips

  • To keep good records, you should include the date and a description of backup in the filename.
  • Another option would be to use bzip2 to compress your backup instead of gzip. Bzip2 provides a higher compression ratio at the expense of speed. If compression is important to you, just substitute the z in the command with j, and change the file name to .tar.bz2. The rest of this guides examples use gzip, make the subsequent changes to the examples before using them.

  • If you want to exclude all other mounts other than the current - by this I mean partitions mounted to directories - then use the --one-file-system option appended before the exclusion rules. This has the effect of stopping tar from crossing into any other mounts in any directory including /mnt or /media. For instance, many users create a separate mount for /home to keep user folders separate from root, adding this option to our original example would exclude home's contents entirely.

 

Archive Splitting

If you want to burn the archive to discs, or transfer them to a filesystem with a limited max filesize (say FAT32 with a limit of 4GB per file) then you will have to split the file either during or after archive creation. A simple means is to use the split command. Below are examples of both scenarios. More information than conveyed here can be found in the man pages of split, use man split in a terminal to read. Ensure you keep these archives all together in a directory you label for extraction at a later date. Once the archives are split to a desirable size, they can be burned one at a time to disc.

To Split During Creation

tar -cvpz <put options here> / | split -d -b 3900m - /name/of/backup.tar.gz. 
  • The first half until the pipe (|) is identical to our earlier example, except for the omission of the f option. Without this, tar will output the archive to standard output, this is then piped to the split command.
  • -d - This option means that the archive suffix will be numerical instead of alphabetical, each split will be sequential starting with 01 and increasing with each new split file.

  • -b - This option designates the size to split at, in this example I've made it 3900mB to fit into a FAT32 partition.

  • - - The hyphen is a placeholder for the input file (normally an actual file already created) and directs split to use standard input.

  • /name/of/backup.tar.gz. Is the prefix that will be applied to all generated split files. It should direct to the folder you want the archives to end up. In our example, the first split archive will be in the directory /name/of/ and be named backup.tar.gz.01 .

To Split After Creation

split -d -b 3900m /path/to/backup.tar.gz /name/of/backup.tar.gz. 
  • Here instead of using standard input, we are simply splitting an existing file designated by /path/to/backup.tar.gz .

To Reconstitute the Archive
Reconstructing the complete archive is easy, first cd into the directory holding the split archives. Then simply use cat to write all the archives into one and send over standard output to tar to extract to the specified directory.

 

cat *tar.gz* | tar -xvpzf - -C /  
  • The use of * as a wild card before and after tar.gz tells cat to start with first matching file and add every other that matches, a process known as catenation, how the command got its name.
  • Afterwards, it simply passes all that through standard output to tar to be extracted into root in this example.
  • For a more complete explanation of restoration, see Restoring.

 

Backup Over a Network

The command tar does not include network support within itself, but when used in conjunction with other programs this can be achieved. Two common options are netcat (nc) and ssh.

 

Netcat

The command nc is designed to be a general purpose networking tool. It sets up a simple connection between two networked machines. This connection survives until the user manually disconnects it, unlike normal connections such as tcp which terminate upon completion of a file.

Receiving Computer 
On the receiving end you'll setup netcat to write the backup file as in the following example. This command will setup a machine to receive standard input from network to port 1024 then write it to the file backup.tar.gz. The choice of port is entirely up to the user, as long as it is 1024 or larger. A simple example:

nc -l 1024 > backup.tar.gz 

Sending Computer 
On the machine to be backed up, the tar command will be piped to nc which will then send the backup over the network to the port in question to be written in the file. Take note, where it says <receiving host> replace with the name of the computer on the network. The f option was omitted since we are not writing to a local file, but moving the archive through standard output. The following is an example:

tar -cvpz <all those other options like above> / | nc -q 0 <receiving host> 1024 

If all goes well the backup will be piped through the network without touching the file system being read.

 

SSH

You can also use SSH. For a complete explanation of its proper use see SSH. The command below is an example of what is possible.

tar -cvpz <all those other options like above> / | ssh <backuphost> "( cat > ssh_backup.tar.gz )"

In the example:

  • The tar half of the command is the same as above, with the omission of the f option to pipe the archive via standard output to ssh and onto the networked computer.
  • ssh_backup.tar.gz Is the name of the file that will be created on the machine indicated.

  • <backuphost> - Should be replaced with the name of the computer in question on the network.

 

Restoring

IconsPage/warning.png Be careful! If you don't understand what you are doing here you might end up overwriting stuff that is important to you. If you are restoring the root directory while booted and using root, you will encounter trouble. Operate such a restoration from a Live CD, simply mount the drive in question and correct the path as needed.

For the purpose of this tutorial we will assume your backup file is stored in the directory /home/test and named backup.tar.gz. If you are restoring files to directories owned by root, gain superuser access as above by prefacing commands with sudo. Ensure your archive is NOT stored in the directories to be restored, or it will be overwritten during the operation.

Restore Your Backup

tar -xvpzf /home/test/backup.tar.gz -C / 

A brief explanation:

  • x - Tells tar to extract the file designated by the f option immediately after. In this case, the archive is /home/test/backup.tar.gz

  • -C <directory> - This option tells tar to change to a specific directory before extracting. In this example, we are restoring to the root (/) directory.

IconsPage/warning.png This will overwrite every single file and directory on the designated mount with the one in the archive. Any file created after the archive, will have no equivalent stored in the archive and thus will remain untouched

Allow the restoration the time it needs to complete. Once extraction is completed, recreate directories that were not included in the original archive. In our example, these would include /proc, /lost+found, /sys, /mnt and /media. This can be done with the following command in our example:

mkdir /proc /lost+found /sys /mnt /media 

Once finished, reboot and everything should be restored to the state of your system when you made the backup.

 

Restoring Over a Network

This short guide, assumes you employed nc to make the original backup as described above.

Receiving Computer 
Ensure the disk has been mounted and use the following command to accept input over the network that will then be extracted to the path indicated. In this example, the directory /mnt/disk will be extracted to.

nc -l 1024 | tar -xvpjf - -C /mnt/disk 

Sending Computer 
On the computer with the archive to send, use the following command:

cat backup.tar.gz | nc -q 0 <receiving host> 1024 

A few comments:

  • The - character in the first command will tell tar to accept input from standard input rather than a file. In this case, input comes from the pipe.

  • The backup file will be expanded without being saved on the disk of receiving computer, the same as when the backup was made.

 

Reformatted Partitions

If you had to format partitions or are restoring to different discs, update the /etc/fstab and /boot/grub/menu.lst files after restoring the backup.

  1. Mount the reformatted partitions on a LiveCD.
  2. Open a terminal and type

    blkid
  3. Making note of the UUIDs listed, edit the /etc/fstab and /boot/grub/menu.lst files in the restored root partition to match. Use the following commands to edit the files respectively.

 

sudo nano /mnt/disk/etc/fstab 

 

sudo nano /mnt/disk/boot/grub/menu.lst 

Change the UUIDs to match the results of your blkid command.

 

Restoring RAID1 to EXT3 for import into VM

Use this up procedure for logical transfert to disk into VM system bootup with live-cd and create first your file system with one Ext2/3 partition and Swap partition.The procedure for restore RAID1 or RAID5 to VM engine request this additional step for regenerate image for upload with Grub

cd /media/disk/etc/
mv mdadm.conf mdadm.conf.old
mkinitrd /media/disk/boot/initrd-noraid-'uname -r'.img 'uname -r'
cd /media/disk/grub

If not available mkinitrd command use $sudo apt-get install initrd-tools.Now edit grub.conf and change kernel boot parameter root= to reflectpartion without raid e.g. change from /dev/md0 to /dev/sda1, also change the initrd= line to /boot/initrd=noraid-x.x.x.img

Now system is ready to next setup GRUB (step below) and re-boot of virtual machine without Raid.

 

Restoring GRUB

In most cases restoring GRUB should not be necessary since we are only restoring files.

If you find yourself unable to boot GRUB properly, follow the instructions on GrubHowto
转载请注明出处:http://www.cnblogs.com/haochuang/ 8年IT工作经验,5年测试技术与管理,2年产品与项目管理,曾参与过云计算\云存储\车联网产品研发工作; 业余自媒体人,有技术类垂直微信公众号;如有招聘或求职方面需求,请Mail to uetest@qq.com ;或通过 QQ:363573922 微博:@念槐聚 联系;

相关文章
|
7天前
|
Linux
【Linux系统编程】基础指令(二)(下)
【Linux系统编程】基础指令(二)
|
7天前
|
Linux C语言
【Linux系统编程】基础指令(二)(上)
【Linux系统编程】基础指令(二)
|
5天前
|
运维 监控 Linux
提升系统稳定性:Linux内核参数调优实战
【5月更文挑战第1天】 在运维领域,保障服务器的高效稳定运行是核心任务之一。Linux操作系统因其开源、可靠和灵活的特点被广泛应用于服务器中。本文将深入探讨通过调整Linux内核参数来优化系统性能,提升服务器的稳定性和响应能力。文章首先介绍了内核参数调优的必要性和基本原则,然后详细阐述了调优过程中的关键步骤,包括如何监控当前系统状态,确定性能瓶颈,选择合适的参数进行调优,以及调优后的测试与验证。最后,文中提供了一些常见问题的解决策略和调优的最佳实践。
26 5
|
5天前
|
Linux
Linux系统ps命令
这些是一些常见的 `ps`命令选项和用法,用于查看系统中运行的进程及其相关信息。您可以根据需要选择合适的选项以满足您的任务要求。
18 0
|
6天前
|
存储 负载均衡 网络协议
在Linux中优化系统性能的实用指南
【4月更文挑战第30天】本文是关于Linux系统性能优化的指南,涵盖硬件选择、系统及软件更新、调整Swap分区、内核参数优化、使用性能分析工具、文件系统优化、网络服务优化和定期维护等方面。通过这些方法,可提升系统响应速度,降低资源消耗,延长硬件寿命。注意,优化需根据具体系统和应用需求进行。
|
6天前
|
弹性计算 Shell Linux
|
6天前
|
存储 缓存 Linux
linux几种典型应用对系统资源使用的特点
【4月更文挑战第22天】几种典型应用对系统资源使用的特点
15 0
|
7天前
|
Web App开发 监控 Unix
Linux 常用命令汇总(七):进程管理 & 系统权限 & 用户授权
Linux 常用命令汇总(七):进程管理 & 系统权限 & 用户授权
|
7天前
|
Unix 大数据 Linux
Linux系统简介与开源精神
Linux系统简介与开源精神
26 3