Scroll to navigation

virt-sysprep(1) Virtualization Support virt-sysprep(1)
 

НАЗВА

virt-sysprep - Reset, unconfigure or customize a virtual machine so clones can be made

КОРОТКИЙ ОПИС

 virt-sysprep [--параметри] -d назва_домену
 virt-sysprep [--параметри] -a disk.img [-a disk.img ...]

ОПИС

Virt-sysprep can reset or unconfigure a virtual machine so that clones can be made from it. Steps in this process include removing SSH host keys, removing persistent network MAC configuration, and removing user accounts. Virt-sysprep can also customize a virtual machine, for instance by adding SSH keys, users or logos. Each step can be enabled or disabled as required.
Virt-sysprep modifies the guest or disk image in place. The guest must be shut down. If you want to preserve the existing contents of the guest, you must snapshot, copy or clone the disk first. See "COPYING AND CLONING" below.
You do not need to run virt-sysprep as root. In fact we'd generally recommend that you don't. The time you might want to run it as root is when you need root in order to access the disk image, but even in this case it would be better to change the permissions on the disk image to be writable as the non-root user running virt-sysprep.
"Sysprep" stands for "system preparation" tool. The name comes from the Microsoft program "sysprep.exe" which is used to unconfigure Windows machines in preparation for cloning them. Having said that, virt-sysprep does not currently work on Microsoft Windows guests. We plan to support Windows sysprepping in a future version, and we already have code to do it.

ПАРАМЕТРИ

--help
Показати коротку довідку.
-a файл
--add файл
Додати файл, який має бути образом диска з віртуальної машини.
Формат образу диска визначається автоматично. Щоб перевизначити його і примусово використати певний формат, скористайтеся параметром --format.
-a адреса
--add адреса
Add a remote disk. The URI format is compatible with guestfish. See "ADDING REMOTE STORAGE" in guestfish(1).
-c адреса
--connect адреса
Якщо використовується libvirt, встановити з’єднання з вказаним URI. Якщо пропущено, з’єднання буде встановлено з типовим гіпервізором libvirt.
Якщо вказати блокові пристрої гостьових систем безпосередньо ( -a), libvirt не буде використовуватися взагалі.
-d гість
--domain гість
Додати всі диски з вказаної гостьової системи libvirt. UUID доменів можна використовувати замість назв.
-n
--dry-run
Perform a read-only "dry run" on the guest. This runs the sysprep operation, but throws away any changes to the disk at the end.
--enable дії
Choose which sysprep operations to perform. Give a comma-separated list of operations, for example:
 --enable ssh-hostkeys,udev-persistent-net
    
would enable ONLY "ssh-hostkeys" and "udev-persistent-net" operations.
If the --enable option is not given, then we default to trying most sysprep operations (see --list-operations to show which are enabled).
Regardless of the --enable option, sysprep operations are skipped for some guest types.
Use --list-operations to list operations supported by a particular version of virt-sysprep.
See "OPERATIONS" below for a list and an explanation of each operation.
--operation дії
--operations дії
Choose which sysprep operations to perform. Give a comma-separated list of operations, for example:
 --operations ssh-hostkeys,udev-persistent-net
    
would enable ONLY "ssh-hostkeys" and "udev-persistent-net" operations.
--operations allows you to enable and disable any operation, including the default ones (which would be tried when specifying neither --operations nor --enable) and all the available ones; prepending a "-" in front of an operation name removes it from the list of enabled operations, while the meta-names "defaults" and "all" represent respectively the operations enabled by default and all the available ones. For example:
 --operations firewall-rules,defaults,-tmp-files
    
would enable the "firewall-rules" operation (regardless whether it is enabled by default), all the default ones, and disable the "tmp-files" operation.
--operations can be specified multiple times; the first time the set of enabled operations is empty, while any further --operations affects the operations enabled so far.
If the --operations option is not given, then we default to trying most sysprep operations (see --list-operations to show which are enabled).
Regardless of the --operations option, sysprep operations are skipped for some guest types.
Use --list-operations to list operations supported by a particular version of virt-sysprep.
See "OPERATIONS" below for a list and an explanation of each operation.
--format raw|qcow2|..
--format auto
Типовим значенням для параметра -a є автоматичне визначення формату образу диска. Використання цього параметра примусово визначає значення параметрів -a формату диска у наступному рядку команди. Використання параметра --format auto перемикає програму у режим автоматичного визначення у наступних параметрах -a.
Приклад:
 virt-sysprep --format raw -a disk.img
    
примусове встановлення формату без обробки (без автоматичного визначення) для "disk.img".
 virt-sysprep --format raw -a disk.img --format auto -a another.img
    
примусове встановлення формату без обробки (без автоматичного визначення) для "disk.img" і повернення до автоматичного визначення для "another.img".
Якщо ви користуєтеся ненадійними образами гостьових систем у необробленому форматі, вам слід скористатися цим параметром для визначення формату диска. Таким чином можна уникнути можливих проблем з захистом для сформованих зловмисниками гостьових систем (CVE-2010-3851).
--list-operations
List the operations supported by the virt-sysprep program.
These are listed one per line, with one or more single-space-separated fields, eg:
 $ virt-sysprep --list-operations
 bash-history * Remove the bash history in the guest
 cron-spool * Remove user at-jobs and cron-jobs
 dhcp-client-state * Remove DHCP client leases
 dhcp-server-state * Remove DHCP server leases
 [etc]
    
The first field is the operation name, which can be supplied to --enable. The second field is a "*" character if the operation is enabled by default or blank if not. Subsequent fields on the same line are the description of the operation.
Before libguestfs 1.17.33 only the first (operation name) field was shown and all operations were enabled by default.
--mount-options mp:opts[;mp:opts;...]
Set the mount options used when libguestfs opens the disk image. Note this has no effect on the guest. It is used when opening certain guests such as ones using the UFS (BSD) filesystem.
Use a semicolon-separated list of "mountpoint:options" pairs. You may need to quote this list to protect it from the shell.
Приклад:
 --mount-options "/:noatime"
    
will mount the root directory with "notime". This example:
 --mount-options "/:noatime;/var:rw,nodiratime"
    
will do the same, plus mount "/var" with "rw,nodiratime".
-q
--quiet
Не виводити повідомлень до журналу.
To enable detailed logging of individual file operations, use -x.
-v
--verbose
Увімкнути докладний показ повідомлень з метою діагностики.
-V
--version
Показати дані щодо версії і завершити роботу.
-x
Увімкнути трасування викликів програмного інтерфейсу libguestfs.
--chmod PERMISSIONS:FILE (see "customize" below)
Change the permissions of "FILE" to "PERMISSIONS".
Note: "PERMISSIONS" by default would be decimal, unless you prefix it with 0 to get octal, ie. use 0700 not 700.
--delete PATH (see "customize" below)
Delete a file from the guest. Or delete a directory (and all its contents, recursively).
Див. також --upload, --scrub.
--edit FILE:EXPR (see "customize" below)
Edit "FILE" using the Perl expression "EXPR".
Be careful to properly quote the expression to prevent it from being altered by the shell.
Note that this option is only available when Perl 5 is installed.
Див. "NON-INTERACTIVE EDITING" in virt-edit(1).
--firstboot SCRIPT (see "customize" below)
Install "SCRIPT" inside the guest, so that when the guest first boots up, the script runs (as root, late in the boot process).
The script is automatically chmod +x after installation in the guest.
The alternative version --firstboot-command is the same, but it conveniently wraps the command up in a single line script for you.
You can have multiple --firstboot options. They run in the same order that they appear on the command line.
Див. також --run.
--firstboot-command 'CMD+ARGS' (see "customize" below)
Run command (and arguments) inside the guest when the guest first boots up (as root, late in the boot process).
You can have multiple --firstboot options. They run in the same order that they appear on the command line.
Див. також --run.
--firstboot-install PKG,PKG.. (see "customize" below)
Install the named packages (a comma-separated list). These are installed when the guest first boots using the guest's package manager (eg. apt, yum, etc.) and the guest's network connection.
For an overview on the different ways to install packages, see "INSTALLING PACKAGES" in virt-builder(1).
--hostname HOSTNAME (see "customize" below)
Set the hostname of the guest to "HOSTNAME". You can use a dotted hostname.domainname (FQDN) if you want.
--install PKG,PKG.. (see "customize" below)
Install the named packages (a comma-separated list). These are installed during the image build using the guest's package manager (eg. apt, yum, etc.) and the host's network connection.
For an overview on the different ways to install packages, see "INSTALLING PACKAGES" in virt-builder(1).
Див. також --update.
--keep-user-accounts USERS (see "user-account" below)
Облікові записи користувачів, які слід залишити у гостьовій системі. Значенням цього параметра є список імен користувачів, відокремлених комами, який визначатиме ті записи, які слід зберегти. Приклад:
 --keep-user-accounts mary
    
збереже обліковий запис користувача "mary".
Цей параметр можна вказувати декілька разів у одній команді.
--link TARGET:LINK[:LINK..] (see "customize" below)
Create symbolic link(s) in the guest, starting at "LINK" and pointing at "TARGET".
--mkdir DIR (see "customize" below)
Create a directory in the guest.
This uses "mkdir -p" so any intermediate directories are created, and it also works if the directory already exists.
--no-logfile (see "customize" below)
Scrub "builder.log" (log file from build commands) from the image after building is complete. If you don't want to reveal precisely how the image was built, use this option.
Див. також "LOG FILE".
--password USER:SELECTOR (see "customize" below)
Set the password for "USER". (Note this option does not create the user account).
See "USERS AND PASSWORDS" in virt-builder(1) for the format of the "SELECTOR" field, and also how to set up user accounts.
--password-crypto md5|sha256|sha512 (see "customize" below)
When the virt tools change or set a password in the guest, this option sets the password encryption of that password to "md5", "sha256" or "sha512".
"sha256" and "sha512" require glibc ≥ 2.7 (check crypt(3) inside the guest).
"md5" працюватиме з відносно давніми гостьовими системами Linux (наприкладRHEL 3), але є незахищеним щодо новітніх способів атак.
Типовим способом шифрування є "sha512". Він використовується, якщо libguestfs вдасться виявити у гостьовій системі підтримку SHA-512. Якщо такої підтримки не буде виявлено, використовуватиметься "md5". За допомогою цього параметра ви можете перевизначити автоматично визначений libguestfs спосіб шифрування.
Note this does not change the default password encryption used by the guest when you create new user accounts inside the guest. If you want to do that, then you should use the --edit option to modify "/etc/sysconfig/authconfig" (Fedora, RHEL) or "/etc/pam.d/common-password" (Debian, Ubuntu).
--remove-user-accounts USERS (see "user-account" below)
Облікові записи користувачів, які слід вилучити з гостьової системи. Значенням цього параметра є список імен користувачів, відокремлених комами, який визначатиме ті записи, які слід вилучити. Приклад:
 --remove-user-accounts bob,eve
    
would only remove the user accounts "bob" and "eve".
Цей параметр можна вказувати декілька разів у одній команді.
--root-password SELECTOR (see "customize" below)
Встановити пароль користувача root.
See "USERS AND PASSWORDS" in virt-builder(1) for the format of the "SELECTOR" field, and also how to set up user accounts.
Note: In virt-builder, if you don't set --root-password then the guest is given a random root password.
--run SCRIPT (see "customize" below)
Run the shell script (or any program) called "SCRIPT" on the disk image. The script runs virtualized inside a small appliance, chrooted into the guest filesystem.
The script is automatically chmod +x.
If libguestfs supports it then a limited network connection is available but it only allows outgoing network connections. You can also attach data disks (eg. ISO files) as another way to provide data (eg. software packages) to the script without needing a network connection ( --attach). You can also upload data files ( --upload).
You can have multiple --run options. They run in the same order that they appear on the command line.
See also: --firstboot, --attach, --upload.
--run-command 'CMD+ARGS' (see "customize" below)
Run the command and arguments on the disk image. The command runs virtualized inside a small appliance, chrooted into the guest filesystem.
If libguestfs supports it then a limited network connection is available but it only allows outgoing network connections. You can also attach data disks (eg. ISO files) as another way to provide data (eg. software packages) to the script without needing a network connection ( --attach). You can also upload data files ( --upload).
You can have multiple --run-command options. They run in the same order that they appear on the command line.
See also: --firstboot, --attach, --upload.
--script SCRIPT (see "script" below)
Run the named "SCRIPT" (a shell script or program) against the guest. The script can be any program on the host. The script's current directory will be the guest's root directory.
Note: If the script is not on the $PATH, then you must give the full absolute path to the script.
--scriptdir SCRIPTDIR (see "script" below)
Точку монтування (порожній каталог на вузлі), використану при виконанні дії "script", увімкнено і вказано використання одного або декількох скриптів за допомогою --script.
Зауваження: "SCRIPTDIR" має бути вказано повністю.
Якщо --scriptdir не вказано, буде створено тимчасову точку монтування
--scrub FILE (see "customize" below)
Витерти файл з гостьової системи. Подібне до --delete, окрім того, що:
It scrubs the data so a guest could not recover it.
It cannot delete directories, only regular files.
--selinux-relabel (see "customize" below)
Relabel files in the guest so that they have the correct SELinux label.
You should only use this option for guests which support SELinux.
--timezone TIMEZONE (see "customize" below)
Set the default timezone of the guest to "TIMEZONE". Use a location string like "Europe/London"
--update (see "customize" below)
Do the equivalent of "yum update", "apt-get upgrade", or whatever command is required to update the packages already installed in the template to their latest versions.
Див. також --install.
--upload FILE:DEST (see "customize" below)
Upload local file "FILE" to destination "DEST" in the disk image. File owner and permissions from the original are preserved, so you should set them to what you want them to be in the disk image.
"DEST" could be the final filename. This can be used to rename the file on upload.
If "DEST" is a directory name (which must already exist in the guest) then the file is uploaded into that directory, and it keeps the same name as on the local filesystem.
Див. також --mkdir, --delete, --scrub.
--write FILE:CONTENT (see "customize" below)
Записати "ДАНІ" до файла "ФАЙЛ".

ДІЇ

If the --enable/--operations option is not given, then most sysprep operations are enabled.
Use "virt-sysprep --list-operations" to list all operations for your virt-sysprep binary. The ones which are enabled by default are marked with a "*" character. Regardless of the --enable/--operations options, sysprep operations are skipped for some guest types.
Operations can be individually enabled using the --enable/--operations options. Use a comma-separated list, for example:
 virt-sysprep --operations ssh-hostkeys,udev-persistent-net [etc..]
Future versions of virt-sysprep may add more operations. If you are using virt-sysprep and want predictable behaviour, specify only the operations that you want to have enabled.
"*" = enabled by default when no --enable/--operations option is given.

abrt-data *

Вилучити дані щодо аварії, створені ABRT.
Вилучити автоматично створені ABRT дані щодо аварії у "/var/spool/abrt/".

bash-history *

Вилучити журнал команд bash у гостьовій системі.
Вилучити журнал команд bash користувача «root» та всіх інших користувачів, у домашніх каталогах яких містяться файли ".bash_history".
Notes on bash-history
У поточній версії пошук домашніх каталогів користувачів виконується лише у "/root" і "/home/*". Отже, журнал bash користувачів, дані яких зберігаються у інших каталогах, не буде вилучено.

blkid-tab *

Вилучити вкладку ідентифікаторів блоків у гостьовій системі.

ca-certificates

Вилучити сертифікати CA у гостьовій системі.

crash-data *

Вилучити дані щодо аварії, створені kexec-tools.
Вилучити автоматично створені kdump дані аварії ядра.

cron-spool *

Вилучити завдання at та cron користувачів.

customize *

Налаштувати гостьову систему.
Налаштувати гостьову систему визначенням параметрів virt-customize(1) для встановлення пакунків, редагування файлів тощо.

dhcp-client-state *

Вилучити надані клієнтські адреси DHCP.

dhcp-server-state *

Вилучити надані серверні адреси DHCP.

dovecot-data *

Вилучити дані Dovecot (поштового сервера).

firewall-rules

Вилучити правила брандмауера.
Вилучає нетипові правила брандмауера вилученням "/etc/sysconfig/iptables" або нетипових налаштувань firewalld з "/etc/firewalld/*/*".
Зауважте, що цю можливість типово не увімкнено, оскільки може відкрити гостьову систему для вразливостей. Користуйтеся обережно.

flag-reconfiguration

Позначити систему для зміни налаштувань.
Для гостьових систем Linux оновлює часову позначку "/.unconfigured", отже, під час першого завантаження користувачеві буде надіслано запит щодо параметрів, зокрема пароля root та часового поясу.

fs-uuids

Змінити UUID файлових систем.
У гостьових системах та типах файлових систем, де передбачено таку підтримку, буде створено нові випадкові UUID, які буде пов’язано з файловими системами.
Зауваження щодо fs-uuids
Типово, дію fs-uuids вимкнено, оскільки у поточній версії програма ще не здатна знайти і оновити усі записи у гостьовій системі, які використовують UUID, наприклад "/etc/fstab" або завантажувач. Вмикання цієї дії може з високою ймовірністю зробити вашу гостьову систему непридатною до завантаження.
Див. https://bugzilla.redhat.com/show_bug.cgi?id=991641

дані-kerberos

Вилучити дані Kerberos у гостьовій системі.

logfiles *

Вилучити з гостьової системи багато файлів журналів.
У Linux вилучено такі файли:
 /etc/Pegasus/*.cnf
 /etc/Pegasus/*.crt
 /etc/Pegasus/*.csr
 /etc/Pegasus/*.pem
 /etc/Pegasus/*.srl
 /root/anaconda-ks.cfg
 /root/anaconda-post.log
 /root/initial-setup-ks.cfg
 /root/install.log
 /root/install.log.syslog
 /var/cache/fontconfig/*
 /var/cache/gdm/*
 /var/cache/man/*
 /var/lib/AccountService/users/*
 /var/lib/fprint/*
 /var/lib/logrotate.status
 /var/log/*.log*
 /var/log/BackupPC/LOG
 /var/log/ConsoleKit/*
 /var/log/anaconda.syslog
 /var/log/anaconda/*
 /var/log/apache2/*_log
 /var/log/apache2/*_log-*
 /var/log/apt/*
 /var/log/aptitude*
 /var/log/audit/*
 /var/log/btmp*
 /var/log/ceph/*.log
 /var/log/chrony/*.log
 /var/log/cron*
 /var/log/cups/*_log*
 /var/log/debug*
 /var/log/dmesg*
 /var/log/exim4/*
 /var/log/faillog*
 /var/log/firewalld*
 /var/log/gdm/*
 /var/log/glusterfs/*glusterd.vol.log
 /var/log/glusterfs/glusterfs.log
 /var/log/grubby*
 /var/log/httpd/*log
 /var/log/installer/*
 /var/log/jetty/jetty-console.log
 /var/log/journal/*
 /var/log/lastlog*
 /var/log/libvirt/libvirtd.log
 /var/log/libvirt/libxl/*.log
 /var/log/libvirt/lxc/*.log
 /var/log/libvirt/qemu/*.log
 /var/log/libvirt/uml/*.log
 /var/log/lightdm/*
 /var/log/mail/*
 /var/log/maillog*
 /var/log/messages*
 /var/log/ntp
 /var/log/ntpstats/*
 /var/log/ppp/connect-errors
 /var/log/rhsm/*
 /var/log/sa/*
 /var/log/secure*
 /var/log/setroubleshoot/*.log
 /var/log/spooler*
 /var/log/squid/*.log
 /var/log/syslog*
 /var/log/tallylog*
 /var/log/tuned/tuned.log
 /var/log/wtmp*
 /var/log/xferlog*
 /var/named/data/named.run

lvm-uuids *

Змінити UUID ФТ і ГТ LVM2.
Для гостьових систем Linux, які містять фізичні томи (ФТ) або групи томів (ГТ) LVM2 для ФТ і ГТ буде створено і призначено випадкові UUID.

ід-комп’ютера *

Вилучити ідентифікатор локального комп’ютера.
Зазвичай, ідентифікатор системи створюється на основі випадкових джерел даних під час встановлення системи і не змінюється під час всіх наступних її завантажень. За потреби у системах без певного стану цей ідентифікатор створюється під час роботи завантажувача, якщо буде виявлено порожнє значення.

mail-spool *

Вилучити поштове повідомлення з локального каталогу поштового буфера.

net-hostname *

Вилучити HOSTNAME у налаштуваннях інтерфейсу мережі.
Для Fedora і Red Hat Enterprise Linux це вилучається з файлів "ifcfg-*".

net-hwaddr *

Вилучити налаштування HWADDR (апаратної адреси MAC).
Для Fedora і Red Hat Enterprise Linux це вилучається з файлів "ifcfg-*".

pacct-log *

Вилучити файли журналу обліку процесів.
Дані обліку процесів системи будуть зберігатися у файлах журналу pacct, якщо увімкнено облік процесів.

package-manager-cache *

Вилучити кеш керування пакунками.

pam-data *

Вилучити дані PAM у гостьовій системі.

puppet-data-log *

Вилучити дані та файли журналів puppet.

rh-subscription-manager *

Вилучити файли керування передплатою RH.

rhn-systemid *

Вилучити ідентифікатор системи у RHN.

rpm-db *

Вилучити специфічні для системи файли баз даних RPM.
Вилучити специфічні для системи файли баз даних RPM. RPM буде повторно створено ці файли, якщо це потрібно.

samba-db-log *

Вилучити бази даних та файли журналів Samba.

script *

Запустити довільні скрипти дій над гостьовою системою.
The "script" module lets you run arbitrary shell scripts or programs against the guest.
Note this feature requires FUSE support. You may have to enable this in your host, for example by adding the current user to the "fuse" group, or by loading a kernel module.
Use one or more --script parameters to specify scripts or programs that will be run against the guest.
The script or program is run with its current directory being the guest's root directory, so relative paths should be used. For example: "rm etc/resolv.conf" in the script would remove a Linux guest's DNS configuration file, but "rm /etc/resolv.conf" would (try to) remove the host's file.
Normally a temporary mount point for the guest is used, but you can choose a specific one by using the --scriptdir parameter.
Note: This is different from --firstboot scripts (which run in the context of the guest when it is booting first time). --script scripts run on the host, not in the guest.

smolt-uuid *

Вилучити UUID обладнання Smolt.

ssh-hostkeys *

Вилучити ключі вузла SSH у гостьовій системі.
Ключі вузла SSH повторно створюються (незалежно) під час наступного завантаження гостьової системи.
Якщо після клонування гостьова система отримати ту саму IP-адресу, ssh надасть вам додаткове попередження щодо зміни ключа вузла:
 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 @    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
 IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!

ssh-userdir *

Вилучити каталоги «.ssh» у гостьовій системі.
Вилучити каталог ".ssh" користувача «root» та всіх інших користувачів, домашні каталоги яких містять каталог ".ssh".
Зауваження щодо ssh-userdir
У поточній версії пошук домашніх каталогів користувачів виконується лише у "/root" і "/home/*". Отже, файли ssh користувачів, дані яких зберігаються у інших каталогах, не буде вилучено.

sssd-db-log *

Вилучити бази даних і файли журналів sssd.

tmp-files *

Вилучити тимчасові файли.
Вилучає тимчасові файли з "/tmp" і "/var/tmp".

udev-persistent-net *

Вилучити постійні правила мережі udev.
Вилучити постійні правила мережі udev, які відображають вже створену MAC-адресу гостьової системи на фіксований пристрій ethernet (наприклад eth0).
Після клонування гостьової системи MAC-адреса зазвичай змінюється. Оскільки стару MAC-адресу вже пов’язано зі старою назвою (наприклад eth0), це означає, що нову MAC-адресу буде пов’язано з новою назвою (наприклад eth1), а це зазвичай є небажаним. За допомогою вилучення постійних правил мережі udev цьому можна запобігти.

user-account

Вилучити облікові записи користувачів у гостьовій системі.
By default remove all the user accounts and their home directories. The "root" account is not removed.
See the --remove-user-accounts parameter for a way to specify how to remove only some users, or to not remove some others.

utmp *

Вилучити файл utmp.
У цьому файлі зберігаються записи щодо входу користувачів до машини. У сучасних дистрибутивах Linux ці записи зберігаються на диску у пам’яті, тому не є частиною віртуальної машини на диску, але ці дані зберігаються на диску у старіших версіях дистрибутивів.

yum-uuid *

Вилучити UUID yum.
Yum створить новий UUID під час наступного запуску, коли виявить, що початковий UUID було вилучено.

КОПІЮВАННЯ ТА КЛОНУВАННЯ

Virt-sysprep can be used as part of a process of cloning guests, or to prepare a template from which guests can be cloned. There are many different ways to achieve this using the virt tools, and this section is just an introduction.
A virtual machine (when switched off) consists of two parts:
налаштування
The configuration or description of the guest. eg. The libvirt XML (see "virsh dumpxml"), the running configuration of the guest, or another external format like OVF.
Some configuration items that might need to be changed:
назва
UUID
шлях до блокових пристроїв
MAC-адреса мережевої картки
блокові пристрої
One or more hard disk images, themselves containing files, directories, applications, kernels, configuration, etc.
Some things inside the block devices that might need to be changed:
hostname and other net configuration
UUID
SSH host keys
Windows unique security ID (SID)
Puppet registration

КОПІЮВАННЯ БЛОКОВОГО ПРИСТРОЮ

Starting with an original guest, you probably wish to copy the guest block device and its configuration to make a template. Then once you are happy with the template, you will want to make many clones from it.
                        virt-sysprep
                             |
                             v
 original guest --------> template ---------->
                                      \------> cloned
                                       \-----> guests
                                        \---->
You can, of course, just copy the block device on the host using cp(1) or dd(1).
                   dd                 dd
 original guest --------> template ---------->
                                      \------> cloned
                                       \-----> guests
                                        \---->
There are some smarter (and faster) ways too:
                          snapshot
                template ---------->
                            \------> cloned
                             \-----> guests
                              \---->
You may want to run virt-sysprep twice, once to reset the guest (to make a template) and a second time to customize the guest for a specific user:
                    virt-sysprep        virt-sysprep
                      (reset)      (add user, keys, logos)
                         |                   |
                 dd      v          dd       v
 original guest ----> template ---------> copied ------> custom
                                          template       guest
Create a snapshot using qemu-img:
 qemu-img create -f qcow2 -o backing_file=original snapshot.qcow
    
The advantage is that you don't need to copy the original (very fast) and only changes are stored (less storage required).
Note that writing to the backing file once you have created guests on top of it is not possible: you will corrupt the guests.
Create a snapshot using "lvcreate --snapshot".
Other ways to create snapshots include using filesystems-level tools (for filesystems such as btrfs).
Most Network Attached Storage (NAS) devices can also create cheap snapshots from files or LUNs.
Get your NAS to duplicate the LUN. Most NAS devices can also duplicate LUNs very cheaply (they copy them on-demand in the background).
Prepare your template using virt-sparsify(1). See below.

VIRT-CLONE

A separate tool, virt-clone(1), can be used to duplicate the block device and/or modify the external libvirt configuration of a guest. It will reset the name, UUID and MAC address of the guest in the libvirt XML.
virt-clone(1) does not use libguestfs and cannot look inside the disk image. This was the original motivation to write virt-sysprep.

SPARSIFY

              virt-sparsify
 original guest --------> template
virt-sparsify(1) can be used to make the cloning template smaller, making it easier to compress and/or faster to copy.
Notice that since virt-sparsify also copies the image, you can use it to make the initial copy (instead of "dd").

ЗМІНА РОЗМІРІВ

                         virt-resize
                template ---------->
                            \------> cloned
                             \-----> guests
                              \---->
If you want to give people cloned guests, but let them pick the size of the guest themselves (eg. depending on how much they are prepared to pay for disk space), then instead of copying the template, you can run virt-resize(1). Virt-resize performs a copy and resize, and thus is ideal for cloning guests from a template.

FIRSTBOOT VS SCRIPT

The two options --firstboot and --script both supply shell scripts that are run against the guest. However these two options are significantly different.
--firstboot script uploads the file "script" into the guest and arranges that it will run, in the guest, when the guest is next booted. (The script will only run once, at the "first boot").
--script script runs the shell "script" on the host, with its current directory inside the guest filesystem.
If you needed, for example, to "yum install" new packages, then you must not use --script for this, since that would (a) run the "yum" command on the host and (b) wouldn't have access to the same resources (repositories, keys, etc.) as the guest. Any command that needs to run on the guest must be run via --firstboot.
On the other hand if you need to make adjustments to the guest filesystem (eg. copying in files), then --script is ideal since (a) it has access to the host filesystem and (b) you will get immediate feedback on errors.
Either or both options can be used multiple times on the command line.

БЕЗПЕКА

Although virt-sysprep removes some sensitive information from the guest, it does not pretend to remove all of it. You should examine the "OPERATIONS" above and the guest afterwards.
Sensitive files are simply removed. The data they contained may still exist on the disk, easily recovered with a hex editor or undelete tool. The --scrub option can be used to scrub files instead of just deleting them. virt-sparsify(1) is another way to remove this content. See also the scrub(1) command to get rid of deleted content in directory entries and inodes.

БАЗА ВИПАДКОВОСТІ

(Цей розділ стосується лише гостьових систем Linux)
For supported guests, virt-sysprep writes a few bytes of randomness from the host into the guest's random seed file.
If this is just done once and the guest is cloned from the same template, then each guest will start with the same entropy, and things like SSH host keys and TCP sequence numbers may be predictable.
Therefore you should arrange to add more randomness after cloning from a template too, which can be done by enabling just the customize module:
 cp template.img newguest.img
 virt-sysprep --enable customize -a newguest.img

WINDOWS 8

Windows 8 "fast startup" can prevent virt-sysprep from working. See "WINDOWS HIBERNATION AND WINDOWS 8 FAST STARTUP" in guestfs(3).

СТАН ВИХОДУ

This program returns 0 on success, or 1 if there was an error.

ЗМІННІ СЕРЕДОВИЩА

"VIRT_TOOLS_DATA_DIR"
This can point to the directory containing data files used for Windows firstboot installation.
Normally you do not need to set this. If not set, a compiled-in default will be used (something like "/usr/share/virt-tools").
Цей каталог може містити такі файли:
"rhsrvany.exe"
This is the RHSrvAny Windows binary, used to install a "firstboot" script in Windows guests. It is required if you intend to use the --firstboot or --firstboot-command options with Windows guests.
Див. також "https://github.com/rwmjones/rhsrvany"
Опис інших змінних середовища наведено у розділі "ENVIRONMENT VARIABLES" in guestfs(3).

ТАКОЖ ПЕРЕГЛЯНЬТЕ

guestfs(3), guestfish(1), virt-builder(1), virt-clone(1), virt-customize(1), virt-rescue(1), virt-resize(1), virt-sparsify(1), virsh(1), lvcreate(8), qemu-img(1), scrub(1), http://libguestfs.org/, http://libvirt.org/.

АВТОРИ

Richard W.M. Jones http://people.redhat.com/~rjones/
Wanlong Gao, Fujitsu Ltd.

АВТОРСЬКІ ПРАВА

Copyright (C) 2011-2014 Red Hat Inc.
Авторські права належать Fujitsu Ltd., 2012

LICENSE

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

BUGS

To get a list of bugs against libguestfs, use this link: https://bugzilla.redhat.com/buglist.cgi?component=libguestfs&product=Virtualization+Tools
To report a new bug against libguestfs, use this link: https://bugzilla.redhat.com/enter_bug.cgi?component=libguestfs&product=Virtualization+Tools
When reporting a bug, please supply:
The version of libguestfs.
Where you got libguestfs (eg. which Linux distro, compiled from source, etc)
Describe the bug accurately and give a way to reproduce it.
Run libguestfs-test-tool(1) and paste the complete, unedited output into the bug report.
2014-10-18 libguestfs-1.28.1