Webmin резервное копирование файлов
Since Webmin is a lesser discussed product, there’s less documentation available on how to secure Webmin servers. The easiest issues to resolve:
-
(Certbot being one of the easiest options)
- Automated Antivirus (AV) scanning
- Webmin Backups
Once you log into the Webmin dashboard, there are multiple options to backup data on a Webmin server. We’ll cover how to do the following below:
If you don’t need cPanel, don't pay for it. Only pay for what you need with our Cloud VPS solutions .
CentOS, Debian, or Ubuntu No bloatware SSH Key management made easy
Простое резервное копирование Ubuntu
Для того что бы выполнить резервное копирование всей системы, достаточно выполнить всего одну команду:
А теперь распишу что означает это команда. С правами суперпользователя ( sudo ) создаём тарбол ( tar с ключём c ) и архивируем его архиватором gz (ключ z ). При этом с помощью ключа --exclude исключаем из архива системные директории и файлы устройств и, конечно же, сам архив (чтобы он рекурсивно не начал паковаться сам в себя). В итоге, получаем в корне наш полный архив системы в файле backup.tgz
Как его потом развернуть? Ну, во-первых, нужна будет всё-таки работающая система. Например, можно провести «читсую» установку (или же загрузиться с LiveCD). Будем считать, что у нас есть работающая система, в которой мы хотим развернуть наш архив. Хватит тоже одной команды:
Благодаря ключику p они сохраняются в исходном состоянии и правами.
Поскольку заранее не известно какого типа у Вас данные и, соответсвенно, насколько плотно они сожмутся. Как минимум вы должны иметь на диске 50% свободного места, для ее проверки выполните седующую команду:
В реальности же, если у вас не лежит множество других архивов на диске и всяких фильмов с прочими медиа, то должно хватить и 30%.
Editing and Deleting Backup Jobs
Once a job has been defined, you can edit it by clicking on the source directory(s) in the first column of the backup jobs table on the module's main page. This will bring up the same form as is shown above, in which all of the job settings can be adjusted.
To delete a job, select the checkbox next to it on the module's main page, and click on the Delete Selected Backups button.
Filesystem Backup module
This module allows you to define backup jobs in a variety of formats, and perform either one-off or regularly scheduled backups to local or remote destinations. It can also restore backups in the formats it creates.
When you open the module (under the System category), it will display a list of existing backup jobs as shown below:
The Filesystem Backup module
If this is the first time you have used the module, the table of backups will be empty though.
Integrate Bacula for Webmin Backups
The Bacula Webmin module allows system administrators to integrate Webmin servers with a Bacula backup and recovery instance. To do so, you must install the Bacula Webmin module from Webmin > Webmin Configuration > Webmin Modules. Choose an installation method, then select Install Module at the bottom. You may then configure backups with the Bacula Backup System from the left-hand menu.
Learn more essential server administration tasks from our Cloud Server Hosting Product Guide.
This page explains what the Backup Configuration Files module does, and how to use it.
Introduction to Unix backup commands
Pretty much all Unix and Linux systems come with the tar command, which can backup multiple files and directories into a single file, with all permissions and ownership information preserved. Tar is the most common Unix backup format, and although it was originally designed for backups to tape (tar stands for Tape Archive), it works just as well to local or remote files. If you are familiar with the zip format on Windows systems, tar is very similar.
Most systems also ship with the dump and restore commands, which are similar to tar but operate at a lower level when it comes to accessing the filesystem. While tar will work with any files (either local, on a removable drive, or mounted from an NFS or SMB server), the dump command can only backup files on a local filesystem. However, it has the advantage that it can backup file attributes that tar misses due to shortcomings in its file format, such as EXT2 attributes and Posix ACLs.
When it comes to choosing which format to use, tar is mandatory if you want to backup non-local files, or if you may need to restore on a system running a different OS (as the dump format is specific to the underlying filesystem type). The dump format is only recommended if you need to backup files that have ACLs or other attributes that tar would miss.
Contents
Configuration Files in Webmin
Most Webmin modules work by editing configuration files on your system, like /etc/exports for NFS shares, /etc/passwd for users and /etc/fstab for filesystems. Each module knows which configuration files it manages, and what commands need to be run to activate them. Not all modules actually deal with config files though - for example, the MySQL module works by executing SQL commands. As such, it cannot participate in the configuration backup process.
The Backup Configuration Files module can collect information about config files from other modules, and create and restore backups containing some or all of those files. It is designed for saving the configuration of a single system, but not for migrating configs from one server to another - that would be far more complex. You can theoretically backup the configs from one system and restore them on another if they are running the exact same OS and version (like Fedora Core 5), but attempting this between systems of different types is almost certain to fail.
Creating a scheduled backup
Once you have performed a manual backup, you can schedule it to run on a regular basis as follows :
- Click on the Scheduled backups tab.
- Click the Add a new scheduled backup link, which will open the form shown below.
- Select the modules whose config files you want to include from the Modules to backup list.
- Enter a local or remote file destination in the Backup destination section.
- If you want to be notified about the status of this backup, enter your email address in the Email result to address field.
- In the Scheduled backup enabled? field select Yes, and choose the times and days for the backup to run from the Cron time selector below it.
- Click the Create button.
Creating a scheduled backup
Once a scheduled backup has been created, you can edit or remove it by clicking on the destination path in the table under the Scheduled backups tab.
Restoring a backup
If you find that a config file on your system has been corrupted, incorrectly edited or mistakenly deleted, it can be easily restored using this module. The steps to perform a restore are :
- Click on the Restore now tab.
- Select the module or modules whose config files you want to restore from the Modules to restore menu.
- In the Restore from section, enter the path to a local or remote file that was originally created by this module. To be useful, it must contain backups for the modules that you selected above.
- Click the Restore Now button.
If all goes well, a page will be displayed showing the number of modules and files restored. Files will be restored to their original locations on the system, rather than the paths that are set on the Module Config pages of the selected modules.
This page explains common Unix backup commands, and how Webmin makes use of them to perform one-off or regular backups and restores.
Backup Webmin Configuration Files
Webmin has the ability to create, schedule, and restore backups of essential server configuration files in the tgz format.
The settings option in the upper-left corner allows you to change the backup data time-frames to strftime or Webmin variable substitution, update the From address for email notifications, and more.
- On the left, under Webmin, select Backup Configuration Files.
- Select Webmin modules to backup. You can select multiple modules with the Ctrl key or all modules between two modules with the Shift key.
- Select a backup destination: local file, external FTP server, external SSH server, or browser download.
- Specify other files to include in the backup: module configuration files, server configuration files, and other files listed in the text box at the bottom of the page.
- At the bottom, select Backup Now.
Restore Webmin Configuration Files
- At the top of the Backup Configuration Files page, select Restore now.
- Select modules to restore and other files if necessary.
- Under Restore from, specify the backup file for restoration.
- Choose where to apply configurations and list files that would be affected.
- At the bottom, select Restore Now.
Автоматическое резервное копирование Ubuntu
на другой диск или по сети
Примечание
- Сеть должна быть настроена
- Винчестер, на который будем делать резервную копию, должен быть подготовлен
Подготавливаем жесткий диск
Смотрим наш жесткий диск и монтируем в /mnt/hdd :
Чтобы после перезагрузки сервера hdd автоматом монтировался, допишем строку в файл /etc/fstab:
Подготавливаем сетевую папку
Если для доступа к сетевой папке требуется логин и пароль:
Если имя сетевой папки содержит пробел, то необходимо написать команду следующим образом:
Для того что бы размонтировать папку выполните команду:
Создаем файл backup.save в корне системы и делаем его исполняемым:
Жмем Ctrl+O для сохранения и Ctrl+X для выхода. Сделаем его исполняемым:
Для проверки запустим его и проверим его работу. Для создания запуска по расписанию выполним следующее:
В файл пропишем следующее:
После этого в каталоге /var/spool/cron/crontabs/ будет создан файл "root" примерно с таким содержимым:
Для примера пару шаблонов:
Restoring a Backup
Так же есть альтернативный способ в Windows, за счет применения программы WinSCP, так же похож на Norton Commander разница лишь в том, что работает она исключительно по сети, а так же производит подключение через SSH протокол. Обратите внимание, что при подключении вы должны быть root пользователем, а на сервере заранее должен быть активирован и установлен супер пользователь (прописан пароль).
Для того что бы выполнить резервное копирование всей системы, достаточно выполнить всего одну команду:
sudo tar cvpzf /backup.tgz --exclude=/proc --exclude=/lost+found --exclude=/backup.tgz --exclude=/mnt --exclude=/sys /
А теперь распишу что означает это команда. С правами суперпользователя (sudo) создаём тарбол (tar с ключём c) и архивируем его архиватором gz (ключ z). При этом с помощью ключа --exclude исключаем из архива системные директории и файлы устройств и, конечно же, сам архив (чтобы он рекурсивно не начал паковаться сам в себя). В итоге, получаем в корне наш полный архив системы в файле backup.tgz
Как его потом развернуть? Ну, во-первых, нужна будет всё-таки работающая система. Например, можно провести «читсую» установку (или же загрузиться с LiveCD). Будем считать, что у нас есть работающая система, в которой мы хотим развернуть наш архив. Хватит тоже одной команды:
Благодаря ключику p они сохраняются в исходном состоянии и правами.
Поскольку заранее не известно какого типа у Вас данные и, соответсвенно, насколько плотно они сожмутся. Как минимум вы должны иметь на диске 50% свободного места, для ее проверки выполните седующую команду:
В реальности же, если у вас не лежит множество других архивов на диске и всяких фильмов с прочими медиа, то должно хватить и 30%.
Жмем Ctrl+O для сохранения и Ctrl+X для выхода
Создаем папку /mnt/backup в которую будем делать резервную копию системы:
Далее идем в корень и открываем наш файл нажатием F4 и вставляем в наш backup.save файл следующий код (нажав Shift+Insert):
Этот код создает архив дата_и_время_создания.tgz в папке /mnt/backup/ исключая папки: proc, lost+found, mnt, sys
Жмем F2 для сохранения и F10 для выхода. Проверяем работоспособность просто запустив наш файл в mc нажатием Enter.
Если все сделали правильно, то в папке /mnt/backup появится наш файл. Периодически заходя в эту папку мы увидим как меняется размер файла. Время резервного копирования естественно зависит от количества информации на сервере и его скорости.
Для перехода в mc в терминал жмем Ctrl+O и обратно, а так же не забываем про Меню в mc - F9
Примечание
Сеть должна быть настроена
Винчестер, на который будем делать резервную копию, должен быть подготовлен
sudo fdisk -l
Диск /dev/sda: 40.0 ГБ, 40020664320 байт
255 heads, 63 sectors/track, 4865 cylinders
Units = цилиндры of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0000c5e7
Устр-во Загр Начало Конец Блоки Id Система
/dev/sda1 * 1 4661 37431296 83 Linux
/dev/sda2 4661 4866 1648641 5 Расширенный
/dev/sda5 4661 4866 1648640 82 Linux своп / Solaris
Диск /dev/sdb: 20.0 ГБ, 20020396032 байт
255 heads, 63 sectors/track, 2434 cylinders
Units = цилиндры of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xd5df5ded
Ctrl+O для сохранения и Crtl+X для выхода
Я не стал прописывать в /etc/fstab автомонтирование сетевой папки. Я буду монтировать ее только тогда, когда будет запускаться скрипт на резервное копирование.
Создаем файл backup.save в корне системы и делаем его исполняемым:
Для проверки запустим его и проверим его работу. Для создания запуска по расписанию выполним следующее:
После этого в каталоге /var/spool/cron/crontabs/ будет создан файл "root" примерно с таким содержимым:
еперь наш скрипт backup.save будет автоматически запускаться каждый день в 21:00.
Если надо запускать в другое время, то просто меняем строку 00 21 * * * /backup.save
Пример:
* * * * * выполняемая команда
- - - - -
| | | | |
| | | | ----- День недели (0 - 7) (Воскресенье =0 или =7)
| | | ------- Месяц (1 - 12)
| | --------- День (1 - 31)
| ----------- Час (0 - 23)
------------- Минута (0 - 59)
Сохраняем каталог boot нашей чистой системы в папку /mnt/
Туда же сохраняем файл fstab из /etc/
распаковываем архив поверх чистой системы
Далее копируем с заменой нашу сохраненную папку boot из /mnt/boot в корень системы с заменой
И fstab из /mnt/ тоже копируем в /etc/ с заменой
Перезагружаем систему
Я считаю это самый простой способ выполнения как резервного копирования, так и восстановление. Для начала у Вас уже должна быть установлена панель управления сервером Webmin (Установка Webmin на Ubuntu server) Заходим в пункт резервного копирования файловой системы Система - Резервное копирование.
На данном изображении я показал уже созданную команду для резервного копирования всей системы. Для начала создания такой команды мы укажим наш каталог, так как мы копируем всю систему, то указываем корень " / ", и нажимаю кнопку "Добавить для резервного копирования каталог", открывшееся окно заполняем следующим образом. Т.к. я использовал удаленный FTP сервер, то добавил сервер имя пользователя и пароль для доступа а так же указал каталог и имя файла в который будет происходить резервное копирование Ubuntu.
Кнопка "Сохранить и приступить к резервному копированию" приведет к созданию правила и немедленного его исполнения. Результат статуса резервного копирования будет выглядеть следующим образом:
И снова короткий обзор резервного копирования Ubuntu постараюсь пойти от простого к сложному, начиная от простого резервного копирования все системы 1 командой и заканчивая резервным копированием Ubuntu в автоматическом режиме без нашего участия. А так же дополню это все облегченным способом при резервном копировании Ubuntu через панель администрирования сервера Webmin .
Для удобства работы с Linux Ubuntu server устанавливаем mc - аналог Norton Commander:
Так же есть альтернативный способ в Windows, за счет применения программы WinSCP, так же похож на Norton Commander разница лишь в том, что работает она исключительно по сети, а так же производит подключение через SSH протокол. Обратите внимание, что при подключении вы должны быть root пользователем, а на сервере заранее должен быть активирован и установлен супер пользователь (прописан пароль)
Schedule Webmin Configuration Backups
- At the top of the Backup Configuration Files page, select Scheduled backups.
- Edit backup options same as for immediate backups covered above.
- Select Pre and post backup commands to add pre-backup and post-backup commands if needed. Possible usage examples for this option include loading / unloading tapes and creating checksums.
- Select Backup schedule to set the cron job timing, what email account should receive results notifications, and when.
- At the bottom, select Create.
You’ll see created Webmin backups listed on the Scheduled backups page showing the backup destination, Webmin modules, and scheduled time.
Contents
Аналогичное резервное копирование Ubuntu в Webmin
Я считаю это самый простой способ выполнения как резервного копирования, так и восстановление. Для начала у Вас уже должна быть установлена панель управления сервером Webmin (Установка Webmin на Ubuntu server) Заходим в пункт резервного копирования файловой системы Система - Резервное копирование.
На данном изображении я показал уже созданную команду для резервного копирования всей системы. Для начала создания такой команды мы укажим наш каталог, так как мы копируем всю систему, то указываем корень " / ", и нажимаю кнопку "Добавить для резервного копирования каталог", открывшееся окно заполняем следующим образом. Т.к. я использовал удаленный FTP сервер, то добавил сервер имя пользователя и пароль для доступа а так же указал каталог и имя файла в который будет происходить резервное копирование Ubuntu.
Кнопка "Сохранить и приступить к резервному копированию" приведет к созданию правила и немедленного его исполнения. Результат статуса резервного копирования будет выглядеть следующим образом:
Расписание на выполнение данного правила я вам посоветовать не могу, в своем личном случае я выполняю резервное копирование в ручную по мере надобности, а вот резервные копии сайтов и настроек системы выполняются автоматически каждый день, раз в неделю и раз в месяц, Резервные копии сайтов включают в себя как сами файлы сайта так и их базы данных.
Обмениваться, хранить, передавать Ваши файлы стало просто как никогда.
Читать подробнее: для чего Yandex-Диск проекту Mini-Server. Практика установки, настройки и использования сетевого хранилища на Ubuntu server LTS 12.04 в статье Резервное копирование сервера Ubuntu на Яндекс Диск.
Using the Backup Configuration Files module
When this module (under the Webmin category) is opened, it will display a set of tabs with the form for making a backup selected by default, as in the image below.
The Backup Configuration Files module
To perform an immediate config backup, follow these steps :
- Click on the Backup now tab.
- In the Modules to backup list, select the modules you want to backup config files for, such as Users and Groups. Multiple modules can be selected by ctrl-clicking.
- In the Backup destination field, select Local file and enter a path to write the backup to. This should be given a tar.gz extension, as that is the file format used.
- Click the Backup Now button.
Assuming the path you entered is valid, a page should appear showing the list of modules whose configs were backed up, and the size of the resulting file.
Backups can also be made to a remote SSH or FTP server, provided you have a login, password and writable directory. This is done by selecting the FTP server or SSH server options in step 3 above, and filling in the appropriate fields.
The "Module Config" page of this module provides options to use variables in the backup path and filename you configured. With the option for timestamp variables enabled, for example,
will add the date of the backup to the filename.
Backup Webmin Filesystem
Webmin offers the ability to schedule full server backups in tar format.
The settings option in the upper-left corner allows you to run backups in the foreground / background, send backup notifications, and more.
- On the left, under System, select Filesystem Backup.
- Select the file icon to the right of the text box.
- Select a file path to backup.
- Select Add a new backup of directory: to continue.
- On the next page, add additional directories to backup.
- Specify the directory (or remote system) and filename for the backup to be created.
- Select the Remote backup command if applicable. Then fill in the Password for SSH/FTP login.
- Select Backup options to specify backup label, files to skip, and more.
- Select Backup schedule to set cron job timing, what email account should receive results notifications and in what situations.
- At bottom, select Save or Save and Backup Now. You can also restore filesystem backups from here.
Webmin backups are listed on the Filesystem Backup page.
Running a Backup
Once a backup job has been defined, it can be started by clicking on the Backup.. link in the last column of the backup jobs table. By default this will start the job as a foreground process so that you can view its progress in the browser. However, for long jobs, it may be better to run them in the background so that closing the browser does not interrupt the process. To enable this, click on the Module Config link and change the Run backups in option to Background.
Jobs run in the background (either explicitly started from the web interface or run on schedule) will be displayed on the module's main page under the Running Backup Jobs header. By clicking on a link in the Action column you can terminate running jobs, or if required signal to the job that a new backup tape is available.
Восстановление системы из резервной копии
Configuration
A few important setting should be defined in the modules' configuration. If you'd like to have hourly/dayly/weekly/monthly/yearly backups, variable substitution would be necessary.
Defining backups
To create a new backup job, do the following:
- In the field next to the Add a new backup of directory button, enter the full path to the directory you want to save. By default, the module will use the dump command for backups, but if you prefer tar format you should select the In tar format checkbox. Then click the button. The rest of these steps will assume that you selected the Tar option, as that is the most common format.
- On the Add New Backup form (shown below), add an additional paths to backup to the Directories to backup field.
- In the Backup to section, you can select File or tape device if you want to save to a file on the same system. In the adjacent field, either enter a path like /backup/myfiles.tar, or if you have an attached tape drive use a path like /dev/st0 (the first SCSI tape drive).
Alternately, you can select the Host option, and enter a remote hostname, login name and remote file into the three fields next to it. Remote backups are clearly preferable in most cases, as they can be restored if the system being backed up completely dies! - If performing a remote backup, the Remote backup command field can be used to select the protocol to use for transferring the backup. SSH is most commonly used, but FTP is a suitable alternative if you don't have an SSH login on the remote system. The default RSH protocol is almost never used these days.
- If backing up via SSH or FTP, you will need to enter a password into the Password for SSH/FTP login field. This can be omitted if the root user on the source system has his .ssh directory setup to allow password-less logins as the destination user.
- Most of the fields in the Backup options section can be left as their defaults. The only exception is Compress archive?, which should be set to Gzip or Bzip if your backup is not to a tape drive.
- If you want the backup to be run on a regular schedule, select the Enabled, at times chosen below.. radio button and enter an email address to notify into the Email scheduled output to field.
- Select a schedule to run from the Cron time / date chooser.
- Click the Create button at the bottom of the form.
Adding a new backup
Автоматическое резервное копирование Ubuntu
на этот же диск
Создаем файл backup.save в корне, в котором будет скрип для резервного копирования:
Создаем папку /mnt/backup в которую будем делать резервную копию системы:
Делаем наш файл backup.save исполняемым:
Заходим в mc (для удобства):
Далее идем в корень и открываем наш файл нажатием F4 и вставляем в наш backup.save файл следующий код (нажав Shift+Insert):
Жмем F2 для сохранения и F10 для выхода. Проверяем работоспособность просто запустив наш файл в mc нажатием Enter.
Если все сделали правильно, то в папке /mnt/backup появится наш файл. Периодически заходя в эту папку мы увидим как меняется размер файла. Время резервного копирования естественно зависит от количества информации на сервере и его скорости.
Читайте также: