- Клонирование жёсткого диска на Linux
- Инструменты клонирования дисков Linux
- 1. dd: инструмент для клонирования Native Linux
- 2. Инструмент клонирования разделов Linux, Partimage
- 3. Partclone: программное обеспечение для создания разделов и клонирования
- 4. Клонируйте свой диск Linux с помощью Clonezilla
- Клонировать ваш жесткий диск Linux легко
- Disk cloning
- Contents
- Using dd
- Using ddrescue
- File system cloning
- Using e2image
- Disk cloning software
- Disk cloning in Linux using dd command
- How to clone a partition from one disk to another
- How to clone an entire disk
- How to create a disk image
- Compressed disk image
- Send disk image to remote system
- Split the disk image by size
- Restoring disk image
- How to Clone a Partition or Hard drive in Linux
- How to Clone Linux Partition
- How to Clone Linux Hard Drive
- How to Backup MBR in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Клонирование жёсткого диска на Linux
То, что вы работаете в операционной системе Linux, не означает, что вы не будете время от времени сталкиваться с проблемами. Всегда хорошо иметь план резервного копирования, на случай, если возникнет проблема. Возможно, редкий вирус Linux будет атаковать; возможно, вы будете жертвами мошенников-вымогателей. Может быть, жесткий диск (HDD) выйдет из строя.
Клонируя жесткий диск Linux, вы создаете образ диска, который можно восстановить позже. Но как вы клонируете свой жесткий диск Linux?
Инструменты клонирования дисков Linux
Ваша установка Linux может привести к ошибке; Вы можете обновить жесткий диск до большего объема. Безотносительно проблемы, если у вас есть резервная копия вашего диска, восстановить и запустить все будет относительно просто.
В Linux есть четыре решения для клонирования дисков, которые вы должны рассмотреть:
Используете ли вы функции, встроенные в вашу операционную систему Linux, или устанавливаете сторонний инструмент, не должно пройти много времени, прежде чем вы сможете восстановить свою систему и запустить ее.
Давайте рассмотрим каждый из четырех основных вариантов клонирования диска в Linux.
1. dd: инструмент для клонирования Native Linux
Возможно, самый мощный инструмент Linux из всех, dd (иногда называемый «разрушитель диска»), может клонировать весь жесткий диск или раздел диска в другой. Но в случае неправильного использования он может удалить содержимое вашего диска.
Таким образом, вы должны использовать с особой осторожностью. Вы найдете dd встроенный в большинство операционных систем Linux. Если нет, установите его из менеджера пакетов. Чтобы клонировать жесткий диск вашего компьютера, используйте команду:
Здесь sdX — это исходный диск, а sdY — место назначения. Числовое значение 64K соответствует команде размера блока, bs. Значение по умолчанию составляет 512 байт, что очень мало, поэтому лучше включить 64K или более 128K в качестве условия. Однако: хотя больший размер блока делает передачу быстрее, меньший размер блока делает передачу более надежной.
Если вы хотите клонировать только раздел вашего диска, используйте
Как вы можете видеть, раздел sda1 (то есть раздел 1 на устройстве sda) будет клонирован в sdb1 (вновь созданный раздел 1 на устройстве sdb), например, вторичный или внешний жесткий диск, подключенный к вашему компьютеру.
Нажмите Enter, чтобы запустить команду. Сколько времени это займет, будет зависеть от размера диска или раздела. Просто убедитесь, что объем назначения достаточно велик для его хранения!
2. Инструмент клонирования разделов Linux, Partimage
Если вы столкнулись с проблемами, пытаясь разобраться с инструкциями с помощью dd, или предпочли бы избежать случайного удаления вашего жесткого диска с опечаткой, partimage также доступен для большинства дистрибутивов и не несет риска «уничтожения диска»!
Однако partimage не поддерживает файловую систему ext4, поэтому избегайте ее использования для клонирования дисков или разделов этого типа. Однако при необходимости его можно использовать для клонирования дисковых форматов Windows (FAT32 или NTFS, хотя это экспериментально), а также для более широко используемой файловой системы Linux ext3 и других более старых альтернатив.
Перед началом убедитесь, что раздел, который вы хотите клонировать, отключен ( с помощью команды umount ). В противном случае вам нужно будет выйти из partimage, прежде чем продолжить процесс. Вы можете выйти в любое время с помощью клавиши F6 .
Для Ubuntu установите:
Запустите из командной строки:
Это приложение, управляемое мышью, которое требует, чтобы вы сначала выбрали раздел, который нужно клонировать.
Нажмите вправо на клавиши со стрелками, чтобы перейти к следующему разделу, затем Image file to create/use и дайте ему имя (или введите имя файла изображения, которое будет восстановлено).
Выберите Action to be done (убедитесь, что у выбранной опции есть звездочка) и нажмите F5, чтобы продолжить. На следующем экране выберите уровень сжатия и предпочитаемые параметры. Вы также можете выбрать режим разделения изображений и указать, что должно произойти после создания резервной копии.
Нажмите F5, чтобы продолжить, подтвердите данные, затем нажмите OK, чтобы начать процесс. Скорость этого будет зависеть от мощности вашего компьютера.
Если вы ищете быстрое и грязное, но безопасное решение для клонирования дисков для Linux, используйте partimage.
3. Partclone: программное обеспечение для создания разделов и клонирования
Для более зрелой альтернативы dd, которая поддерживает резервное копирование файловой системы ext4, partclone прост в использовании, но опять же требует текстовых команд, а не интерфейса, управляемого клавиатурой или мышью. Установить с помощью:
… Где [fstype] — тип файловой системы раздела, который вы хотите клонировать.
Следующая команда создаст образ диска hda1 (жесткий диск 1, раздел 1) с именем hda1.img:
Возможно, вы захотите восстановить это изображение, поэтому используйте
partclone.extfs -r -d -s hda1.img -o /dev/hda1
Более подробную информацию об использовании можно найти на сайте partclone.
4. Клонируйте свой диск Linux с помощью Clonezilla
Для более гибкого решения, почему бы не попробовать Clonezilla? Это популярное решение для аварийного восстановления основано на Partclone и предназначено для ряда задач клонирования дисков. Поддерживаются все ожидаемые файловые системы в Linux, Windows и MacOS (и за ее пределами).
В отличие от dd и Partclone, Clonezilla доступен в виде загрузочного ISO. Вы можете записать это на DVD или USB-накопитель, чтобы полностью клонировать жесткий диск Linux. Clonezilla проста в использовании, с меню на клавиатуре, а не с непонятными командами, так что любой может справиться с этим.
Хотя Clonezilla можно настроить как отдельную утилиту, вы можете предпочесть использовать ее как часть инструмента восстановления Boot CD от Hiren.
Вы также можете использовать Clonezilla на профессиональном уровне, чтобы создавать изображения схожих настроек ПК с одной и той же операционной системой.
Клонировать ваш жесткий диск Linux легко
Если вы никогда ранее не клонировали жесткий диск, возможно, вы неохотно начинаете. Это может быть пугающим, особенно если вы находитесь в тяжелом положении с поврежденным жестким диском, который отчаянно нуждается в клонировании перед отказом.
Хотя вы можете предпочесть просто синхронизировать ваши важные данные в облаке, всегда полезно иметь полную резервную копию диска, которую можно быстро восстановить в случае системных ошибок. Однако не забывайте использовать эти инструменты с осторожностью, поскольку они могут легко привести к случайной потере ваших данных.
Источник
Disk cloning
Disk cloning is the process of making an image of a partition or of an entire hard drive. This can be useful for copying the drive to other computers or for backup and recovery purposes.
Contents
Using dd
Using ddrescue
ddrescue is a tool designed for cloning and recovering data. It copies data from one file or block device (hard disc, cdrom, etc) to another, trying to rescue the good parts first in case of read errors, to maximize the recovered data.
To clone a faulty or dying drive, run ddrescue twice. For the first round, copy every block without read error and map the errors to rescue.map .
where X is the partition letter of the source and Y of the target block device.
For the second round, copy only the bad blocks and try 3 times to read from the source before giving up.
Now you can check the file system for corruption and mount the new drive.
File system cloning
This article or section needs expansion.
Using e2image
e2image is a tool included in e2fsprogs for debugging purposes. It can be used to copy ext2, ext3, and ext4 partitions efficiently by only copying the used blocks. Note that this only works for ext2, ext3, and ext4 filesystems, and the unused blocks are not copied so this may not be a useful tool if one is hoping to recover deleted files.
To clone a partition from physical disk /dev/sda , partition 1, to physical disk /dev/sdb , partition 1 with e2image, run
Disk cloning software
These applications allow easy backup of entire filesystems and recovery in case of failure, usually in the form of a Live CD or USB drive. They contain complete system images from one or more specific points in time and are frequently used to record known good configurations. See Wikipedia:Comparison of disk cloning software for their comparison.
See also Synchronization and backup programs for other applications that can take full system snapshots, among other functionality.
Источник
Disk cloning in Linux using dd command
The dd command utility is a simple yet powerful and useful command available in Unix and Linux systems which is used to convert and copy files. Unix like systems treat all devices as files and these device files are located in the /dev directory in your system. So typically your hard disk drive is a file in the /dev directory with the prefix of hd or sd (depending on IDE or SCSI driver). This concept of device as files makes dd a perfect candidate for backup and restore of disk images or cloning some partitions or the entire disk.
This article shows you some examples of how to use the dd command to backup or clone drive partitions and entire drives.
You can use the fdisk command or check the /proc/partitions to view all the disk partitions in your system.
From the above output we can deduce that you have hard disks on your system and their device file names are sda and sdb. There are two partitions in sda which are sda1 and sda2 and we also know that sda1 is a boot partition.
How to clone a partition from one disk to another
The following are the steps to create a clone of a partition from one disk to another disk, lets say for example you want to clone sda1 partition to sdb1 . In this case sda is your source disk and sdb is the destination disk.
Step 1: Create a new partition in the destination disk if it does not already exist. You can use the fdisk command to create the new partition.
Step 2: Run the dd command.
- conv=sync,noerror tells dd command to continue copying after read errors and fill input block with nulls in case partial records.
- status=progress shows progress of the copy.
- bs=64M set the block size to copy at a time. Adjust this value could improve the copying speed
How to clone an entire disk
To clone an entire disk, say for example sda to sdb , run:
When you clone a entire disk, the destination disk will get all the partitions that are on the source disk.
How to create a disk image
Before you create a disk image backup, make sure no partitions on that disk are mounted and run the following command
where sdb is the disk file name and /path/to/backup.img is the path and filename of the backup image.
Compressed disk image
You could also compress the backup image with gzip as shown in the example below
Send disk image to remote system
You could send the backup image to a remote machine using ssh as in the below example.
Split the disk image by size
You can split the disk image in to smaller pieces of any size that you specify by passing the dd output through split command.
The above command splits the backup image file to smaller files of size 50MB or less. A two letter suffix will be added to the files. The resulting files will have names backup.img.gz.aa, backup.img.gz.ab, backup.img.gz.ac.
To join the split files into a single image file, you run the command
Restoring disk image
The below command restores the disk sdb from the image file backup.img .
To restore from a compressed backup image, use the gunzip command with dd
To restore from a backup image that is compressed and split, run:
Источник
How to Clone a Partition or Hard drive in Linux
There are many reasons why you may want to clone a Linux partition or even hard drive, most of which are related to creating backups of your data. There are multiple ways you can achieve this in Linux by using some external tools such as partimage or Clonezilla.
However in this tutorial we are going to review Linux disk cloning with tool called dd, which is most commonly used to convert or copy files and it comes pre-installed in most Linux distributions.
How to Clone Linux Partition
With dd command you can copy entire hard drive or just a Linux partition. Lets start with cloning one of our partitions. In my case I have the following drives: /dev/sdb, /dev/sdc.. I will clone /dev/sdb1/ to /dev/sdc1.
First list the these partitions using the fdisk command as shown.
List Linux Partitions
Now clone a partition /dev/sdb1/ to /dev/sdc1 using the following dd command.
The above command tells dd to use /dev/sdb1 as input file and write it to output file /dev/sdc1.
Clone Linux Partition with dd Command
After cloning Linux partition, you can then check both partitions with:
Verify Linux Partition Cloning
How to Clone Linux Hard Drive
Cloning a Linux hard drive is similar to cloning a partition. However, instead of specifying the partition, you just use the entire drive. Note that in this case it is recommended that the hard drive is same in size (or bigger) than the source drive.
Clone Hard Drive in Linux
This should have copied the drive /dev/sdb with its partitions on the target hard drive /dev/sdc. You can verify the changes by listing both drives with fdisk command.
Verify Linux Hard Drive Cloning
How to Backup MBR in Linux
dd command can also be used to backup your MBR, which is located at the first sector of the device, before the first partition. So if you want to create backup of your MBR, simply run:
The above command tells dd to copy /dev/sda to /backup/mbr.img with step of 512 bytes and the count option tells to copy only 1 block. In other words you tell dd to copy the first 512 bytes from /dev/sda to the file you have provided.
Backup MBR in Linux
That’s all! dd command is a powerful Linux tool that should be used with caution when copying or cloning Linux partitions or drives.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник