https://wiki.archlinux.org/api.php?action=feedcontributions&user=Whgirw&feedformat=atom
ArchWiki - User contributions [en]
2024-03-29T09:34:31Z
User contributions
MediaWiki 1.41.0
https://wiki.archlinux.org/index.php?title=Tor_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=235535
Tor (Русский)
2012-11-15T13:58:58Z
<p>Whgirw: /* Privoxy */</p>
<hr />
<div>[[en:Tor]]<br />
[[es:Tor]]<br />
[[zh-CN:Tor]]<br />
{{Article summary start}}<br />
{{Article summary text|В этой статье будет рассказано, как установить и настроить всё необходимое для анонимной луковой маршрутизации (Tor)}}<br />
{{Article summary heading|Используемые приложения}}<br />
{{Article summary link|Tor|https://www.torproject.org/download/download.html}}<br />
{{Article summary link|Privoxy|http://www.privoxy.org/}}<br />
{{Article summary link|Polipo|http://www.pps.jussieu.fr/~jch/software/polipo/}}<br />
{{Article summary heading|См. также}}<br />
{{Article summary wiki|Privoxy}}<br />
{{Article summary wiki|Polipo}}<br />
{{Article summary end}}<br />
<br />
<br />
'''Tor''' - открытая реализация анонимной сети луковой маршрутизации 2-го поколения[https://ru.wikipedia.org/wiki/Tor]. Он, вместе с прокси-сервером Privoxy, может пригодится тем, кто хочет сохранить анонимность в интернете, а также защитить трафик от третьей стороны (провайдера и других любопытных). Также, использование подобного программного обеспечения актуально для стран в которых есть [https://ru.wikipedia.org/wiki/Интернет-цензура интернет-церзура].<br />
<br />
Подробнее о луковой маршрутизации и принципах её работы можно прочитать [https://ru.wikipedia.org/wiki/Луковая_маршрутизация в Википедии].<br />
<br />
== Принцип работы ==<br />
Пользователи сети Tor запускают прокси на своей машине. Это приложение соединяется с сетью и формирует цепочку из трех серверов, которая периодически меняется. Передаваемые данные шифруются несколько раз на вашем компьютере и передаются на цепь серверов, каждый из которых последовательно снимает свой "луковый" слой шифрования. На последнем сервере ваша инфорамция приобретает первоначальный вид. Большое количество промежуточных узлов значительно замедляет скорость работы сети.<br />
<br />
Tor предоставляет SOCKS интерфейс, через который могут направлять трафик совместимые приложения. Происходит т.н. "торификация" соединения.<br />
<br />
{{Warning|Учтите, что недобросовестные владельцы конечных серверов (нод в цепочке) могут перехватывать ваш трафик, так что озаботьесь дополнительным шифрованием, для предотвращения перехвата личной информации и паролей.}}<br />
{{Warning|Tor сам по себе не обеспечивает анонимности: он не дает определить ''откуда'' произошла передача данных, но все ещё остается возможность идентификации личности по их содержимому (см. [https://www.torproject.org/download/download.html.en#warning Want Tor to really work?]).}}<br />
Кроме описанных, есть и другие ограничения. Будет лучше, если вы ознакомитесь с ними на сайте проекта '''до''' использования.<br />
<br />
== Установка и настройка ==<br />
<br />
Установим Tor. Его пакет расположен в {{Ic|[community]}}.<br />
# pacman -S tor<br />
<br />
Для лучшего понимания работы просмотрите конфигурационный файл {{ic|/etc/tor/torrc}}. Опции подробно расписаны в {{Ic|man tor}} и на [https://www.torproject.org/docs/tor-manual.html.en сайте проекта].<br />
<br />
Конфигурационный файл по умолчанию подойдет для большинства пользователей. Вы также можете использовать для настройки и управление графический клиент Vidalia - это Qt GUI для Tor ([https://aur.archlinux.org/packages.php?ID=9731 пакет Vidalia] в [[AUR (Русский)|AUR]]).<br />
<br />
Кроме конфигурирования и контроля над процессом работы вы также получаете возможность видеть статус сети Tor, монитор трафика, просматривать фильтровать и искать логи.<br />
<br />
Установить значение дескриптора ulimits можно изменив переменную {{Ic|TOR_MAX_FD}} в конфигурационном файле {{ic|/etc/conf.d/tor}}.<br />
<br />
== Логгирование ==<br />
По умолчанию Tor выводит логи в "stdout" в качестве уведомлений. Вы можете включить запись логов в файле{{ic|torrc}} и в этом случае они будут писаться в {{ic|/usr/local/var/log/tor/}}.<br />
<br />
== Использование ==<br />
<br />
<br />
'''SysV'''<br />
<br />
Запустите Tor как демон:<br />
# /etc/rc.d/tor start<br />
<br />
Чтобы добавить Tor в автозагрузку, допишите {{ic|tor}} в секцию {{Ic|DAEMONS}} в вашем файле {{ic|/etc/rc.conf}}:<br />
DAEMONS=(... '''tor''' ...)<br />
<br />
'''systemd'''<br />
systemctl start tor.service<br />
(''systemctl enable tor.service'' для запуска Tor во время загрузки системы)<br />
<br />
<br />
Чтобы проверить, работает ли Tor, посетите страницу [https://check.torproject.org/ Tor], [http://serifos.eecs.harvard.edu/cgi-bin/ipaddr.pl?tor=1 Harvard] или [https://torcheck.xenobite.eu/ Xenobite.eu].<br />
<br />
== Веб-сёрфинг ==<br />
{{Note|В связи со сложностями обеспечения анонимности (cookies, javascripts, etc), проект Torprogect рекомендует использовать свою версию Firefox для анонимного серфинга. Мы вас предупреждали. [http://www.opennet.ru/opennews/art.shtml?num&#61;30449]}}<br />
<br />
[[Firefox]] и [[Chromium]] позволяют без проблем направлять трафик через Tor.<br />
<br />
=== Firefox ===<br />
<br />
Вы можете просто добавить Tor в качестве SOCKS прокси ("localhost", порт "9050"), открыв браузер и перейдя в '''Настройки''' > '''Дополнительные''' > '''Вкладка "Сеть"''' > '''Настроить'''.<br />
Чтобы перенаправить все DNS-запросы Firefox через прокси (иначе они пойдут не через Tor и будут доступны, например, провайдеру), откройте новую вкладку и введите {{ic|about:config}}. Измените переменную ''network.proxy.socks_remote_dns'' на ''yes''.<br />
<br />
Можно также использовать дополнения, позволяющие переключаться между множественными прокси (например, вы можете использовать Tor в связке с "ssh -D").<br />
В качестве примера можно привести "[https://addons.mozilla.org/en-us/firefox/addon/foxyproxy-standard/ FoxyProxy]".<br />
<br />
Также можно установить дополнение [https://www.torproject.org/torbutton/ TorButton], выполняющий и другие функции, который, однако, более не подерживается.<br />
<br />
=== Chromium ===<br />
Просто запустите:<br />
$ chromium --proxy-server="socks://localhost:9050"<br />
<br />
== Tor и HTTP прокси ==<br />
Если вам требуется какой-либо HTTP-прокси.<br />
<br />
{{note|На данный момент командой разработчиков Tor рекомендуется прокси-сервер Polipo.}}<br />
<br />
=== Polipo ===<br />
Polipo это маленький и быстрый HTTP-прокси. Установите и настройте его в соответствии со статьёй [[Polipo]]. Также вы можете воспользоваться [https://gitweb.torproject.org/torbrowser.git/blob_plain/HEAD:/build-scripts/config/polipo.conf готовой конфигурацией] опубликованной на сайте Torprogect.<br />
<br />
Обратите внимание, что polipo не требуется если вы хотите использовать прокси SOCKS 5, который доступен на порту 9050 после запуска Tor. Если вы хотите использовать Chromium через сеть Tor вам не требуется пакет polipo. Об использовании см. выше.<br />
<br />
=== Privoxy ===<br />
Privoxy - это HTTP-прокси, который использует SOCKS4a и может фильтровать html/cookie. Установить и настроить его поможет статья [[Privoxy]].<br />
<br />
Добавьте <br />
forward-socks4a / localhost:9050 . # Не забудте точку в конце<br />
в файл /etc/privoxy/config. Убедитесь,<br />
chown privoxy:privoxy /etc/privoxy/config<br />
что на него выставлены нужные права.<br />
<br />
Выполните следующие команды:<br />
mkdir /var/log/privoxy<br />
touch /var/log/privoxy/errorfile<br />
touch /var/log/privoxy/logfile<br />
chown -R privoxy:adm /var/log/privoxy<br />
<br />
Удостоверьтесь, что имя компьютера, записаное в /etc/rc.conf (параметр HOSTNAME) совпадает с именем, записанным в /etc/hosts.<br />
<br />
Запустите демоны tor и privoxy<br />
/etc/rc.d/tor start<br />
/etc/rc.d/privoxy start<br />
<br />
Также, их можно добавить в автозапуск в файл /etc/rc.conf<br />
DAEMONS=(syslog-ng ... privoxy tor)<br />
<br />
==== Tor и Privoxy в Firefox ====<br />
Настройте прокси в Firefox:<br />
<br />
Hostname: 127.0.0.1 Port: 8118<br />
<br />
Можно также добавить необходимые исключения.<br />
<br />
==== Tor и Privoxy в других приложениях ====<br />
Вы можете использовать Privoxy для интернет-пейджеров (Jabber, IRC) и прочих приложений. Просто укажите IP-адрес и номер порта (127.0.0.1 port 8118).<br />
<br />
Чтобы использовать SOCKS прокси напрямую вы можете указать приложению на Tor непосредственно (127.0.0.1 port 9050). Недостатоком методя является возможность самостоятельной посылки DNS-запросов приложением в обход Tor. Рассмотрите возможность использования SOCKS4A (например, через Privoxy) вместо нее.<br />
<br />
== Запуск сервера Tor ==<br />
=== Настройка ===<br />
Вы должны иметь скорость доступа в интернет не менее 20кб/с:<br />
Nickname <tornickname><br />
ORPort 9001<br />
BandwidthRate 20 KB # Замедлить трафик до 20кб/с<br />
BandwidthBurst 50 KB # Но позволить всплески до 50кб/с<br />
<br />
Allow irc ports 6660-6667 to exit from node:<br />
ExitPolicy accept *:6660-6667,reject *:* # Разрешить IRC порты, но не более<br />
<br />
Run Tor as an exit node:<br />
ExitPolicy accept *:119 # Принимать nntp тажке как и политики выходных нод по умолчанию<br />
<br />
Run Tor as middleman ( a relay):<br />
ExitPolicy reject *:*<br />
<br />
==TorDNS==<br />
Tor версий 0.2.x имеет встроенный механизм перенаправления DNS-запросов. Чтобы включить его, добавьте следующую строку в конфигурационный файл:<br />
{{hc|/etc/tor/torrc|<br />
DNSPort 9053<br />
AutomapHostsOnResolve 1<br />
AutomapHostsSuffixes .exit,.onion<br />
}}<br />
И перезапустите Tor, чтобы он подхватил новые настройки:<br />
/etc/rc.d/tor restart<br />
<br />
Это позволит Tor принимать запросы (например слушать 9053 порт в этом примере) как обычному DNS-серверу, и разрешать домены по сети Tor. Недостатком является то, что становится возможным разрешать только A-записи; MX и NS запросы будут проигнорированы. См. [https://techstdout.boum.org/TorDns/ документацию для Debian].<br />
<br />
DNS запросы могут быть осуществлены средствами коммандного интерпретатора, используя {{Ic|<nowiki>tor-resolve</nowiki>}}. For example:<br />
{{bc|<br />
$ tor-resolve archlinux.org<br />
66.211.214.131<br />
}}<br />
<br />
== "Торификация" ==<br />
<br />
"Торификация" (torify) позволяет использовать приложение через сеть Tor без каких либо дополнительных настроек в самом приложении. Выдержка из man page:<br />
{{bc|<br />
torify - это простая оболочка, вызывающая tsocks с конфигурационным файлом<br />
<br />
tsocks представляет собой оболочку между библиотекой tsocks и приложением, которое вы хотите соксифицировать<br />
}}<br />
Пример использования:<br />
{{bc|<nowiki><br />
$ torify elinks checkip.dyndns.org<br />
$ torify wget -qO- https://check.torproject.org/ | grep -i congratulations<br />
</nowiki>}}<br />
<br />
Учтите, что torify не будет выполнять поиск DNS через Tordns. Для этого придётся использовать его в сочетании с {{Ic|<nowiki>tor-resolve</nowiki>}} (описано выше). В этом случае процедура для первого из приведенных примеров будет выглядеть следующим образом:<br />
<br />
{{bc|<br />
$ tor-resolve checkip.dyndns.org<br />
208.78.69.70<br />
$ torify elinks 208.78.69.70<br />
}}<br />
<br />
== Решение проблем ==<br />
<br />
=== Проблема с пользовательским значением ===<br />
<br />
Если демон tor не запускается, выполните слудующую комманду от root:<br />
<br />
# tor<br />
<br />
Если вы получили следующую ошибку:<br />
<br />
May 23 00:27:24.624 [warn] Error setting groups to gid 43: "Operation not permitted".<br />
May 23 00:27:24.624 [warn] If you set the "User" option, you must start Tor as root.<br />
May 23 00:27:24.624 [warn] Failed to parse/validate config: Problem with User value. See logs for details.<br />
May 23 00:27:24.624 [err] Reading config failed--see warnings above.<br />
<br />
Она означает проблемы с пользовательскими значениями. Приступим к решению проблемы.<br />
<br />
Узнайте права доступа к папке {{ic|/var/lib/tor}}:<br />
<br />
# ls -l /var/lib/<br />
<br />
Если права {{ic|/var/lib/tor}} такие же как указанные ниже, то это значит, что директория является собственностью пользователя ''tor'' группы ''tor''.<br />
<br />
drwx------ 2 tor tor 4096 May 12 21:03 tor<br />
<br />
Измените владельца и группу:<br />
<br />
# chown -R root:root /var/lib/tor<br />
<br />
Теперь права доступы должны быть такими:<br />
<br />
drwx------ 2 root root 4096 May 12 21:03 tor<br />
<br />
Теперь откройте {{ic|/etc/tor/torrc}} и найдите следующие строки:<br />
<br />
## Uncomment this to start the process in the background... or use<br />
## --runasdaemon 1 on the command line.<br />
RunAsDaemon 1<br />
User tor<br />
Group tor<br />
<br />
Закомментируйте строки ''User tor'' и ''Group tor'':<br />
<br />
## Uncomment this to start the process in the background... or use<br />
## --runasdaemon 1 on the command line.<br />
RunAsDaemon 1<br />
#User tor<br />
#Group tor<br />
<br />
Сохраните и перезапустите демон '''tor'''. Теперь всё должно работать.<br />
<br />
# /etc/rc.d/tor restart<br />
<br />
== Внешние ссылки ==<br />
* [https://www.torproject.org/ Official Website]<br />
* [https://trac.torproject.org/projects/tor/wiki#Unixish Unix-based Tor Articles]<br />
* [https://trac.torproject.org/projects/tor/wiki/doc/SupportPrograms Software commonly integrated with Tor]<br />
* [https://www.torproject.org/docs/tor-hidden-service.html.en How to set up a Tor ''Hidden Service'']<br />
<br />
----<br />
<br />
----<br />
<br />
<br />
<br />
[[Category:Русский]]<br />
[[Category:Security (Русский)]]<br />
[[Category:Proxy servers (Русский)]]</div>
Whgirw
https://wiki.archlinux.org/index.php?title=QEMU&diff=217044
QEMU
2012-08-08T11:02:26Z
<p>Whgirw: /* Overlay images */</p>
<hr />
<div>[[Category:Emulators]]<br />
[[Category:Virtualization]]<br />
[[de:Qemu]]<br />
[[fr:Qemu]]<br />
[[zh-CN:QEMU]]<br />
<br />
{{Out of date|[https://www.archlinux.org/news/deprecation-of-net-tools net-tools] is deprecated. [[QEMU#Networking|Networking]] section needs updating. |QEMU#Networking}}<br />
<br />
From the [http://wiki.qemu.org/Main_Page QEMU about page],<br />
<blockquote><br />
<p>QEMU is a generic and open source machine emulator and virtualizer.</p><br />
<br />
<p>When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your own PC). By using dynamic translation, it achieves very good performance.</p><br />
<br />
<p>When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU. QEMU supports virtualization when executing under the Xen hypervisor or using the KVM kernel module in Linux. When using KVM, QEMU can virtualize x86, server and embedded PowerPC, and S390 guests.</p><br />
</blockquote><br />
<br />
== Installing QEMU ==<br />
<br />
Depending on your needs, you can choose to install either {{Pkg|qemu}} or {{Pkg|qemu-kvm}} from the [[Official Repositories|official repositories]]. {{Pkg|qemu}} includes support for emulating a wide variety of machine architectures, while {{Pkg|qemu-kvm}} only supports virtualizing your host architecture using [[KVM]]. It is strongly recommended to use KVM whenever possible; see [[#Using the Kernel-based Virtual Machine]] for more information. In the current version of QEMU (>= 0.15.0), you can still use KVM with the {{Pkg|qemu}} package, if supported by your processor and kernel, provided that you start QEMU with the {{ic|-enable-kvm}} argument; this was not the case for older versions of QEMU (< 0.15.0), when not all KVM-related functions had been merged into upstream QEMU.<br />
<br />
=== Build Your QEMU With Spice support ===<br />
<br />
The official package is built without spice support. You can build your version with spice enabled. You must have installed the [[Arch Build System]] on your system.<br />
<br />
You must install {{aur|spice}} from the [[Arch User Repository|AUR]] first.<br />
<br />
Then update ABS on your system to the latest version and copy {{ic|/var/abs/extra/qemu}} (for QEMU users) or {{ic|/var/abs/extra/qemu-kvm}} (for QEMU-KVM users) to somewhere (here we use {{ic|~/temp/}} as an example) you like:<br />
$ sudo abs<br />
$ cp -r /var/abs/extra/qemu ~/temp<br />
<br />
Go to your copy of the package folder (here {{ic|~/temp/qemu}} or {{ic|~/temp/qemu-kvm}}) and add {{ic|--enable-spice}} after {{ic|.configure}} in the build() function of the [[PKGBUILD]]:<br />
$ cd ~/temp/qemu<br />
$ sed -i "s/\.\/configure/& --enable-spice/g" <br />
<br />
Then build and install the package:<br />
$ makepkg -i<br />
<br />
== Creating a hard disk image==<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk. <br />
<br />
A hard disk image may simply contain the literal contents, byte for byte, of the hard disk. This is usually called ''raw'' format, and it provides the least I/O overhead, although the images may take up a large amount of space.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' that can save enormous amounts of space by only allocating space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. The following command creates a 4GB image named {{ic|myimage.qcow2}} in the qcow2 format:<br />
$ qemu-img create -f qcow2 myimage.qcow2 4G<br />
<br />
You may use {{ic|-f raw}} to create a raw disk instead, although you can also do so simply by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.<br />
<br />
== Preparing the installation media ==<br />
<br />
To install an operating system into your disk image, you need the installation media (e.g. CD-ROM, floppy, or ISO image) for the operating system.<br />
<br />
{{Tip|If you would like to run an Arch Linux virtual machine, you can install it using the [http://archlinux.org/download/ official installation media for Arch Linux]. It is also possible to set up an Arch Linux virtual machine without the installation media, provided that your host machine is running Arch Linux, although this is more difficult; it is detailed [[Creating Arch Linux disk image#Install Arch Linux in a disk image without the installation media|here]].}}<br />
<br />
The installation media should not be mounted because QEMU accesses the media directly. Also, if using physical media (e.g. CD-ROM or floppy), it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command:<br />
# dd if=/dev/cdrom of=mycdimg.iso<br />
<br />
Do the same for floppies:<br />
# dd if=/dev/fd of=myfloppy.img<br />
<br />
== Installing the operating system==<br />
<br />
To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
This is the first time you will need to start the emulator. By default, QEMU will show the virtual machine's video output in a window. <br />
One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it press {{Keypress|Ctrl+Alt}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
If you need to use a bootable floppy, run QEMU with:<br />
$ qemu -cdrom <nowiki>[[cdrom_image]]</nowiki> -fda <nowiki>[[floppy_image]]</nowiki> -boot a <nowiki>[[hd_image]]</nowiki><br />
<br />
or if you are on a x86_64 system (will avoid many problems afterwards):<br />
$ qemu-system-x86_64 -cdrom <nowiki>[[cdrom_image]]</nowiki> -fda <nowiki>[[floppy_image]]</nowiki> -boot a <nowiki>[[hd_image]]</nowiki><br />
<br />
If your CD-ROM is bootable or you are using ISO files, run QEMU with:<br />
$ qemu -cdrom <nowiki>[[cdrom_image]]</nowiki> -boot d <nowiki>[[hd_image]]</nowiki><br />
<br />
or if you are on a x86_64 system (will avoid many problems afterwards):<br />
$ qemu-system-x86_64 -cdrom <nowiki>[[cdrom_image]]</nowiki> -boot d <nowiki>[[hd_image]]</nowiki><br />
<br />
Now, using the installer for the OS, partition the virtual hard disk, format the partitions, and install the OS.<br />
<br />
{{Note|See [[#Windows-specific notes]] if you are installing Windows in your virtual machine.}}<br />
<br />
{{Note|If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{Keypress|Ctrl-Alt-2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{Keypress|Ctrl-Alt-1}} to go back to the virtual machine.}}<br />
<br />
== Running the installed system==<br />
<br />
After the operating system has finished installing, you can boot the disk image by itself, without the installation media.<br />
<br />
To run the system simply use a command like:<br />
$ qemu [hd_image]<br />
<br />
{{Note|If possible, you should consider [[#Using the Kernel-based Virtual Machine|using KVM]] for improved performance.}}<br />
<br />
== Using the Kernel-based Virtual Machine ==<br />
<br />
[[KVM]] is a full virtualization solution for Linux on x86 hardware containing virtualization extensions (Intel VT or AMD-V). It consists of a loadable kernel module, kvm.ko, that provides the core virtualization infrastructure and a processor specific module, kvm-intel.ko or kvm-amd.ko. Using KVM, one can run multiple virtual machines running unmodified Linux or Windows images. Each virtual machine has private virtualized hardware: a network card, disk, graphics adapter, etc.<br />
<br />
{{Tip|It is recommended to use KVM whenever possible because it will greatly improve the performance of the running virtual machine compared to QEMU emulating the virtual machine entirely in software.}}<br />
<br />
KVM requires an x86 machine running a recent ( >= 2.6.22) Linux kernel on an Intel processor with VT-x (Virtualization Technology) extensions, or an AMD processor with SVM (Secure Virtual Machine) extensions—''AMD-V'' is the marketing term for AMD's SVM. It is included in the mainline Linux kernel since 2.6.20 and is enabled by default in the Arch Linux kernel.<br />
<br />
{{Pkg|qemu}} ><nowiki>=</nowiki> 0.15.0 has full support for KVM, as the {{Pkg|qemu-kvm}} tree has been completely merged into the upstream QEMU tree. Therefore, there should be no difference between {{ic|qemu -enable-kvm}} and {{ic|qemu-kvm}} if your version of {{Pkg|qemu}} is ><nowiki>=</nowiki> 0.15.0.<br />
<br />
{{Note|QEMU in older versions ( < 0.15.0) does have initial KVM support ({{ic|qemu -enable-kvm}}), but it is not recommended to use this, as many KVM-related functions had not been implemented in upstream QEMU. Instead, for older versions of QEMU you should go for the {{Pkg|qemu-kvm}} package in the [[Official Repositories|official repositories]], which is released by the KVM development team and contains all of the latest features (and bug-fixes) of KVM userspace. Please refer to the [[KVM]] page itself, for more information on using QEMU with KVM on Arch Linux.}}<br />
<br />
To take advantage of KVM, you need a compatible processor (the following command must return something on the screen):<br />
$ grep -E "(vmx|svm)" --color=always /proc/cpuinfo<br />
<br />
And load the appropriate module from your {{ic|/etc/[[rc.conf]]}}.<br />
<br />
* For Intel® processors, add {{ic|kvm-intel}} to your {{ic|MODULES}} array in {{ic|/etc/rc.conf}}<br />
* for AMD® processors, add {{ic|kvm-amd}} to your {{ic|MODULES}} array in {{ic|/etc/rc.conf}}<br />
<br />
Also, you will need to add yourself to the group {{ic|kvm}}.<br />
# gpasswd -a <Your_User_Account> kvm<br />
<br />
== Overlay images ==<br />
<br />
A good idea is to use overlay images. This way you can a create hard disk image once and tell QEMU to store changes in an external file.<br />
This makes it easy to revert the virtual machine's disk to a previous state.<br />
<br />
To create an overlay image, type:<br />
$<nowiki> qemu-img create -b [[base_image]] -f qcow2 [[overlay_image]]</nowiki><br />
<br />
After that you can run qemu with:<br />
$ qemu [overlay_image]<br />
<br />
or if you are on a x86_64 system:<br />
$ qemu-system-x86_64 [overlay_image]<br />
<br />
and the original image will be left untouched. One hitch, the base image cannot be renamed or moved, the overlay remembers the base's full path.<br />
<br />
== Moving data between host and guest OS ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[Samba|SMB]], NBD, HTTP, [[Very Secure FTP Daemon|FTP]], or [[Secure Shell|SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[Samba|SMB]] or [[NFS]], or you can access the host's HTTP server, etc. <br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
{{Note|QEMU's "built-in" SMB server is currently (as of qemu-1.0.1-1) broken because it does not specify the {{ic|state_directory}} option in the {{ic|smb.conf}} file it writes. This issue is fixed in upstream QEMU.}}<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] with an automatically generated configuration file and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and this isn't necessarily very useful since the guest can also access the normal [[Samba]] service on the host if you have set up shares on it.<br />
<br />
To enable this feature, start QEMU with a command like:<br />
$ qemu [hd_image] -net nic -net user,smb=/path/to/shared/dir<br />
<br />
where {{ic|/path/to/shared/dir}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
=== Mounting a partition inside a raw disk image ===<br />
<br />
When the virtual machine is not running, it is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices. This does not work with disk images in special formats, such as qcow2, although those can be mounted using {{ic|qemu-nbd}}.<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise data corruption could occur, unless you had mounted the partitions read-only.}}<br />
<br />
==== With manually specifying byte offset ====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
# mount -o loop,offset=32256 [hd_image] [tmp_dir]<br />
<br />
The {{ic|<nowiki>offset=32256</nowiki>}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l [hd_image]}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}.<br />
<br />
==== With loop module autodetecting partitions ====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* Unload the loop [[Kernel modules|module]].<br />
# modprobe -r loop<br />
* Load the loop [[Kernel modules|module]] with the {{ic|max_part}} parameter set.<br />
# modprobe loop max_part=15<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|<nowiki>max_part=15</nowiki>}} every time, or you can put {{ic|<nowiki>loop.max_part=15</nowiki>}} on the kernel command line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
# losetup -f [os_image]<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
# mount /dev/loop0p1 [tmp_dir]<br />
<br />
==== With kpartx ====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
# kpartx -a /dev/loop0<br />
<br />
=== Mounting qcow2 image ===<br />
You may mount a qcow2 image using {{ic|qemu-nbd}}. See [[http://en.wikibooks.org/wiki/QEMU/Images#Mounting_an_image_on_the_host Wikibooks]].<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the filesystem layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you need to change the owner of the partition's device file to that user.<br />
<br />
{{Warning|Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.}}<br />
<br />
{{Warning|You must not mount a filesystem on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a filesystem and not as a partitioned device with a MBR (FIXME: Isn't that actually possible, since filesystems don't begin on the first sector?). Such a virtual machine can be booted either by specifying the [[Kernels|kernel]] and [[initramfs|initrd]] manually, or by simulating a disk with a MBR by using linear [[RAID]].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root filesystem as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
$ qemu -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root filesystem is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
==== Simulate virtual disk with MBR using linear RAID ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a filesystem and not just having the guest partition the partition as if it were a disk, is to simulate a MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
You can do this using software [[RAID]] in linear mode (you need the linear.ko kernel driver) and a loopback device: the trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image.<br />
<br />
Suppose you have a plain, unmounted {{ic|/dev/hdaN}} partition with some filesystem on it you wish to make part of a QEMU disk image. First, you create some small file to hold the MBR:<br />
$ dd if=/dev/zero of=/path/to/mbr count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
# losetup -f /path/to/mbr<br />
<br />
Let's assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hdaN}} disk image using software RAID:<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hdaN<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hdaN}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
# fdisk /dev/md0<br />
<br />
Press {{Keypress|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{Keypress|R}} to return to the main menu. <br />
<br />
Press {{Keypress|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hdaN}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You know have a partition you can mount directly from your host, as well as part of a QEMU disk image: <br />
<br />
$ qemu -hdc /dev/md0 [...]<br />
<br />
You can of course safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hdaN}} partition contains the necessary tools.<br />
<br />
==Networking==<br />
===User-mode networking===<br />
<br />
By default, without any {{ic|-net}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU. This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. <br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, or attaching guests to virtual LANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
=== Tap networking with QEMU ===<br />
==== Basic idea ====<br />
<br />
[http://en.wikipedia.org/wiki/TUN/TAP Tap devices] are a Linux kernel feature that allows you to create virtual "tap" network interfaces that appear as real network interfaces. Packets sent to a "tap" interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as eth0. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
==== Bridge virtual machines to external network ====<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as eth0, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
{{Warning|Beware that since your virtual machines will appear directly on the external network, this may expose them to attack. Depending on what resources your virtual machines have access to, you may need to take all the precautions you normally would take in securing a computer to secure your virtual machines.}}<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it. See http://en.gentoo-wiki.com/wiki/KVM#Networking_2 .<br />
<br />
1. Make sure that the following packages are installed:<br />
*{{Pkg|bridge-utils}} (provides {{ic|brctl}}, to manipulate bridges)<br />
*{{Pkg|uml_utilities}} (provides {{ic|tunctl}}, to manipulate taps)<br />
<br />
2. Enable IPv4 forwarding by changing {{ic|<nowiki>net.ipv4.ip_forward = 0</nowiki>}} to {{ic|<nowiki>net.ipv4.ip_forward = 1</nowiki>}} in {{ic|<nowiki>/etc/sysctl.conf</nowiki>}}.<br />
<br />
3. Add {{ic|bridge}} and {{ic|tun}} to your {{ic|MODULES}} array in {{ic|/etc/rc.conf}}:<br />
<br />
MODULES=( ... bridge tun)<br />
<br />
4. Configure your bridge {{ic|br0}} to have your real Ethernet adapter (assuming {{ic|eth0}} for the rest of this guide) in it, in {{ic|/etc/conf.d/bridges}}:<br />
bridge_br0="eth0"<br />
control_br0="setfd br0 0"<br />
BRIDGE_INTERFACES=(br0)<br />
<br />
{{Note|This is not described anywhere, but adding the {{ic|control_br0}} line is vital for the bridge to work! For more details look here: {{bug|16625}}}}<br />
<br />
5. Change your networking configuration so that you just bring up your real Ethernet adapter without configuring it, allowing real configuration to happen on the bridge interface. In {{ic|/etc/rc.conf}}:<br />
eth0="eth0 up"<br />
br0="dhcp"<br />
INTERFACES=(eth0 br0)<br />
<br />
Remember, especially if you are doing DHCP, it is essential that the bridge comes up AFTER the real adapter, otherwise the bridge will not be able to talk to anything to get a DHCP address!<br />
<br />
If you have been giving eth0 a static IP address rather than using DHCP, give br0 similar settings:<br />
<br />
{{ic|/etc/rc.conf}}:<br />
eth0="eth0 0.0.0.0"<br />
br0="br0 192.168.0.3 netmask 255.255.255.0 broadcast 192.168.0.255"<br />
INTERFACES=(eth0 br0)<br />
gateway="default gw 192.168.0.1"<br />
ROUTES=(gateway)<br />
<br />
and then in {{ic|/etc/resolv.conf}}:<br />
domain lan<br />
nameserver 192.168.0.1<br />
<br />
6. Install the script that QEMU uses to bring up the tap adapter in {{ic|/etc/qemu-ifup}} with root:kvm 750 permissions:<br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /sbin/ifconfig $1 0.0.0.0 promisc up<br />
echo "Adding $1 to br0..."<br />
sudo /usr/sbin/brctl addif br0 $1<br />
sleep 2<br />
<br />
7. Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
Cmnd_Alias QEMU=/sbin/ifconfig,/sbin/modprobe,/usr/sbin/brctl,/usr/bin/tunctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
<br />
8. Make sure the user(s) wishing to use this new functionality are in the {{ic|kvm}} group. Exit and log in again if necessary.<br />
<br />
9. You launch QEMU using the following {{ic|run-qemu}} script:<br />
#!/bin/bash<br />
USERID=`whoami`<br />
IFACE=$(sudo tunctl -b -u $USERID)<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" \<br />
$(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) \<br />
$(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
<br />
qemu-kvm -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo tunctl -d $IFACE &> /dev/null<br />
<br />
Then to launch a VM, do something like this<br />
$ run-qemu -hda myvm.img -m 512 -vga std<br />
<br />
10. If you cannot get a DHCP address in the host, it might be because [[Iptables|iptables]] are up by default in the bridge. In that case (from http://www.linux-kvm.org/page/Networking ):<br />
# cd /proc/sys/net/bridge<br />
# ls<br />
bridge-nf-call-arptables bridge-nf-call-iptables<br />
bridge-nf-call-ip6tables bridge-nf-filter-vlan-tagged<br />
# for f in bridge-nf-*; do echo 0 > $f; done<br />
<br />
And if you still cannot get networking to work, see: [[Linux_Containers#Bridge_device_setup]]<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no "real" interface (e.g. eth0) is also connected to the bridge, then the virtual machines will be able to talk to each other and the physical host. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called "host-only" networking by other virtualization software such as [[VirtualBox]].<br />
<br />
You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the 172.20.0.1/16 subnet with [[Dnsmasq]] as the DHCP server:<br />
<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[Iptables|iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called "internal" networking by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
==== Link-level address caveat ====<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address 52:54:00:12:34:56. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
To solve this problem, the last 8 digits of the link-level address of the virtual NICs should be randomized, as in the script above, to make sure that each virtual machine has a unique link-level address.<br />
<br />
=== Networking with [[VDE2]] ===<br />
==== What is VDE? ====<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration I show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. Your are invited to read [http://wiki.virtualsquare.org/wiki/index.php/Main_Page the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
VDE is in the [[Official Repositories|official repositories]], so...<br />
<br />
# pacman -S vde2<br />
<br />
In my config, I use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (or add it to your {{ic|MODULES}} array in {{ic|[[rc.conf]]}}):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group kvm<br />
<br />
This line creates the switch, creates tap0, "plugs" it, and allows the users of the group {{ic|kvm}} to use it.<br />
<br />
The interface is plugged in but not configured yet. Just do it:<br />
<br />
# ifconfig tap0 192.168.100.254 netmask 255.255.255.0<br />
<br />
That is all! Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-kvm -net nic -net vde -hda ...<br />
<br />
Configure your guest as you would do in a physical network. I gave them static addresses and let them access the WAN using IP forwarding and masquerading on my host:<br />
<br />
# echo "1" > /proc/sys/net/ipv4/ip_forward<br />
# iptables -t nat -A POSTROUTING -s 192.168.100.0/24 -o eth0 -j MASQUERADE<br />
<br />
==== Putting it together ====<br />
I added this init script to run all this at start-up:<br />
<br />
#!/bin/bash <br />
<br />
. /etc/rc.conf<br />
. /etc/rc.d/functions<br />
case "$1" in<br />
start)<br />
stat_busy "Starting VDE Switch"<br />
vde_switch -tap tap0 -daemon -mod 660 -pidfile $PIDFILE -group kvm<br />
if [ $? -gt 0 ]; then<br />
stat_fail<br />
else<br />
echo "1" > /proc/sys/net/ipv4/ip_forward && \<br />
iptables -t nat -A POSTROUTING -s 192.168.100.0/24 -o eth0 -j MASQUERADE && \<br />
ifconfig tap0 192.168.100.254 netmask 255.255.255.0 && \<br />
stat_done || stat_fail<br />
fi<br />
;;<br />
stop)<br />
stat_busy "Stopping VDE Switch"<br />
# err.. well, i should remove the switch here...<br />
stat_done<br />
;;<br />
restart)<br />
$0 stop<br />
sleep 1<br />
# Aem.. As long as stop) is not implemented, this just fails<br />
$0 start<br />
;;<br />
*)<br />
echo "usage: $0 {start|stop|restart}" <br />
esac<br />
exit 0<br />
<br />
Well, I know it is dirty and could be more configurable. Feel free to improve it. VDE has an rc script too, but I had to make one anyway for the IP forwarding stuff.<br />
<br />
====Alternative method====<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group kvm<br />
<br />
# slirpvde --dhcp --daemon<br />
<br />
Then to start the vm with a connection to the network of the host:<br />
<br />
$ kvm -net nic,macaddr=52:54:00:00:EE:03 -net vde whatever.qcow<br />
<br />
=== Improving networking performance ===<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde, since tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. To do this, add a {{ic|<nowiki>model=virtio</nowiki>}} flag to the {{ic|-net nic}} option:<br />
<br />
-net nic,model=virtio<br />
<br />
This will only work if the guest machine has a driver for virtio network devices. Linux does, and the required driver ('''virtio_net''') is included with Arch Linux, but there is no guarantee that virtio networking will work with arbitrary operating systems. There do exist [[#Virtio drivers for Windows|virtio drivers for Windows]], but you need to install them manually.<br />
<br />
== Graphics ==<br />
QEMU can use the following different graphic outputs: std, cirrus, vmware, qxl, xenfs and vnc.<br />
With the {{ic|vnc}} option you can run your guest standalone and connect to it via VNC. Other options are using {{ic|std}}, {{ic|vmware}}, {{ic|cirrus}}:<br />
<br />
===std===<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels.<br />
<br />
===vmware===<br />
Although it is a bit buggy, it performs better than std and cirrus. On the guest, install the VMware drivers. For Arch Linux guests:<br />
# pacman -S xf86-video-vmware xf86-input-vmmouse<br />
<br />
===none===<br />
<br />
If you do not want to see the graphical output from your virtual machine because you will be accessing it entirely through the network or serial port, you can run QEMU with the {{ic|-nographic}} option.<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization progrems such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s). However, there are several GUI front-ends for QEMU:<br />
<br />
* virt-manager (part of [[libvirt]])<br />
* {{Pkg|qemu-launcher}}<br />
* community/qemulator<br />
* {{Pkg|qtemu}}<br />
<br />
== Windows-specific notes ==<br />
=== Choosing a Windows version ===<br />
<br />
QEMU can run any version of Windows. However, 98, Me and XP will run at quite a low speed. You should choose either Windows 95 or Windows 2000. Surprisingly, 2000 seems to run faster than 98. The fastest one is 95, which can from time to time make you forget that you are running an emulator :)<br />
<br />
If you own both Win95 and Win98/WinME, then 98lite (from http://www.litepc.com) might be worth trying. It decouples Internet Explorer from operating system and replaces it with original Windows 95 Explorer. It also enables you to do a minimal Windows installation, without all the bloat you normally cannot disable. This might be the best option, because you get the smallest, fastest and most stable Windows this way.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
=== Windows 95 boot floppy ===<br />
<br />
If you are using the Windows 95 boot floppy, choosing SAMSUNG as the type of CD-ROM seems to work.<br />
<br />
=== Windows 2000 installation bug ===<br />
<br />
There are problems when installing Windows 2000. Windows setup will generate a lot of edb*.log files, one after the other containing nothing but blank spaces in {{ic|C:\WINNT\SECURITY}} which quickly fill the virtual hard disk. A workaround is to open a Windows command prompt as early as possible during setup (by pressing {{Keypress|Shift+F10}}) which will allow you to remove these log files as they appear by typing:<br />
del %windir%\security\*.log<br />
<br />
{{Note|According to the official QEMU website, "Windows 2000 has a bug which gives a disk full problem during its installation. When installing it, use the {{ic|-win2k-hack}} QEMU option to enable a specific workaround. After Windows 2000 is installed, you no longer need this option (this option slows down the IDE transfers)."}}<br />
<br />
=== Optimizing Windows 9X CPU usage ===<br />
<br />
Windows 9X uses an idle loop instead of the HLT (halt) instruction. Consequently, the emulator will consume all CPU resources when running Windows 9X guests -- even if no work is being done. This only applies to DOS and DOS-based Windows versions (3.X, 95/98/ME) -- NT-based and later Windows versions are not affected.<br />
<br />
To resolve this issue, install [http://www.benchtest.com/rain.html Rain], [http://www.benchtest.com/wfp.html Waterfall] or [http://www.benchtest.com/cpuidle.html CpuIdle] in the Windows 9X guest. (Rain might be preferred because it does only what is needed -- replacing the idle loop with the HLT instruction -- and nothing more.)<br />
<br />
See [https://forums.virtualbox.org/viewtopic.php?f=28&t=9918 Tutorial: Windows 95/98 guest OSes] for more information.<br />
<br />
===Remote Desktop Protocol===<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. Use: (if you are using a VLAN or are not in the same network as the guest)<br />
$ qemu -nographic -net user,hostfwd=tcp::5555-:3389<br />
Then connect with either rdesktop or freerdp to the guest, for example:<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Windows virtio drivers ===<br />
<br />
You can use [http://wiki.libvirt.org/page/Virtio virtio] devices with Windows if you install the [http://www.linux-kvm.org/page/WindowsGuestDrivers/Download_Drivers virtio guest drivers] for Windows.<br />
<br />
== General problems ==<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
{{bc|<br />
qemu -k [keymap] [disk_image]<br />
}}<br />
<br />
=== Virtual machine runs too slowly ===<br />
<br />
There are a number of techniques that you can use to improve the performance if your virtual machine. For example:<br />
<br />
* Use KVM if possible (see [[#Using the Kernel-based Virtual Machine]]).<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024MiB of memory.<br />
* If the host machine has multiple CPUs, assign the guest more CPUs using the {{ic|-smp}} option.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you don't do this, it may be trying to emulate a more generic CPU.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu -net nic,model=virtio -net tap,if=tap0,script=no -drive file=mydisk.raw,media=disk,if=virtio<br />
* [[#Tap networking with QEMU|Use TAP devices]] instead of user-mode networking.<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's filesystem. For example, you can mount an [[Ext4|ext4 filesystem]] with the option {{ic|<nowiki>barrier=0</nowiki>}}. You should read the documentation for any options that you change, since sometimes performance-enhancing options for filesystems come at the cost of data integrity.<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [http://en.wikipedia.org/wiki/Kernel_SamePage_Merging_(KSM) kernel same-page merging]:<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU with the {{ic|-balloon virtio}} option.<br />
<br />
==Starting QEMU virtual machines on boot==<br />
<br />
===With libvirt===<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured through the virt-manager GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
===Custom script===<br />
To run QEMU VMs on boot, you can use following rc-script and config.<br />
<br />
{| border="1"<br />
|+ Config file options<br />
|-<br />
| QEMU_MACHINES || List of VMs to start<br />
|-<br />
| qemu_${vm}_type || QEMU binary to call. If specified, will be prepended with {{ic|/usr/bin/qemu-}} and that binary will be used to start the VM. I.e. you can boot e.g. qemu-system-arm images with qemu_my_arm_vm_type="system-arm". If not specified, {{ic|/usr/bin/qemu}} will be used.<br />
|-<br />
| qemu_${vm} || QEMU command line to start with. Will always be prepended with {{ic|-name ${vm} -pidfile /var/run/qemu/${vm}.pid -daemonize -nographic}}.<br />
|-<br />
| qemu_${vm}_haltcmd || Command to shutdown VM safely. I am using {{ic|-monitor telnet:..}} and power off my VMs via ACPI by sending {{ic|system_powerdown}} to monitor. You can use ssh or some other ways.<br />
|-<br />
| qemu_${vm}_haltcmd_wait || How much time to wait for safe VM shutdown. Default is 30 seconds. rc-script will kill qemu process after this timeout.<br />
|}<br />
<br />
Config file example:<br />
{{hc|/etc/conf.d/qemu.conf|<nowiki><br />
# VMs that should be started on boot<br />
# use the ! prefix to disable starting/stopping a VM<br />
QEMU_MACHINES=(vm1 vm2)<br />
<br />
# NOTE: following options will be prepended to qemu_${vm}<br />
# -name ${vm} -pidfile /var/run/qemu/${vm}.pid -daemonize -nographic<br />
<br />
qemu_vm1_type="system-x86_64"<br />
<br />
qemu_vm1="-enable-kvm -m 512 -hda /dev/mapper/vg0-vm1 -net nic,macaddr=DE:AD:BE:EF:E0:00 \<br />
-net tap,ifname=tap0 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
qemu_vm1_haltcmd="echo 'system_powerdown' | nc.openbsd localhost 7100" # or netcat/ncat<br />
<br />
# You can use other ways to shutdown your VM correctly<br />
#qemu_vm1_haltcmd="ssh powermanager@vm1 sudo poweroff"<br />
<br />
# By default rc-script will wait 30 seconds before killing VM. Here you can change this timeout.<br />
#qemu_vm1_haltcmd_wait="30"<br />
<br />
qemu_vm2="-enable-kvm -m 512 -hda /srv/kvm/vm2.img -net nic,macaddr=DE:AD:BE:EF:E0:01 \<br />
-net tap,ifname=tap1 -serial telnet:localhost:7001,server,nowait,nodelay \<br />
-monitor telnet:localhost:7101,server,nowait,nodelay -vnc :1"<br />
<br />
qemu_vm2_haltcmd="echo 'system_powerdown' | nc.openbsd localhost 7101"<br />
</nowiki>}}<br />
<br />
rc-script:<br />
{{hc|/etc/rc.d/qemu|<nowiki><br />
#!/bin/bash<br />
. /etc/rc.conf<br />
. /etc/rc.d/functions<br />
<br />
[ -f /etc/conf.d/qemu.conf ] && source /etc/conf.d/qemu.conf<br />
<br />
PIDDIR=/var/run/qemu<br />
QEMU_DEFAULT_FLAGS='-name ${vm} -pidfile ${PIDDIR}/${vm}.pid -daemonize -nographic'<br />
QEMU_HALTCMD_WAIT=30<br />
<br />
case "$1" in<br />
start)<br />
[ -d "${PIDDIR}" ] || mkdir -p "${PIDDIR}"<br />
for vm in "${QEMU_MACHINES[@]}"; do<br />
if [ "${vm}" = "${vm#!}" ]; then<br />
stat_busy "Starting QEMU VM: ${vm}"<br />
eval vm_cmdline="\$qemu_${vm}"<br />
eval vm_type="\$qemu_${vm}_type"<br />
<br />
if [ -n "${vm_type}" ]; then<br />
vm_cmd="/usr/bin/qemu-${vm_type}"<br />
else<br />
vm_cmd='/usr/bin/qemu'<br />
fi<br />
<br />
eval "qemu_flags=\"${QEMU_DEFAULT_FLAGS}\""<br />
<br />
${vm_cmd} ${qemu_flags} ${vm_cmdline} >/dev/null<br />
if [ $? -gt 0 ]; then<br />
stat_fail<br />
else<br />
stat_done<br />
fi<br />
fi<br />
done<br />
add_daemon qemu<br />
;;<br />
<br />
stop)<br />
for vm in "${QEMU_MACHINES[@]}"; do<br />
if [ "${vm}" = "${vm#!}" ]; then<br />
# check pidfile presence and permissions<br />
if [ ! -r "${PIDDIR}/${vm}.pid" ]; then<br />
continue<br />
fi<br />
<br />
stat_busy "Stopping QEMU VM: ${vm}"<br />
<br />
eval vm_haltcmd="\$qemu_${vm}_haltcmd"<br />
eval vm_haltcmd_wait="\$qemu_${vm}_haltcmd_wait"<br />
vm_haltcmd_wait=${vm_haltcmd_wait:-${QEMU_HALTCMD_WAIT}}<br />
vm_pid=$(cat ${PIDDIR}/${vm}.pid)<br />
<br />
# check process existence<br />
if ! kill -0 ${vm_pid} 2>/dev/null; then<br />
stat_done<br />
rm -f "${PIDDIR}/${vm}.pid"<br />
continue<br />
fi<br />
<br />
# Try to shutdown VM safely<br />
_vm_running='yes'<br />
if [ -n "${vm_haltcmd}" ]; then<br />
eval ${vm_haltcmd} >/dev/null<br />
<br />
_w=0<br />
while [ "${_w}" -lt "${vm_haltcmd_wait}" ]; do<br />
sleep 1<br />
if ! kill -0 ${vm_pid} 2>/dev/null; then<br />
# no such process<br />
_vm_running=''<br />
break<br />
fi<br />
_w=$((_w + 1))<br />
done<br />
<br />
else<br />
# No haltcmd - kill VM unsafely<br />
_vm_running='yes'<br />
fi<br />
<br />
if [ -n "${_vm_running}" ]; then<br />
# kill VM unsafely<br />
kill ${vm_pid} 2>/dev/null<br />
sleep 1<br />
fi<br />
<br />
# report status<br />
if kill -0 ${vm_pid} 2>/dev/null; then<br />
# VM is still alive<br />
#kill -9 ${vm_pid}<br />
stat_fail<br />
else<br />
stat_done<br />
fi<br />
<br />
# remove pidfile<br />
rm -f "${PIDDIR}/${vm}.pid"<br />
fi<br />
done<br />
rm_daemon qemu<br />
;;<br />
<br />
restart)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
<br />
*)<br />
echo "usage: $0 {start|stop|restart}"<br />
<br />
esac<br />
</nowiki>}}<br />
<br />
==See also==<br />
*[http://qemu.org Official QEMU website]<br />
*[http://www.linux-kvm.org Official KVM website]<br />
*[http://en.wikibooks.org/wiki/QEMU QEMU Wikibook]<br />
*''[http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU]'' by AlienBOB<br />
*''[http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army]'' by Falconindy</div>
Whgirw
https://wiki.archlinux.org/index.php?title=QEMU&diff=217043
QEMU
2012-08-08T11:00:31Z
<p>Whgirw: /* Installing the operating system */</p>
<hr />
<div>[[Category:Emulators]]<br />
[[Category:Virtualization]]<br />
[[de:Qemu]]<br />
[[fr:Qemu]]<br />
[[zh-CN:QEMU]]<br />
<br />
{{Out of date|[https://www.archlinux.org/news/deprecation-of-net-tools net-tools] is deprecated. [[QEMU#Networking|Networking]] section needs updating. |QEMU#Networking}}<br />
<br />
From the [http://wiki.qemu.org/Main_Page QEMU about page],<br />
<blockquote><br />
<p>QEMU is a generic and open source machine emulator and virtualizer.</p><br />
<br />
<p>When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your own PC). By using dynamic translation, it achieves very good performance.</p><br />
<br />
<p>When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU. QEMU supports virtualization when executing under the Xen hypervisor or using the KVM kernel module in Linux. When using KVM, QEMU can virtualize x86, server and embedded PowerPC, and S390 guests.</p><br />
</blockquote><br />
<br />
== Installing QEMU ==<br />
<br />
Depending on your needs, you can choose to install either {{Pkg|qemu}} or {{Pkg|qemu-kvm}} from the [[Official Repositories|official repositories]]. {{Pkg|qemu}} includes support for emulating a wide variety of machine architectures, while {{Pkg|qemu-kvm}} only supports virtualizing your host architecture using [[KVM]]. It is strongly recommended to use KVM whenever possible; see [[#Using the Kernel-based Virtual Machine]] for more information. In the current version of QEMU (>= 0.15.0), you can still use KVM with the {{Pkg|qemu}} package, if supported by your processor and kernel, provided that you start QEMU with the {{ic|-enable-kvm}} argument; this was not the case for older versions of QEMU (< 0.15.0), when not all KVM-related functions had been merged into upstream QEMU.<br />
<br />
=== Build Your QEMU With Spice support ===<br />
<br />
The official package is built without spice support. You can build your version with spice enabled. You must have installed the [[Arch Build System]] on your system.<br />
<br />
You must install {{aur|spice}} from the [[Arch User Repository|AUR]] first.<br />
<br />
Then update ABS on your system to the latest version and copy {{ic|/var/abs/extra/qemu}} (for QEMU users) or {{ic|/var/abs/extra/qemu-kvm}} (for QEMU-KVM users) to somewhere (here we use {{ic|~/temp/}} as an example) you like:<br />
$ sudo abs<br />
$ cp -r /var/abs/extra/qemu ~/temp<br />
<br />
Go to your copy of the package folder (here {{ic|~/temp/qemu}} or {{ic|~/temp/qemu-kvm}}) and add {{ic|--enable-spice}} after {{ic|.configure}} in the build() function of the [[PKGBUILD]]:<br />
$ cd ~/temp/qemu<br />
$ sed -i "s/\.\/configure/& --enable-spice/g" <br />
<br />
Then build and install the package:<br />
$ makepkg -i<br />
<br />
== Creating a hard disk image==<br />
To run QEMU you will need a hard disk image, unless you are booting a live system from CD-ROM or the network (and not doing so to install an operating system to a hard disk image). A hard disk image is a file which stores the contents of the emulated hard disk. <br />
<br />
A hard disk image may simply contain the literal contents, byte for byte, of the hard disk. This is usually called ''raw'' format, and it provides the least I/O overhead, although the images may take up a large amount of space.<br />
<br />
Alternatively, the hard disk image can be in a format such as ''qcow2'' that can save enormous amounts of space by only allocating space to the image file when the guest operating system actually writes to those sectors on its virtual hard disk. The image appears as the full size to the guest operating system, even though it may take up only a very small amount of space on the host system.<br />
<br />
QEMU provides the {{ic|qemu-img}} command to create hard disk images. The following command creates a 4GB image named {{ic|myimage.qcow2}} in the qcow2 format:<br />
$ qemu-img create -f qcow2 myimage.qcow2 4G<br />
<br />
You may use {{ic|-f raw}} to create a raw disk instead, although you can also do so simply by creating a file of the needed size using {{ic|dd}} or {{ic|fallocate}}.<br />
<br />
== Preparing the installation media ==<br />
<br />
To install an operating system into your disk image, you need the installation media (e.g. CD-ROM, floppy, or ISO image) for the operating system.<br />
<br />
{{Tip|If you would like to run an Arch Linux virtual machine, you can install it using the [http://archlinux.org/download/ official installation media for Arch Linux]. It is also possible to set up an Arch Linux virtual machine without the installation media, provided that your host machine is running Arch Linux, although this is more difficult; it is detailed [[Creating Arch Linux disk image#Install Arch Linux in a disk image without the installation media|here]].}}<br />
<br />
The installation media should not be mounted because QEMU accesses the media directly. Also, if using physical media (e.g. CD-ROM or floppy), it is a good idea to first dump the media to a file because this both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user without having to change access permissions on the media's device file). For example, if the CD-ROM device node is named {{ic|/dev/cdrom}}, you can dump it to a file with the command:<br />
# dd if=/dev/cdrom of=mycdimg.iso<br />
<br />
Do the same for floppies:<br />
# dd if=/dev/fd of=myfloppy.img<br />
<br />
== Installing the operating system==<br />
<br />
To install the operating system on the disk image, you must attach both the disk image and the installation media to the virtual machine, and have it boot from the installation media.<br />
<br />
This is the first time you will need to start the emulator. By default, QEMU will show the virtual machine's video output in a window. <br />
One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it press {{Keypress|Ctrl+Alt}}.<br />
<br />
{{Warning|QEMU should never be run as root. If you must launch it in a script as root, you should use the {{ic|-runas}} option to make QEMU drop root privileges.}}<br />
<br />
If you need to use a bootable floppy, run QEMU with:<br />
$ qemu -cdrom <nowiki>[[cdrom_image]]</nowiki> -fda <nowiki>[[floppy_image]]</nowiki> -boot a <nowiki>[[hd_image]]</nowiki><br />
<br />
or if you are on a x86_64 system (will avoid many problems afterwards):<br />
$ qemu-system-x86_64 -cdrom <nowiki>[[cdrom_image]]</nowiki> -fda <nowiki>[[floppy_image]]</nowiki> -boot a <nowiki>[[hd_image]]</nowiki><br />
<br />
If your CD-ROM is bootable or you are using ISO files, run QEMU with:<br />
$ qemu -cdrom <nowiki>[[cdrom_image]]</nowiki> -boot d <nowiki>[[hd_image]]</nowiki><br />
<br />
or if you are on a x86_64 system (will avoid many problems afterwards):<br />
$ qemu-system-x86_64 -cdrom <nowiki>[[cdrom_image]]</nowiki> -boot d <nowiki>[[hd_image]]</nowiki><br />
<br />
Now, using the installer for the OS, partition the virtual hard disk, format the partitions, and install the OS.<br />
<br />
{{Note|See [[#Windows-specific notes]] if you are installing Windows in your virtual machine.}}<br />
<br />
{{Note|If you need to replace floppies or CDs as part of the installation process, you can use the QEMU machine monitor (press {{Keypress|Ctrl-Alt-2}} in the virtual machine's window) to remove and attach storage devices to a virtual machine. Type {{ic|info block}} to see the block devices, and use the {{ic|change}} command to swap out a device. Press {{Keypress|Ctrl-Alt-1}} to go back to the virtual machine.}}<br />
<br />
== Running the installed system==<br />
<br />
After the operating system has finished installing, you can boot the disk image by itself, without the installation media.<br />
<br />
To run the system simply use a command like:<br />
$ qemu [hd_image]<br />
<br />
{{Note|If possible, you should consider [[#Using the Kernel-based Virtual Machine|using KVM]] for improved performance.}}<br />
<br />
== Using the Kernel-based Virtual Machine ==<br />
<br />
[[KVM]] is a full virtualization solution for Linux on x86 hardware containing virtualization extensions (Intel VT or AMD-V). It consists of a loadable kernel module, kvm.ko, that provides the core virtualization infrastructure and a processor specific module, kvm-intel.ko or kvm-amd.ko. Using KVM, one can run multiple virtual machines running unmodified Linux or Windows images. Each virtual machine has private virtualized hardware: a network card, disk, graphics adapter, etc.<br />
<br />
{{Tip|It is recommended to use KVM whenever possible because it will greatly improve the performance of the running virtual machine compared to QEMU emulating the virtual machine entirely in software.}}<br />
<br />
KVM requires an x86 machine running a recent ( >= 2.6.22) Linux kernel on an Intel processor with VT-x (Virtualization Technology) extensions, or an AMD processor with SVM (Secure Virtual Machine) extensions—''AMD-V'' is the marketing term for AMD's SVM. It is included in the mainline Linux kernel since 2.6.20 and is enabled by default in the Arch Linux kernel.<br />
<br />
{{Pkg|qemu}} ><nowiki>=</nowiki> 0.15.0 has full support for KVM, as the {{Pkg|qemu-kvm}} tree has been completely merged into the upstream QEMU tree. Therefore, there should be no difference between {{ic|qemu -enable-kvm}} and {{ic|qemu-kvm}} if your version of {{Pkg|qemu}} is ><nowiki>=</nowiki> 0.15.0.<br />
<br />
{{Note|QEMU in older versions ( < 0.15.0) does have initial KVM support ({{ic|qemu -enable-kvm}}), but it is not recommended to use this, as many KVM-related functions had not been implemented in upstream QEMU. Instead, for older versions of QEMU you should go for the {{Pkg|qemu-kvm}} package in the [[Official Repositories|official repositories]], which is released by the KVM development team and contains all of the latest features (and bug-fixes) of KVM userspace. Please refer to the [[KVM]] page itself, for more information on using QEMU with KVM on Arch Linux.}}<br />
<br />
To take advantage of KVM, you need a compatible processor (the following command must return something on the screen):<br />
$ grep -E "(vmx|svm)" --color=always /proc/cpuinfo<br />
<br />
And load the appropriate module from your {{ic|/etc/[[rc.conf]]}}.<br />
<br />
* For Intel® processors, add {{ic|kvm-intel}} to your {{ic|MODULES}} array in {{ic|/etc/rc.conf}}<br />
* for AMD® processors, add {{ic|kvm-amd}} to your {{ic|MODULES}} array in {{ic|/etc/rc.conf}}<br />
<br />
Also, you will need to add yourself to the group {{ic|kvm}}.<br />
# gpasswd -a <Your_User_Account> kvm<br />
<br />
== Overlay images ==<br />
<br />
A good idea is to use overlay images. This way you can a create hard disk image once and tell QEMU to store changes in an external file.<br />
This makes it easy to revert the virtual machine's disk to a previous state.<br />
<br />
To create an overlay image, type:<br />
$<nowiki> qemu-img create -b [[base''image]] -f qcow2 [[overlay''image]]</nowiki><br />
<br />
After that you can run qemu with:<br />
$ qemu [overlay_image]<br />
<br />
or if you are on a x86_64 system:<br />
$ qemu-system-x86_64 [overlay_image]<br />
<br />
and the original image will be left untouched. One hitch, the base image cannot be renamed or moved, the overlay remembers the base's full path.<br />
<br />
== Moving data between host and guest OS ==<br />
<br />
=== Network ===<br />
<br />
Data can be shared between the host and guest OS using any network protocol that can transfer files, such as [[NFS]], [[Samba|SMB]], NBD, HTTP, [[Very Secure FTP Daemon|FTP]], or [[Secure Shell|SSH]], provided that you have set up the network appropriately and enabled the appropriate services.<br />
<br />
The default user-mode networking allows the guest to access the host OS at the IP address 10.0.2.2. Any servers that you are running on your host OS, such as a SSH server or SMB server, will be accessible at this IP address. So on the guests, you can mount directories exported on the host via [[Samba|SMB]] or [[NFS]], or you can access the host's HTTP server, etc. <br />
It will not be possible for the host OS to access servers running on the guest OS, but this can be done with other network configurations (see [[#Tap networking with QEMU]]).<br />
<br />
=== QEMU's built-in SMB server ===<br />
<br />
{{Note|QEMU's "built-in" SMB server is currently (as of qemu-1.0.1-1) broken because it does not specify the {{ic|state_directory}} option in the {{ic|smb.conf}} file it writes. This issue is fixed in upstream QEMU.}}<br />
<br />
QEMU's documentation says it has a "built-in" SMB server, but actually it just starts up [[Samba]] with an automatically generated configuration file and makes it accessible to the guest at a different IP address (10.0.2.4 by default). This only works for user networking, and this isn't necessarily very useful since the guest can also access the normal [[Samba]] service on the host if you have set up shares on it.<br />
<br />
To enable this feature, start QEMU with a command like:<br />
$ qemu [hd_image] -net nic -net user,smb=/path/to/shared/dir<br />
<br />
where {{ic|/path/to/shared/dir}} is a directory that you want to share between the guest and host.<br />
<br />
Then, in the guest, you will be able to access the shared directory on the host 10.0.2.4 with the share name "qemu". For example, in Windows Explorer you would go to {{ic|\\10.0.2.4\qemu}}.<br />
<br />
=== Mounting a partition inside a raw disk image ===<br />
<br />
When the virtual machine is not running, it is possible to mount partitions that are inside a raw disk image file by setting them up as loopback devices. This does not work with disk images in special formats, such as qcow2, although those can be mounted using {{ic|qemu-nbd}}.<br />
<br />
{{Warning|You must make sure to unmount the partitions before running the virtual machine again. Otherwise data corruption could occur, unless you had mounted the partitions read-only.}}<br />
<br />
==== With manually specifying byte offset ====<br />
<br />
One way to mount a disk image partition is to mount the disk image at a certain offset using a command like the following:<br />
# mount -o loop,offset=32256 [hd_image] [tmp_dir]<br />
<br />
The {{ic|<nowiki>offset=32256</nowiki>}} option is actually passed to the {{ic|losetup}} program to set up a loopback device that starts at byte offset 32256 of the file and continues to the end. This loopback device is then mounted. You may also use the {{ic|sizelimit}} option to specify the exact size of the partition, but this is usually unnecessary.<br />
<br />
Depending on your disk image, the needed partition may not start at offset 32256. Run {{ic|fdisk -l [hd_image]}} to see the partitions in the image. fdisk gives the start and end offsets in 512-byte sectors, so multiply by 512 to get the correct offset to pass to {{ic|mount}.<br />
<br />
==== With loop module autodetecting partitions ====<br />
<br />
The Linux loop driver actually supports partitions in loopback devices, but it is disabled by default. To enable it, do the following:<br />
<br />
* Get rid of all your loopback devices (unmount all mounted images, etc.).<br />
* Unload the loop [[Kernel modules|module]].<br />
# modprobe -r loop<br />
* Load the loop [[Kernel modules|module]] with the {{ic|max_part}} parameter set.<br />
# modprobe loop max_part=15<br />
<br />
{{Tip|You can put an entry in {{ic|/etc/modprobe.d}} to load the loop module with {{ic|<nowiki>max_part=15</nowiki>}} every time, or you can put {{ic|<nowiki>loop.max_part=15</nowiki>}} on the kernel command line, depending on whether you have the {{ic|loop.ko}} module built into your kernel or not.}}<br />
<br />
Set up your image as a loopback device:<br />
# losetup -f [os_image]<br />
<br />
Then, if the device created was {{ic|/dev/loop0}}, additional devices {{ic|/dev/loop0pX}} will have been automatically created, where X is the number of the partition. These partition loopback devices can be mounted directly. For example:<br />
# mount /dev/loop0p1 [tmp_dir]<br />
<br />
==== With kpartx ====<br />
<br />
'''kpartx''' from the {{Pkg|multipath-tools}} package can read a partition table on a device and create a new device for each partition. For example:<br />
# kpartx -a /dev/loop0<br />
<br />
=== Mounting qcow2 image ===<br />
You may mount a qcow2 image using {{ic|qemu-nbd}}. See [[http://en.wikibooks.org/wiki/QEMU/Images#Mounting_an_image_on_the_host Wikibooks]].<br />
<br />
=== Using any real partition as the single primary partition of a hard disk image ===<br />
<br />
Sometimes, you may wish to use one of your system partitions from within QEMU. Using a raw partition for a virtual machine will improve performance, as the read and write operations do not go through the filesystem layer on the physical host. Such a partition also provides a way to share data between the host and guest.<br />
<br />
In Arch Linux, device files for raw partitions are, by default, owned by ''root'' and the ''disk'' group. If you would like to have a non-root user be able to read and write to a raw partition, you need to change the owner of the partition's device file to that user.<br />
<br />
{{Warning|Although it is possible, it is not recommended to allow virtual machines to alter critical data on the host system, such as the root partition.}}<br />
<br />
{{Warning|You must not mount a filesystem on a partition read-write on both the host and the guest at the same time. Otherwise, data corruption will result.}}<br />
<br />
After doing so, you can attach the partition to a QEMU virtual machine as a virtual disk.<br />
<br />
However, things are a little more complicated if you want to have the ''entire'' virtual machine contained in a partition. In that case, there would be no disk image file to actually boot the virtual machine since you cannot install a bootloader to a partition that is itself formatted as a filesystem and not as a partitioned device with a MBR (FIXME: Isn't that actually possible, since filesystems don't begin on the first sector?). Such a virtual machine can be booted either by specifying the [[Kernels|kernel]] and [[initramfs|initrd]] manually, or by simulating a disk with a MBR by using linear [[RAID]].<br />
<br />
==== By specifying kernel and initrd manually ====<br />
<br />
QEMU supports loading [[Kernels|Linux kernels]] and [[initramfs|init ramdisks]] directly, thereby circumventing bootloaders such as [[GRUB]]. It then can be launched with the physical partition containing the root filesystem as the virtual disk, which will not appear to be partitioned. This is done by issuing a command similar to the following:<br />
$ qemu -kernel /boot/vmlinuz-linux -initrd /boot/initramfs-linux.img -append root=/dev/sda /dev/sda3<br />
<br />
In the above example, the physical partition being used for the guest's root filesystem is {{ic|/dev/sda3}} on the host, but it shows up as {{ic|/dev/sda}} on the guest.<br />
<br />
You may, of course, specify any kernel and initrd that you want, and not just the ones that come with Arch Linux.<br />
<br />
==== Simulate virtual disk with MBR using linear RAID ====<br />
<br />
A more complicated way to have a virtual machine use a physical partition, while keeping that partition formatted as a filesystem and not just having the guest partition the partition as if it were a disk, is to simulate a MBR for it so that it can boot using a bootloader such as GRUB.<br />
<br />
You can do this using software [[RAID]] in linear mode (you need the linear.ko kernel driver) and a loopback device: the trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image.<br />
<br />
Suppose you have a plain, unmounted {{ic|/dev/hdaN}} partition with some filesystem on it you wish to make part of a QEMU disk image. First, you create some small file to hold the MBR:<br />
$ dd if=/dev/zero of=/path/to/mbr count=32<br />
<br />
Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:<br />
# losetup -f /path/to/mbr<br />
<br />
Let's assume the resulting device is {{ic|/dev/loop0}}, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + {{ic|/dev/hdaN}} disk image using software RAID:<br />
# modprobe linear<br />
# mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hdaN<br />
<br />
The resulting {{ic|/dev/md0}} is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of {{ic|/dev/hdaN}} inside {{ic|/dev/md0}} (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using {{ic|fdisk}} on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:<br />
# fdisk /dev/md0<br />
<br />
Press {{Keypress|X}} to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.<br />
<br />
Now, press {{Keypress|R}} to return to the main menu. <br />
<br />
Press {{Keypress|P}} and check that the cylinder size is now 16k.<br />
<br />
Now, create a single primary partition corresponding to {{ic|/dev/hdaN}}. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.<br />
<br />
Finally, 'w'rite the result to the file: you are done. You know have a partition you can mount directly from your host, as well as part of a QEMU disk image: <br />
<br />
$ qemu -hdc /dev/md0 [...]<br />
<br />
You can of course safely set any bootloader on this disk image using QEMU, provided the original {{ic|/dev/hdaN}} partition contains the necessary tools.<br />
<br />
==Networking==<br />
===User-mode networking===<br />
<br />
By default, without any {{ic|-net}} arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU. This only works with the TCP and UDP protocols, so ICMP, including {{ic|ping}}, will not work. <br />
<br />
This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.<br />
<br />
QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, or attaching guests to virtual LANs so that they can talk to each other. See the QEMU documentation on the {{ic|-net user}} flag for more details.<br />
<br />
However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.<br />
<br />
=== Tap networking with QEMU ===<br />
==== Basic idea ====<br />
<br />
[http://en.wikipedia.org/wiki/TUN/TAP Tap devices] are a Linux kernel feature that allows you to create virtual "tap" network interfaces that appear as real network interfaces. Packets sent to a "tap" interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.<br />
<br />
QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.<br />
<br />
Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as eth0. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.<br />
<br />
==== Bridge virtual machines to external network ====<br />
<br />
The following describes how to bridge a virtual machine to a host interface such as eth0, which is probably the most common configuration. This configuration makes it appear that the virtual machine is located directly on the external network, on the same Ethernet segment as the physical host machine.<br />
<br />
{{Warning|Beware that since your virtual machines will appear directly on the external network, this may expose them to attack. Depending on what resources your virtual machines have access to, you may need to take all the precautions you normally would take in securing a computer to secure your virtual machines.}}<br />
<br />
We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it. See http://en.gentoo-wiki.com/wiki/KVM#Networking_2 .<br />
<br />
1. Make sure that the following packages are installed:<br />
*{{Pkg|bridge-utils}} (provides {{ic|brctl}}, to manipulate bridges)<br />
*{{Pkg|uml_utilities}} (provides {{ic|tunctl}}, to manipulate taps)<br />
<br />
2. Enable IPv4 forwarding by changing {{ic|<nowiki>net.ipv4.ip_forward = 0</nowiki>}} to {{ic|<nowiki>net.ipv4.ip_forward = 1</nowiki>}} in {{ic|<nowiki>/etc/sysctl.conf</nowiki>}}.<br />
<br />
3. Add {{ic|bridge}} and {{ic|tun}} to your {{ic|MODULES}} array in {{ic|/etc/rc.conf}}:<br />
<br />
MODULES=( ... bridge tun)<br />
<br />
4. Configure your bridge {{ic|br0}} to have your real Ethernet adapter (assuming {{ic|eth0}} for the rest of this guide) in it, in {{ic|/etc/conf.d/bridges}}:<br />
bridge_br0="eth0"<br />
control_br0="setfd br0 0"<br />
BRIDGE_INTERFACES=(br0)<br />
<br />
{{Note|This is not described anywhere, but adding the {{ic|control_br0}} line is vital for the bridge to work! For more details look here: {{bug|16625}}}}<br />
<br />
5. Change your networking configuration so that you just bring up your real Ethernet adapter without configuring it, allowing real configuration to happen on the bridge interface. In {{ic|/etc/rc.conf}}:<br />
eth0="eth0 up"<br />
br0="dhcp"<br />
INTERFACES=(eth0 br0)<br />
<br />
Remember, especially if you are doing DHCP, it is essential that the bridge comes up AFTER the real adapter, otherwise the bridge will not be able to talk to anything to get a DHCP address!<br />
<br />
If you have been giving eth0 a static IP address rather than using DHCP, give br0 similar settings:<br />
<br />
{{ic|/etc/rc.conf}}:<br />
eth0="eth0 0.0.0.0"<br />
br0="br0 192.168.0.3 netmask 255.255.255.0 broadcast 192.168.0.255"<br />
INTERFACES=(eth0 br0)<br />
gateway="default gw 192.168.0.1"<br />
ROUTES=(gateway)<br />
<br />
and then in {{ic|/etc/resolv.conf}}:<br />
domain lan<br />
nameserver 192.168.0.1<br />
<br />
6. Install the script that QEMU uses to bring up the tap adapter in {{ic|/etc/qemu-ifup}} with root:kvm 750 permissions:<br />
#!/bin/sh<br />
<br />
echo "Executing /etc/qemu-ifup"<br />
echo "Bringing up $1 for bridged mode..."<br />
sudo /sbin/ifconfig $1 0.0.0.0 promisc up<br />
echo "Adding $1 to br0..."<br />
sudo /usr/sbin/brctl addif br0 $1<br />
sleep 2<br />
<br />
7. Use {{ic|visudo}} to add the following to your {{ic|sudoers}} file:<br />
Cmnd_Alias QEMU=/sbin/ifconfig,/sbin/modprobe,/usr/sbin/brctl,/usr/bin/tunctl<br />
%kvm ALL=NOPASSWD: QEMU<br />
<br />
8. Make sure the user(s) wishing to use this new functionality are in the {{ic|kvm}} group. Exit and log in again if necessary.<br />
<br />
9. You launch QEMU using the following {{ic|run-qemu}} script:<br />
#!/bin/bash<br />
USERID=`whoami`<br />
IFACE=$(sudo tunctl -b -u $USERID)<br />
printf -v macaddr "52:54:%02x:%02x:%02x:%02x" \<br />
$(( $RANDOM & 0xff)) $(( $RANDOM & 0xff )) \<br />
$(( $RANDOM & 0xff)) $(( $RANDOM & 0xff ))<br />
<br />
qemu-kvm -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*<br />
<br />
sudo tunctl -d $IFACE &> /dev/null<br />
<br />
Then to launch a VM, do something like this<br />
$ run-qemu -hda myvm.img -m 512 -vga std<br />
<br />
10. If you cannot get a DHCP address in the host, it might be because [[Iptables|iptables]] are up by default in the bridge. In that case (from http://www.linux-kvm.org/page/Networking ):<br />
# cd /proc/sys/net/bridge<br />
# ls<br />
bridge-nf-call-arptables bridge-nf-call-iptables<br />
bridge-nf-call-ip6tables bridge-nf-filter-vlan-tagged<br />
# for f in bridge-nf-*; do echo 0 > $f; done<br />
<br />
And if you still cannot get networking to work, see: [[Linux_Containers#Bridge_device_setup]]<br />
<br />
==== Host-only networking ====<br />
<br />
If the bridge is given an IP address and traffic destined for it is allowed, but no "real" interface (e.g. eth0) is also connected to the bridge, then the virtual machines will be able to talk to each other and the physical host. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called "host-only" networking by other virtualization software such as [[VirtualBox]].<br />
<br />
You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the 172.20.0.1/16 subnet with [[Dnsmasq]] as the DHCP server:<br />
<br />
# ip addr add 172.20.0.1/16 dev br0<br />
# ip link set br0 up<br />
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=172.20.0.2,172.20.255.254<br />
<br />
==== Internal networking ====<br />
<br />
If you do not give the bridge an IP address and add an [[Iptables|iptables]] rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or to the outside network. This configuration is called "internal" networking by other virtualization software such as [[VirtualBox]]. You will need to either assign static IP addresses to the virtual machines or run a DHCP server on one of them.<br />
<br />
==== Link-level address caveat ====<br />
<br />
By giving the {{ic|-net nic}} argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address 52:54:00:12:34:56. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.<br />
<br />
To solve this problem, the last 8 digits of the link-level address of the virtual NICs should be randomized, as in the script above, to make sure that each virtual machine has a unique link-level address.<br />
<br />
=== Networking with [[VDE2]] ===<br />
==== What is VDE? ====<br />
VDE stands for Virtual Distributed Ethernet. It started as an enhancement of [[User-mode Linux|uml]]_switch. It is a toolbox to manage virtual networks.<br />
<br />
The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration I show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. Your are invited to read [http://wiki.virtualsquare.org/wiki/index.php/Main_Page the documentation of the project].<br />
<br />
The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.<br />
<br />
==== Basics ====<br />
VDE is in the [[Official Repositories|official repositories]], so...<br />
<br />
# pacman -S vde2<br />
<br />
In my config, I use tun/tap to create a virtual interface on my host. Load the {{ic|tun}} module (or add it to your {{ic|MODULES}} array in {{ic|[[rc.conf]]}}):<br />
<br />
# modprobe tun<br />
<br />
Now create the virtual switch:<br />
<br />
# vde_switch -tap tap0 -daemon -mod 660 -group kvm<br />
<br />
This line creates the switch, creates tap0, "plugs" it, and allows the users of the group {{ic|kvm}} to use it.<br />
<br />
The interface is plugged in but not configured yet. Just do it:<br />
<br />
# ifconfig tap0 192.168.100.254 netmask 255.255.255.0<br />
<br />
That is all! Now, you just have to run KVM with these {{ic|-net}} options as a normal user:<br />
<br />
$ qemu-kvm -net nic -net vde -hda ...<br />
<br />
Configure your guest as you would do in a physical network. I gave them static addresses and let them access the WAN using IP forwarding and masquerading on my host:<br />
<br />
# echo "1" > /proc/sys/net/ipv4/ip_forward<br />
# iptables -t nat -A POSTROUTING -s 192.168.100.0/24 -o eth0 -j MASQUERADE<br />
<br />
==== Putting it together ====<br />
I added this init script to run all this at start-up:<br />
<br />
#!/bin/bash <br />
<br />
. /etc/rc.conf<br />
. /etc/rc.d/functions<br />
case "$1" in<br />
start)<br />
stat_busy "Starting VDE Switch"<br />
vde_switch -tap tap0 -daemon -mod 660 -pidfile $PIDFILE -group kvm<br />
if [ $? -gt 0 ]; then<br />
stat_fail<br />
else<br />
echo "1" > /proc/sys/net/ipv4/ip_forward && \<br />
iptables -t nat -A POSTROUTING -s 192.168.100.0/24 -o eth0 -j MASQUERADE && \<br />
ifconfig tap0 192.168.100.254 netmask 255.255.255.0 && \<br />
stat_done || stat_fail<br />
fi<br />
;;<br />
stop)<br />
stat_busy "Stopping VDE Switch"<br />
# err.. well, i should remove the switch here...<br />
stat_done<br />
;;<br />
restart)<br />
$0 stop<br />
sleep 1<br />
# Aem.. As long as stop) is not implemented, this just fails<br />
$0 start<br />
;;<br />
*)<br />
echo "usage: $0 {start|stop|restart}" <br />
esac<br />
exit 0<br />
<br />
Well, I know it is dirty and could be more configurable. Feel free to improve it. VDE has an rc script too, but I had to make one anyway for the IP forwarding stuff.<br />
<br />
====Alternative method====<br />
If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq and iptables you can do the following for the same result.<br />
<br />
# vde_switch -daemon -mod 660 -group kvm<br />
<br />
# slirpvde --dhcp --daemon<br />
<br />
Then to start the vm with a connection to the network of the host:<br />
<br />
$ kvm -net nic,macaddr=52:54:00:00:EE:03 -net vde whatever.qcow<br />
<br />
=== Improving networking performance ===<br />
<br />
The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde, since tap devices and bridges are implemented in-kernel.<br />
<br />
In addition, networking performance can be improved by assigning virtual machines a [http://wiki.libvirt.org/page/Virtio virtio] network device rather than the default emulation of an e1000 NIC. To do this, add a {{ic|<nowiki>model=virtio</nowiki>}} flag to the {{ic|-net nic}} option:<br />
<br />
-net nic,model=virtio<br />
<br />
This will only work if the guest machine has a driver for virtio network devices. Linux does, and the required driver ('''virtio_net''') is included with Arch Linux, but there is no guarantee that virtio networking will work with arbitrary operating systems. There do exist [[#Virtio drivers for Windows|virtio drivers for Windows]], but you need to install them manually.<br />
<br />
== Graphics ==<br />
QEMU can use the following different graphic outputs: std, cirrus, vmware, qxl, xenfs and vnc.<br />
With the {{ic|vnc}} option you can run your guest standalone and connect to it via VNC. Other options are using {{ic|std}}, {{ic|vmware}}, {{ic|cirrus}}:<br />
<br />
===std===<br />
With {{ic|-vga std}} you can get a resolution of up to 2560 x 1600 pixels.<br />
<br />
===vmware===<br />
Although it is a bit buggy, it performs better than std and cirrus. On the guest, install the VMware drivers. For Arch Linux guests:<br />
# pacman -S xf86-video-vmware xf86-input-vmmouse<br />
<br />
===none===<br />
<br />
If you do not want to see the graphical output from your virtual machine because you will be accessing it entirely through the network or serial port, you can run QEMU with the {{ic|-nographic}} option.<br />
<br />
== Graphical front-ends for QEMU ==<br />
<br />
Unlike other virtualization progrems such as [[VirtualBox]] and [[VMware]], QEMU does not provide a GUI to manage virtual machines (other than the window that appears when running a virtual machine), nor does it provide a way to create persistent virtual machines with saved settings. All parameters to run a virtual machine must be specified on the command line at every launch, unless you have created a custom script to start your virtual machine(s). However, there are several GUI front-ends for QEMU:<br />
<br />
* virt-manager (part of [[libvirt]])<br />
* {{Pkg|qemu-launcher}}<br />
* community/qemulator<br />
* {{Pkg|qtemu}}<br />
<br />
== Windows-specific notes ==<br />
=== Choosing a Windows version ===<br />
<br />
QEMU can run any version of Windows. However, 98, Me and XP will run at quite a low speed. You should choose either Windows 95 or Windows 2000. Surprisingly, 2000 seems to run faster than 98. The fastest one is 95, which can from time to time make you forget that you are running an emulator :)<br />
<br />
If you own both Win95 and Win98/WinME, then 98lite (from http://www.litepc.com) might be worth trying. It decouples Internet Explorer from operating system and replaces it with original Windows 95 Explorer. It also enables you to do a minimal Windows installation, without all the bloat you normally cannot disable. This might be the best option, because you get the smallest, fastest and most stable Windows this way.<br />
<br />
It is possible to run [[Windows PE]] in QEMU.<br />
<br />
=== Windows 95 boot floppy ===<br />
<br />
If you are using the Windows 95 boot floppy, choosing SAMSUNG as the type of CD-ROM seems to work.<br />
<br />
=== Windows 2000 installation bug ===<br />
<br />
There are problems when installing Windows 2000. Windows setup will generate a lot of edb*.log files, one after the other containing nothing but blank spaces in {{ic|C:\WINNT\SECURITY}} which quickly fill the virtual hard disk. A workaround is to open a Windows command prompt as early as possible during setup (by pressing {{Keypress|Shift+F10}}) which will allow you to remove these log files as they appear by typing:<br />
del %windir%\security\*.log<br />
<br />
{{Note|According to the official QEMU website, "Windows 2000 has a bug which gives a disk full problem during its installation. When installing it, use the {{ic|-win2k-hack}} QEMU option to enable a specific workaround. After Windows 2000 is installed, you no longer need this option (this option slows down the IDE transfers)."}}<br />
<br />
=== Optimizing Windows 9X CPU usage ===<br />
<br />
Windows 9X uses an idle loop instead of the HLT (halt) instruction. Consequently, the emulator will consume all CPU resources when running Windows 9X guests -- even if no work is being done. This only applies to DOS and DOS-based Windows versions (3.X, 95/98/ME) -- NT-based and later Windows versions are not affected.<br />
<br />
To resolve this issue, install [http://www.benchtest.com/rain.html Rain], [http://www.benchtest.com/wfp.html Waterfall] or [http://www.benchtest.com/cpuidle.html CpuIdle] in the Windows 9X guest. (Rain might be preferred because it does only what is needed -- replacing the idle loop with the HLT instruction -- and nothing more.)<br />
<br />
See [https://forums.virtualbox.org/viewtopic.php?f=28&t=9918 Tutorial: Windows 95/98 guest OSes] for more information.<br />
<br />
===Remote Desktop Protocol===<br />
If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. Use: (if you are using a VLAN or are not in the same network as the guest)<br />
$ qemu -nographic -net user,hostfwd=tcp::5555-:3389<br />
Then connect with either rdesktop or freerdp to the guest, for example:<br />
$ xfreerdp -g 2048x1152 localhost:5555 -z -x lan<br />
<br />
=== Windows virtio drivers ===<br />
<br />
You can use [http://wiki.libvirt.org/page/Virtio virtio] devices with Windows if you install the [http://www.linux-kvm.org/page/WindowsGuestDrivers/Download_Drivers virtio guest drivers] for Windows.<br />
<br />
== General problems ==<br />
<br />
=== Keyboard seems broken or the arrow keys do not work ===<br />
Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in {{ic|/usr/share/qemu/keymaps}}.<br />
{{bc|<br />
qemu -k [keymap] [disk_image]<br />
}}<br />
<br />
=== Virtual machine runs too slowly ===<br />
<br />
There are a number of techniques that you can use to improve the performance if your virtual machine. For example:<br />
<br />
* Use KVM if possible (see [[#Using the Kernel-based Virtual Machine]]).<br />
* Make sure you have assigned the virtual machine enough memory. By default, QEMU only assigns 128MiB of memory to each virtual machine. Use the {{ic|-m}} option to assign more memory. For example, {{ic|-m 1024}} runs a virtual machine with 1024MiB of memory.<br />
* If the host machine has multiple CPUs, assign the guest more CPUs using the {{ic|-smp}} option.<br />
* Use the {{ic|-cpu host}} option to make QEMU emulate the host's exact CPU. If you don't do this, it may be trying to emulate a more generic CPU.<br />
* If supported by drivers in the guest operating system, use [http://wiki.libvirt.org/page/Virtio virtio] for network and/or block devices. For example:<br />
$ qemu -net nic,model=virtio -net tap,if=tap0,script=no -drive file=mydisk.raw,media=disk,if=virtio<br />
* [[#Tap networking with QEMU|Use TAP devices]] instead of user-mode networking.<br />
* If the guest OS is doing heavy writing to its disk, you may benefit from certain mount options on the host's filesystem. For example, you can mount an [[Ext4|ext4 filesystem]] with the option {{ic|<nowiki>barrier=0</nowiki>}}. You should read the documentation for any options that you change, since sometimes performance-enhancing options for filesystems come at the cost of data integrity.<br />
* If you are running multiple virtual machines concurrently that all have the same operating system installed, you can save memory by enabling [http://en.wikipedia.org/wiki/Kernel_SamePage_Merging_(KSM) kernel same-page merging]:<br />
# echo 1 > /sys/kernel/mm/ksm/run<br />
* In some cases, memory can be reclaimed from running virtual machines by running a memory ballooning driver in the guest operating system and launching QEMU with the {{ic|-balloon virtio}} option.<br />
<br />
==Starting QEMU virtual machines on boot==<br />
<br />
===With libvirt===<br />
<br />
If a virtual machine is set up with [[libvirt]], it can be configured through the virt-manager GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".<br />
<br />
===Custom script===<br />
To run QEMU VMs on boot, you can use following rc-script and config.<br />
<br />
{| border="1"<br />
|+ Config file options<br />
|-<br />
| QEMU_MACHINES || List of VMs to start<br />
|-<br />
| qemu_${vm}_type || QEMU binary to call. If specified, will be prepended with {{ic|/usr/bin/qemu-}} and that binary will be used to start the VM. I.e. you can boot e.g. qemu-system-arm images with qemu_my_arm_vm_type="system-arm". If not specified, {{ic|/usr/bin/qemu}} will be used.<br />
|-<br />
| qemu_${vm} || QEMU command line to start with. Will always be prepended with {{ic|-name ${vm} -pidfile /var/run/qemu/${vm}.pid -daemonize -nographic}}.<br />
|-<br />
| qemu_${vm}_haltcmd || Command to shutdown VM safely. I am using {{ic|-monitor telnet:..}} and power off my VMs via ACPI by sending {{ic|system_powerdown}} to monitor. You can use ssh or some other ways.<br />
|-<br />
| qemu_${vm}_haltcmd_wait || How much time to wait for safe VM shutdown. Default is 30 seconds. rc-script will kill qemu process after this timeout.<br />
|}<br />
<br />
Config file example:<br />
{{hc|/etc/conf.d/qemu.conf|<nowiki><br />
# VMs that should be started on boot<br />
# use the ! prefix to disable starting/stopping a VM<br />
QEMU_MACHINES=(vm1 vm2)<br />
<br />
# NOTE: following options will be prepended to qemu_${vm}<br />
# -name ${vm} -pidfile /var/run/qemu/${vm}.pid -daemonize -nographic<br />
<br />
qemu_vm1_type="system-x86_64"<br />
<br />
qemu_vm1="-enable-kvm -m 512 -hda /dev/mapper/vg0-vm1 -net nic,macaddr=DE:AD:BE:EF:E0:00 \<br />
-net tap,ifname=tap0 -serial telnet:localhost:7000,server,nowait,nodelay \<br />
-monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"<br />
<br />
qemu_vm1_haltcmd="echo 'system_powerdown' | nc.openbsd localhost 7100" # or netcat/ncat<br />
<br />
# You can use other ways to shutdown your VM correctly<br />
#qemu_vm1_haltcmd="ssh powermanager@vm1 sudo poweroff"<br />
<br />
# By default rc-script will wait 30 seconds before killing VM. Here you can change this timeout.<br />
#qemu_vm1_haltcmd_wait="30"<br />
<br />
qemu_vm2="-enable-kvm -m 512 -hda /srv/kvm/vm2.img -net nic,macaddr=DE:AD:BE:EF:E0:01 \<br />
-net tap,ifname=tap1 -serial telnet:localhost:7001,server,nowait,nodelay \<br />
-monitor telnet:localhost:7101,server,nowait,nodelay -vnc :1"<br />
<br />
qemu_vm2_haltcmd="echo 'system_powerdown' | nc.openbsd localhost 7101"<br />
</nowiki>}}<br />
<br />
rc-script:<br />
{{hc|/etc/rc.d/qemu|<nowiki><br />
#!/bin/bash<br />
. /etc/rc.conf<br />
. /etc/rc.d/functions<br />
<br />
[ -f /etc/conf.d/qemu.conf ] && source /etc/conf.d/qemu.conf<br />
<br />
PIDDIR=/var/run/qemu<br />
QEMU_DEFAULT_FLAGS='-name ${vm} -pidfile ${PIDDIR}/${vm}.pid -daemonize -nographic'<br />
QEMU_HALTCMD_WAIT=30<br />
<br />
case "$1" in<br />
start)<br />
[ -d "${PIDDIR}" ] || mkdir -p "${PIDDIR}"<br />
for vm in "${QEMU_MACHINES[@]}"; do<br />
if [ "${vm}" = "${vm#!}" ]; then<br />
stat_busy "Starting QEMU VM: ${vm}"<br />
eval vm_cmdline="\$qemu_${vm}"<br />
eval vm_type="\$qemu_${vm}_type"<br />
<br />
if [ -n "${vm_type}" ]; then<br />
vm_cmd="/usr/bin/qemu-${vm_type}"<br />
else<br />
vm_cmd='/usr/bin/qemu'<br />
fi<br />
<br />
eval "qemu_flags=\"${QEMU_DEFAULT_FLAGS}\""<br />
<br />
${vm_cmd} ${qemu_flags} ${vm_cmdline} >/dev/null<br />
if [ $? -gt 0 ]; then<br />
stat_fail<br />
else<br />
stat_done<br />
fi<br />
fi<br />
done<br />
add_daemon qemu<br />
;;<br />
<br />
stop)<br />
for vm in "${QEMU_MACHINES[@]}"; do<br />
if [ "${vm}" = "${vm#!}" ]; then<br />
# check pidfile presence and permissions<br />
if [ ! -r "${PIDDIR}/${vm}.pid" ]; then<br />
continue<br />
fi<br />
<br />
stat_busy "Stopping QEMU VM: ${vm}"<br />
<br />
eval vm_haltcmd="\$qemu_${vm}_haltcmd"<br />
eval vm_haltcmd_wait="\$qemu_${vm}_haltcmd_wait"<br />
vm_haltcmd_wait=${vm_haltcmd_wait:-${QEMU_HALTCMD_WAIT}}<br />
vm_pid=$(cat ${PIDDIR}/${vm}.pid)<br />
<br />
# check process existence<br />
if ! kill -0 ${vm_pid} 2>/dev/null; then<br />
stat_done<br />
rm -f "${PIDDIR}/${vm}.pid"<br />
continue<br />
fi<br />
<br />
# Try to shutdown VM safely<br />
_vm_running='yes'<br />
if [ -n "${vm_haltcmd}" ]; then<br />
eval ${vm_haltcmd} >/dev/null<br />
<br />
_w=0<br />
while [ "${_w}" -lt "${vm_haltcmd_wait}" ]; do<br />
sleep 1<br />
if ! kill -0 ${vm_pid} 2>/dev/null; then<br />
# no such process<br />
_vm_running=''<br />
break<br />
fi<br />
_w=$((_w + 1))<br />
done<br />
<br />
else<br />
# No haltcmd - kill VM unsafely<br />
_vm_running='yes'<br />
fi<br />
<br />
if [ -n "${_vm_running}" ]; then<br />
# kill VM unsafely<br />
kill ${vm_pid} 2>/dev/null<br />
sleep 1<br />
fi<br />
<br />
# report status<br />
if kill -0 ${vm_pid} 2>/dev/null; then<br />
# VM is still alive<br />
#kill -9 ${vm_pid}<br />
stat_fail<br />
else<br />
stat_done<br />
fi<br />
<br />
# remove pidfile<br />
rm -f "${PIDDIR}/${vm}.pid"<br />
fi<br />
done<br />
rm_daemon qemu<br />
;;<br />
<br />
restart)<br />
$0 stop<br />
sleep 1<br />
$0 start<br />
;;<br />
<br />
*)<br />
echo "usage: $0 {start|stop|restart}"<br />
<br />
esac<br />
</nowiki>}}<br />
<br />
==See also==<br />
*[http://qemu.org Official QEMU website]<br />
*[http://www.linux-kvm.org Official KVM website]<br />
*[http://en.wikibooks.org/wiki/QEMU QEMU Wikibook]<br />
*''[http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu Hardware virtualization with QEMU]'' by AlienBOB<br />
*''[http://blog.falconindy.com/articles/build-a-virtual-army.html Building a Virtual Army]'' by Falconindy</div>
Whgirw
https://wiki.archlinux.org/index.php?title=Archiso&diff=215456
Archiso
2012-07-29T15:25:28Z
<p>Whgirw: Undo revision 215455 by Whgirw (talk)</p>
<hr />
<div>[[Category:Live Arch systems]]<br />
[[el:Archiso]]<br />
[[fr:Archiso]]<br />
[[it:Archiso]]<br />
[[nl:Archiso]]<br />
[[ru:Archiso]]<br />
[[uk:Archiso]]<br />
'''Archiso''' is a small set of bash scripts that is capable of building fully functional Arch Linux based live CD and USB images. It is a very generic tool, so it could potentially be used to generate anything from rescue systems, install disks, to special interest live CD/DVD/USB systems, and who knows what else. Simply put, if it involves Arch on a shiny coaster, it can do it.<br />
The heart and soul of Archiso is mkarchiso. All of its options are documented in its usage output, so its direct usage won't be covered here. Instead, this wiki article will act as a guide for rolling your own live mediums in no time!<br />
<br />
<br />
== Setup ==<br />
<br />
Before we begin, we need to grab the archiso scripts which carry out the beef of the work for us. You can get archiso from Git (recommended) or from [https://aur.archlinux.org/packages.php?ID=25996 aur]. We also need a few packages which archiso relies on; the following commands take care of this for us:<br />
<br />
# pacman -S make patch git libisoburn squashfs-tools dosfstools rsync --needed<br />
# git clone git://projects.archlinux.org/archiso.git<br />
# make -C archiso/archiso install<br />
<br />
Create a directory to work within, this is where all the modifications to the live image will take place: ~/archlive should do fine.<br />
$ mkdir ~/archlive<br />
<br />
The archiso scripts that were installed to the host system earlier now need to be copied over into the newly created directory you will be working within.<br />
Archiso comes with two "profiles": releng, and baseline.<br />
If you wish to create a fully customised live version of Arch Linux, pre-installed with all your favourite programs and configurations, use "releng".<br />
If you just want to create the most basic live media, with no pre-installed packages and minimalistic configurations, then use "baseline".<br />
<br />
So, depending on your needs, execute the following, replacing 'PROFILE' with either '''releng''' or '''baseline'''.<br />
# cp -r /usr/share/archiso/configs/'''PROFILE'''/ ~/archlive<br />
<br />
If you are using the 'releng' profile to make a fully customised image, then you can proceed onto [[Archiso#Configure_our_live_medium]].<br />
<br />
If you are using the 'baseline' profile to create a bare bones, installation image, then you won't be needing to do any customisations and can proceed onto [[Archiso#Build_the_ISO]]<br />
<br />
== Setup (manual way) ==<br />
{{Note|If you have already completed Setup the 'automatic' way, using the steps above, then you do not need to read this section.}}<br />
<br />
Setup a base filesystem<br />
# mkarchiso init<br />
<br />
Install other packages (optional)<br />
# mkarchiso -p "pkg1 pkg2 pkg3 ... pkgN" install<br />
<br />
At this point, customize anything that you want in root-image, then exit when done.<br />
<br />
# mkarchiso -r "bash" run<br />
<br />
Setup initramfs image.<br />
Copy needed hooks to root-image<br />
<br />
# cp /usr/lib/initcpio/hooks/archiso work/root-image/usr/lib/initcpio/hooks<br />
# cp /usr/lib/initcpio/install/archiso work/root-image/usr/lib/initcpio/install<br />
<br />
Create a config for mkinitcpio '''work/root-image/etc/mkinitcpio-archiso.conf'''<br />
HOOKS="base udev archiso pata scsi sata usb fw filesystems usbinput"<br />
COMPRESSION="xz"<br />
<br />
Create a folder named as your PC's architecture, and generate the initramfs image:<br />
# mkdir work/root-image/boot/i686<br />
# mkarchiso -r "mkinitcpio -c /etc/mkinitcpio-archiso.conf -k /boot/vmlinuz-linux -g /boot/i686/archiso.img" run<br />
<br />
Move kernel/initramfs to boot/<br />
# mkdir -p work/iso/arch/boot/i686<br />
# mv work/root-image/boot/vmlinuz-linux work/iso/arch/boot/i686/vmlinuz<br />
# mv work/root-image/boot/i686/archiso.img work/iso/arch/boot/i686/archiso.img<br />
<br />
Setup syslinux<br />
<br />
Create a directory for it.<br />
# mkdir -p work/iso/arch/boot/syslinux<br />
<br />
Create a '''work/iso/arch/boot/syslinux/syslinux.cfg''' file.<br />
<br />
{{bc|1=<br />
DEFAULT menu.c32<br />
PROMPT 0<br />
MENU TITLE Arch Linux<br />
TIMEOUT 300<br />
<br />
LABEL arch<br />
MENU LABEL Arch Linux<br />
LINUX /arch/boot/i686/vmlinuz<br />
INITRD /arch/boot/i686/archiso.img<br />
APPEND archisolabel=MY_ARCH<br />
<br />
ONTIMEOUT arch<br />
}}<br />
<br />
Copy menu.c32 needed by previous config.<br />
# cp work/root-image/usr/lib/syslinux/menu.c32 work/iso/arch/boot/syslinux/<br />
<br />
Setup isolinux (optional, only needed for booteable iso)<br />
<br />
# mkdir work/iso/isolinux<br />
# cp work/root-image/usr/lib/syslinux/isolinux.bin work/iso/isolinux/<br />
# cp work/root-image/usr/lib/syslinux/isohdpfx.bin work/iso/isolinux/<br />
<br />
Create a '''work/iso/isolinux/isolinux.cfg'''<br />
{{bc|<br />
DEFAULT loadconfig<br />
<br />
LABEL loadconfig<br />
CONFIG /arch/boot/syslinux/syslinux.cfg<br />
APPEND /arch/boot/syslinux/<br />
}}<br />
<br />
Create an '''work/iso/arch/aitab''' file.<br />
# <img> <mnt> <arch> <sfs_comp> <fs_type> <fs_size><br />
root-image / i686 xz ext4 50%<br />
<br />
Build all filesystem images specified in aitab (.fs .fs.sfs .sfs)<br />
# mkarchiso prepare<br />
<br />
Generate an ISO 9660 with "El Torito" boot image (optional)<br />
# mkarchiso -L "MY_ARCH" iso "my-arch.iso"<br />
<br />
== Configure our live medium ==<br />
<br />
This section details configuring the image you will be creating, allowing you to define the packages and configurations you want your live image to contain.<br />
<br />
Change into the directory we created earlier (~/archlive/releng/ if you have been following this guide), you will see a number of files and directories; we are only concerned with a few of these, mainly: <br />
packages.* - this is where you list, line by line, the packages you want to have installed, and<br />
the root-image directory - this directory acts as an overlay and it is where you make all the customisations.<br />
<br />
=== Installing packages ===<br />
<br />
You will want to create a list of packages you want installed on your live CD system. A file full of package names, one-per-line, is the format for this. This is '''''great''''' for special interest live CDs, just specify packages you want and bake the image.<br />
Edit the packages.i686, or packages.x86_64 file depending on whether you are create a 32bit, or 64bit image, respectively.<br />
<br />
{{Tip|You can also create a '''[[custom local repository]]''' for the purpose of preparing custom packages or packages from [[AUR]]/[[ABS]]. Just add your local repository at the first position (for top priority) of your build machine's '''pacman.conf''' and you are good to go!}}<br />
<br />
=== Adding a user ===<br />
<br />
There are two methods to creating a user: either by adding the relevant useradd command to rc.local, or by copying over (and modifying) /etc/shadow, /etc/passwd, and /etc/group.<br />
The latter method shall be discussed here.<br />
<br />
Copy your /etc/shadow, /etc/passwd, and /etc/group from your '''host''' system to the /etc/ directory '''where you now working''' (which should be ~/archlive/releng/root-image/etc)<br />
e.g.<br />
# cp /etc/{shadow,passwd,group} ~/archlive/releng/root-image/etc/<br />
<br />
{{Warning|The shadow file will contain your encrypted password. I recommend before you copy the shadow file over, you change the password of your host user to that which you want your live user to have, copy the shadow file over, and then change back your password.}}<br />
<br />
=== Adding files to image ===<br />
<br />
{{Note|You must be root to do this, do not change the ownership of any of the files you copy over, '''everything''' within the root-image directory must be root owned. Proper ownerships will be sorted out shortly.}}<br />
<br />
The root-image directory acts as an overlay, think of it as root directory '/' on your current system, so any files you place within this directory will be copied over on boot-up.<br />
<br />
So if you have a set of iptables scripts on your current system you want to be used on you live image, copy them over as such:<br />
# cp -r /etc/iptables ~/archlive/releng/root-image/etc<br />
<br />
Placing files in the users home directory is a little different. Do not place them within root-image/home, but instead create a skel directory within root-image/ and place them there. We will then add the relevant commands to the rc.local we are going to create to copy them over on boot and sort out the permissions.<br />
<br />
First, create the skel directory; making sure you are within ~/archlive/releng/root-image/etc directory (if this is where you are working from):<br />
# cd ~/archlive/releng/root-image/etc && mkdir skel<br />
<br />
Now copy the 'home' files to the skel directory, again doing everything as root!<br />
e.g for .bashrc. <br />
# cp ~/.bashrc ~/archlive/releng/root-image/etc/skel/<br />
<br />
<br />
Inside the root-image/etc/ directory, create the rc.local file, and '''make sure''' you make it executable:<br />
<br />
# cd ~/archlive/releng/root-image/etc && touch rc.local && chmod +x rc.local<br />
<br />
Now add the all of following to rc.local, replacing 'youruser' with the user you specified earlier.<br />
# Create the user directory for live session<br />
if [ ! -d /home/'''youruser''' ]; then<br />
mkdir /home/'''youruser''' && chown '''youruser''' /home/'''youruser'''<br />
fi<br />
# Copy files over to home<br />
su -c "cp -r /etc/skel/.[a-zA-Z0-9]* /home/'''youruser'''/" '''youruser'''<br />
<br />
=== aitab ===<br />
<br />
The default file should work fine, so you should not need to touch it.<br />
<br />
The aitab file holds information about the filesystems images that must be created by mkarchiso and mounted at initramfs stage from the archiso hook.<br />
It consists of some fields which define the behaviour of images.<br />
<br />
# <img> <mnt> <arch> <sfs_comp> <fs_type> <fs_size><br />
<br />
; <img>: Image name without extension (.fs .fs.sfs .sfs).<br />
; <mnt>: Mount point.<br />
; <arch>: Architecture { i686 | x86_64 | any }.<br />
; <sfs_comp>: SquashFS compression type { gzip | lzo | xz }. A special value of "none" denotes no usage of SquashFS.<br />
; <fs_type>: Set the filesystem type of the image { ext4 | ext3 | ext2 | xfs }. A special value of "none" denotes no usage of a filesystem. In that case all files are pushed directly to SquashFS filesystem.<br />
; <fs_size>: An absolute value of file system image size in MiB (example: 100, 1000, 4096, etc) A relative value of file system free space [in percent] {1%..99%} (example 50%, 10%, 7%). This is an estimation, and calculated in a simple way. Space used + 10% (estimated for metadata overhead) + desired %<br />
<br />
{{Note|Some combinations are invalid. Example both sfs_comp and fs_type are set to none}}<br />
<br />
=== Boot Loader ===<br />
The default file should work fine, so you should not need to touch it.<br />
<br />
Due to the modular nature of isolinux, you are able to use lots of addons since all *.c32 files are copied and available to you. Take a look at the [http://syslinux.zytor.com/wiki/index.php/SYSLINUX official syslinux site] and the [http://projects.archlinux.org/archiso.git/tree/configs/syslinux-iso/boot-files archiso git repo]. Using said addons, it is possible to make visually attractive and complex menus. See [http://syslinux.zytor.com/wiki/index.php/Comboot/menu.c32 here].<br />
<br />
=== Finishing the root-image ===<br />
Some tips that will not be covered in this article because there are other articles on this wiki that already do, but please feel free to add them here.<br />
*Configure an ''inittab'' to start into X at boot time<br />
*Configure the ''hosts'' file<br />
*Configure ''rc.conf'' (no fancy modules required here)<br />
*Configure ''sudoers''<br />
*Configure ''rc.local''<br />
*Put additional artworks onto the medium <br />
*Put arbitrary binary stuff into opt/<br />
<br />
== Build the ISO ==<br />
<br />
Now you are ready to turn your files into the .iso which you can then burn to CD or USB:<br />
Inside the directory you are working with, either ~/archlive/releng, or ~/archlive/baseline, execute:<br />
<br />
# ./build.sh -v build single netinstall<br />
<br />
You can replace 'netinstall' with 'core' if you wish; however, doing so will cache all of the packages pacman downloads into the iso file, which will vastly inrease it's size.<br />
<br />
The script will now download and install the packages you specified to work/*/root-image, create the kernel and init images, apply your customizations and finally build the iso into out/.<br />
<br />
You can now dd the iso file onto a USB using dd, an example of which:<br />
# dd if=~/archlive/releng/out/*.iso of=/dev/sdx<br />
You will have to adjust accordingly, and make sure you choose the right output file! A simple mistake here will destory data on your harddisk.<br />
<br />
== See also ==<br />
*[http://projects.archlinux.org/?p=archiso.git;a=summary Archiso project page]<br />
*[[Archiso_as_pxe_server|Archiso as pxe server]]<br />
*[https://kroweer.wordpress.com/2011/09/07/creating-a-custom-arch-linux-live-usb Step-by-step tutorial on using ArchISO]<br />
*[http://didjix.blogspot.com/ A live DJ distribution powered by ArchLinux and built with Archiso]</div>
Whgirw
https://wiki.archlinux.org/index.php?title=Archiso&diff=215455
Archiso
2012-07-29T15:23:43Z
<p>Whgirw: /* Installing packages */</p>
<hr />
<div>[[Category:Live Arch systems]]<br />
[[el:Archiso]]<br />
[[fr:Archiso]]<br />
[[it:Archiso]]<br />
[[nl:Archiso]]<br />
[[ru:Archiso]]<br />
[[uk:Archiso]]<br />
'''Archiso''' is a small set of bash scripts that is capable of building fully functional Arch Linux based live CD and USB images. It is a very generic tool, so it could potentially be used to generate anything from rescue systems, install disks, to special interest live CD/DVD/USB systems, and who knows what else. Simply put, if it involves Arch on a shiny coaster, it can do it.<br />
The heart and soul of Archiso is mkarchiso. All of its options are documented in its usage output, so its direct usage won't be covered here. Instead, this wiki article will act as a guide for rolling your own live mediums in no time!<br />
<br />
<br />
== Setup ==<br />
<br />
Before we begin, we need to grab the archiso scripts which carry out the beef of the work for us. You can get archiso from Git (recommended) or from [https://aur.archlinux.org/packages.php?ID=25996 aur]. We also need a few packages which archiso relies on; the following commands take care of this for us:<br />
<br />
# pacman -S make patch git libisoburn squashfs-tools dosfstools rsync --needed<br />
# git clone git://projects.archlinux.org/archiso.git<br />
# make -C archiso/archiso install<br />
<br />
Create a directory to work within, this is where all the modifications to the live image will take place: ~/archlive should do fine.<br />
$ mkdir ~/archlive<br />
<br />
The archiso scripts that were installed to the host system earlier now need to be copied over into the newly created directory you will be working within.<br />
Archiso comes with two "profiles": releng, and baseline.<br />
If you wish to create a fully customised live version of Arch Linux, pre-installed with all your favourite programs and configurations, use "releng".<br />
If you just want to create the most basic live media, with no pre-installed packages and minimalistic configurations, then use "baseline".<br />
<br />
So, depending on your needs, execute the following, replacing 'PROFILE' with either '''releng''' or '''baseline'''.<br />
# cp -r /usr/share/archiso/configs/'''PROFILE'''/ ~/archlive<br />
<br />
If you are using the 'releng' profile to make a fully customised image, then you can proceed onto [[Archiso#Configure_our_live_medium]].<br />
<br />
If you are using the 'baseline' profile to create a bare bones, installation image, then you won't be needing to do any customisations and can proceed onto [[Archiso#Build_the_ISO]]<br />
<br />
== Setup (manual way) ==<br />
{{Note|If you have already completed Setup the 'automatic' way, using the steps above, then you do not need to read this section.}}<br />
<br />
Setup a base filesystem<br />
# mkarchiso init<br />
<br />
Install other packages (optional)<br />
# mkarchiso -p "pkg1 pkg2 pkg3 ... pkgN" install<br />
<br />
At this point, customize anything that you want in root-image, then exit when done.<br />
<br />
# mkarchiso -r "bash" run<br />
<br />
Setup initramfs image.<br />
Copy needed hooks to root-image<br />
<br />
# cp /usr/lib/initcpio/hooks/archiso work/root-image/usr/lib/initcpio/hooks<br />
# cp /usr/lib/initcpio/install/archiso work/root-image/usr/lib/initcpio/install<br />
<br />
Create a config for mkinitcpio '''work/root-image/etc/mkinitcpio-archiso.conf'''<br />
HOOKS="base udev archiso pata scsi sata usb fw filesystems usbinput"<br />
COMPRESSION="xz"<br />
<br />
Create a folder named as your PC's architecture, and generate the initramfs image:<br />
# mkdir work/root-image/boot/i686<br />
# mkarchiso -r "mkinitcpio -c /etc/mkinitcpio-archiso.conf -k /boot/vmlinuz-linux -g /boot/i686/archiso.img" run<br />
<br />
Move kernel/initramfs to boot/<br />
# mkdir -p work/iso/arch/boot/i686<br />
# mv work/root-image/boot/vmlinuz-linux work/iso/arch/boot/i686/vmlinuz<br />
# mv work/root-image/boot/i686/archiso.img work/iso/arch/boot/i686/archiso.img<br />
<br />
Setup syslinux<br />
<br />
Create a directory for it.<br />
# mkdir -p work/iso/arch/boot/syslinux<br />
<br />
Create a '''work/iso/arch/boot/syslinux/syslinux.cfg''' file.<br />
<br />
{{bc|1=<br />
DEFAULT menu.c32<br />
PROMPT 0<br />
MENU TITLE Arch Linux<br />
TIMEOUT 300<br />
<br />
LABEL arch<br />
MENU LABEL Arch Linux<br />
LINUX /arch/boot/i686/vmlinuz<br />
INITRD /arch/boot/i686/archiso.img<br />
APPEND archisolabel=MY_ARCH<br />
<br />
ONTIMEOUT arch<br />
}}<br />
<br />
Copy menu.c32 needed by previous config.<br />
# cp work/root-image/usr/lib/syslinux/menu.c32 work/iso/arch/boot/syslinux/<br />
<br />
Setup isolinux (optional, only needed for booteable iso)<br />
<br />
# mkdir work/iso/isolinux<br />
# cp work/root-image/usr/lib/syslinux/isolinux.bin work/iso/isolinux/<br />
# cp work/root-image/usr/lib/syslinux/isohdpfx.bin work/iso/isolinux/<br />
<br />
Create a '''work/iso/isolinux/isolinux.cfg'''<br />
{{bc|<br />
DEFAULT loadconfig<br />
<br />
LABEL loadconfig<br />
CONFIG /arch/boot/syslinux/syslinux.cfg<br />
APPEND /arch/boot/syslinux/<br />
}}<br />
<br />
Create an '''work/iso/arch/aitab''' file.<br />
# <img> <mnt> <arch> <sfs_comp> <fs_type> <fs_size><br />
root-image / i686 xz ext4 50%<br />
<br />
Build all filesystem images specified in aitab (.fs .fs.sfs .sfs)<br />
# mkarchiso prepare<br />
<br />
Generate an ISO 9660 with "El Torito" boot image (optional)<br />
# mkarchiso -L "MY_ARCH" iso "my-arch.iso"<br />
<br />
== Configure our live medium ==<br />
<br />
This section details configuring the image you will be creating, allowing you to define the packages and configurations you want your live image to contain.<br />
<br />
Change into the directory we created earlier (~/archlive/releng/ if you have been following this guide), you will see a number of files and directories; we are only concerned with a few of these, mainly: <br />
packages.* - this is where you list, line by line, the packages you want to have installed, and<br />
the root-image directory - this directory acts as an overlay and it is where you make all the customisations.<br />
<br />
=== Installing packages ===<br />
<br />
You will want to create a list of packages you want installed on your live CD system. A file full of package names, one-per-line, is the format for this. This is '''''great''''' for special interest live CDs, just specify packages you want and bake the image.<br />
Edit the packages.i686, or packages.x86_64 file depending on whether you are create a 32bit, or 64bit image, respectively.<br />
<br />
{{Tip|You can also create a '''[[Pacman_Tips#Custom_local_repository|custom local repository]]''' for the purpose of preparing custom packages or packages from [[AUR]]/[[ABS]]. Just add your local repository at the first position (for top priority) of your build machine's '''pacman.conf''' and you are good to go!}}<br />
<br />
=== Adding a user ===<br />
<br />
There are two methods to creating a user: either by adding the relevant useradd command to rc.local, or by copying over (and modifying) /etc/shadow, /etc/passwd, and /etc/group.<br />
The latter method shall be discussed here.<br />
<br />
Copy your /etc/shadow, /etc/passwd, and /etc/group from your '''host''' system to the /etc/ directory '''where you now working''' (which should be ~/archlive/releng/root-image/etc)<br />
e.g.<br />
# cp /etc/{shadow,passwd,group} ~/archlive/releng/root-image/etc/<br />
<br />
{{Warning|The shadow file will contain your encrypted password. I recommend before you copy the shadow file over, you change the password of your host user to that which you want your live user to have, copy the shadow file over, and then change back your password.}}<br />
<br />
=== Adding files to image ===<br />
<br />
{{Note|You must be root to do this, do not change the ownership of any of the files you copy over, '''everything''' within the root-image directory must be root owned. Proper ownerships will be sorted out shortly.}}<br />
<br />
The root-image directory acts as an overlay, think of it as root directory '/' on your current system, so any files you place within this directory will be copied over on boot-up.<br />
<br />
So if you have a set of iptables scripts on your current system you want to be used on you live image, copy them over as such:<br />
# cp -r /etc/iptables ~/archlive/releng/root-image/etc<br />
<br />
Placing files in the users home directory is a little different. Do not place them within root-image/home, but instead create a skel directory within root-image/ and place them there. We will then add the relevant commands to the rc.local we are going to create to copy them over on boot and sort out the permissions.<br />
<br />
First, create the skel directory; making sure you are within ~/archlive/releng/root-image/etc directory (if this is where you are working from):<br />
# cd ~/archlive/releng/root-image/etc && mkdir skel<br />
<br />
Now copy the 'home' files to the skel directory, again doing everything as root!<br />
e.g for .bashrc. <br />
# cp ~/.bashrc ~/archlive/releng/root-image/etc/skel/<br />
<br />
<br />
Inside the root-image/etc/ directory, create the rc.local file, and '''make sure''' you make it executable:<br />
<br />
# cd ~/archlive/releng/root-image/etc && touch rc.local && chmod +x rc.local<br />
<br />
Now add the all of following to rc.local, replacing 'youruser' with the user you specified earlier.<br />
# Create the user directory for live session<br />
if [ ! -d /home/'''youruser''' ]; then<br />
mkdir /home/'''youruser''' && chown '''youruser''' /home/'''youruser'''<br />
fi<br />
# Copy files over to home<br />
su -c "cp -r /etc/skel/.[a-zA-Z0-9]* /home/'''youruser'''/" '''youruser'''<br />
<br />
=== aitab ===<br />
<br />
The default file should work fine, so you should not need to touch it.<br />
<br />
The aitab file holds information about the filesystems images that must be created by mkarchiso and mounted at initramfs stage from the archiso hook.<br />
It consists of some fields which define the behaviour of images.<br />
<br />
# <img> <mnt> <arch> <sfs_comp> <fs_type> <fs_size><br />
<br />
; <img>: Image name without extension (.fs .fs.sfs .sfs).<br />
; <mnt>: Mount point.<br />
; <arch>: Architecture { i686 | x86_64 | any }.<br />
; <sfs_comp>: SquashFS compression type { gzip | lzo | xz }. A special value of "none" denotes no usage of SquashFS.<br />
; <fs_type>: Set the filesystem type of the image { ext4 | ext3 | ext2 | xfs }. A special value of "none" denotes no usage of a filesystem. In that case all files are pushed directly to SquashFS filesystem.<br />
; <fs_size>: An absolute value of file system image size in MiB (example: 100, 1000, 4096, etc) A relative value of file system free space [in percent] {1%..99%} (example 50%, 10%, 7%). This is an estimation, and calculated in a simple way. Space used + 10% (estimated for metadata overhead) + desired %<br />
<br />
{{Note|Some combinations are invalid. Example both sfs_comp and fs_type are set to none}}<br />
<br />
=== Boot Loader ===<br />
The default file should work fine, so you should not need to touch it.<br />
<br />
Due to the modular nature of isolinux, you are able to use lots of addons since all *.c32 files are copied and available to you. Take a look at the [http://syslinux.zytor.com/wiki/index.php/SYSLINUX official syslinux site] and the [http://projects.archlinux.org/archiso.git/tree/configs/syslinux-iso/boot-files archiso git repo]. Using said addons, it is possible to make visually attractive and complex menus. See [http://syslinux.zytor.com/wiki/index.php/Comboot/menu.c32 here].<br />
<br />
=== Finishing the root-image ===<br />
Some tips that will not be covered in this article because there are other articles on this wiki that already do, but please feel free to add them here.<br />
*Configure an ''inittab'' to start into X at boot time<br />
*Configure the ''hosts'' file<br />
*Configure ''rc.conf'' (no fancy modules required here)<br />
*Configure ''sudoers''<br />
*Configure ''rc.local''<br />
*Put additional artworks onto the medium <br />
*Put arbitrary binary stuff into opt/<br />
<br />
== Build the ISO ==<br />
<br />
Now you are ready to turn your files into the .iso which you can then burn to CD or USB:<br />
Inside the directory you are working with, either ~/archlive/releng, or ~/archlive/baseline, execute:<br />
<br />
# ./build.sh -v build single netinstall<br />
<br />
You can replace 'netinstall' with 'core' if you wish; however, doing so will cache all of the packages pacman downloads into the iso file, which will vastly inrease it's size.<br />
<br />
The script will now download and install the packages you specified to work/*/root-image, create the kernel and init images, apply your customizations and finally build the iso into out/.<br />
<br />
You can now dd the iso file onto a USB using dd, an example of which:<br />
# dd if=~/archlive/releng/out/*.iso of=/dev/sdx<br />
You will have to adjust accordingly, and make sure you choose the right output file! A simple mistake here will destory data on your harddisk.<br />
<br />
== See also ==<br />
*[http://projects.archlinux.org/?p=archiso.git;a=summary Archiso project page]<br />
*[[Archiso_as_pxe_server|Archiso as pxe server]]<br />
*[https://kroweer.wordpress.com/2011/09/07/creating-a-custom-arch-linux-live-usb Step-by-step tutorial on using ArchISO]<br />
*[http://didjix.blogspot.com/ A live DJ distribution powered by ArchLinux and built with Archiso]</div>
Whgirw
https://wiki.archlinux.org/index.php?title=SLiM_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=190073
SLiM (Русский)
2012-03-19T05:09:44Z
<p>Whgirw: /* Автомонтирование шифрованной /home при входе */</p>
<hr />
<div>[[Category:Русский]]<br />
{{i18n|SLiM}}<br />
<br />
=Введение=<br />
SLiM - акроним английского словосочетания Simple Login Manager (SLiM), который в переводе на русский звучит как простой менеджер входа. SLIM является простым, легко настраиваемым и может использоваться на системах с высокой и низкой производительностью. SLIM также очень удобен для тех, кто хочет менеджер входа без зависимостей от графического окружения Gnome или KDE, что делает его идеальным для пользователей, работающих с Xfce, Openbox, Fluxbox и т.д<br />
<br />
{{Note| Важно помнить, что в настоящее время нет команды отображения меню в SLIM. Нужно запомнить стандартные команды, перечисленые в [[SLiM (Русский)#Выключение, перезагрузка, режим сна, выход, запуск терминала из SLIM | "Выключение, перезагрузка,...."]] и т.д. Эти команды используются в поле Имя пользователя, которое всегда отображается.}}<br />
<br />
=Установка=<br />
SLiM доступен в репозиториях<br />
# pacman -S slim<br />
Есть также пакет тем<br />
# pacman -S slim-themes<br />
и тема для Arch Linux<br />
# pacman -S archlinux-themes-slim<br />
<br />
=Конфигурация=<br />
<br />
==Включение SLIM==<br />
Обратитесь к [[добавление_экранного_менеджера_входа_в_систему_(KDM,_GDM_или_XDM)_в_автозагрузку | добавлению менеджера входа (KDM, GDM, или XDM) для автоматической загрузки при старте]].<br />
<br />
Самый простой вариант : <br />
В файле /etc/inittab закомментировать строку<br />
id:3:initdefault:<br />
, раскомментировать<br />
id:5:initdefault:<br />
И дописать<br />
x:5:respawn:/usr/bin/slim >/dev/null 2>&1<br />
<br />
==Одиночные Среды==<br />
<br />
Чтобы настроить SLIM загрузить определенную среду, просто отредактируйте '''~/.xinitrc''' чтобы он выглядел следующим образом:<br />
<br />
<pre><br />
#!/bin/sh<br />
<br />
#<br />
# ~/.xinitrc<br />
#<br />
# Executed by startx (запустите ваш оконный менеджер отсюда)<br />
#<br />
<br />
exec [команда сеанса]<br />
</pre><br />
<br />
*Примечание: Если у вас нет файла ~/.xinitrc, вы можете создать его (например с помощью nano). По умолчанию slim ищет этот файл для всех пользователей и будет жаловаться "что не может выполнить команду login " если нет такого файла в домашнем каталоге пользователя.<br />
<br />
Замените '''''[команду сеанса]''''' соответствующей командой вашей вашего сеанса.Для примера:<br />
<br />
Для запуска Openbox: <br />
exec openbox-session<br />
<br />
Для запуска Fluxbox: <br />
exec fluxbox<br />
или<br />
exec startfluxbox<br />
<br />
Для запуска Xfce: <br />
exec startxfce4<br />
<br />
Для запуска GNOME: <br />
exec gnome-session<br />
<br />
Для запуска KDE: <br />
exec startkde<br />
<br />
Для запуска FVWM2: <br />
exec fvwm2<br />
<br />
Для запуска FVWM-crystal: <br />
exec fvwm-crystal<br />
<br />
Для запуска Awesome: <br />
exec awesome<br />
<br />
Для запуска Enlightenment<br />
exec enlightenment_start<br />
<br />
Если ваше рабочее окружение, не перечислено здесь, обратитесь к документации по программному обеспечению<br />
<br />
==Автоматический вход==<br />
Для того, чтобы сделать возможным автоматический вход в систему(без ввода пароля), необходимо раскомментировать следующие строки в /etc/slim.conf<br />
# default_user simone<br />
Раскомментируйте эту строку и замените simone на имя Вашего пользователя.<br />
# auto_login no<br />
Расскоментируйте эту строку и замените no на yes. Это позволит использовать автоматический вход.<br />
<br />
==PolicyKit==<br />
Если у вас возникли проблемы с PolicyKit запустите ConsoleKit ''ck-launch-session'':<br />
<pre><br />
#!/bin/sh<br />
<br />
#<br />
# ~/.xinitrc<br />
#<br />
# Executed by startx (запустите ваш оконный менеджер отсюда)<br />
#<br />
<br />
exec ck-launch-session [команда сеанса]<br />
</pre><br />
<br />
==Выбор окружения==<br />
Экспериментальная возможность.<br />
Если вам нужна возможность выбора окружения рабочего стола из списка, SLiM нужно настроить следующим образом.<br />
<br />
Поместите правило, подобное этому в ваш файл ~/.xinitrc и отредактируйте переменную сесий в /etc/slim.conf, соответственно именам ваших сессий. Вы можете выбрать рабочее окружение во времени входа нажав F1.<br />
<br />
<pre><br />
# сессия, которая начнётся если пользователь не выбрал рабочее окружение<br />
DEFAULT_SESSION=twm<br />
<br />
case $1 in<br />
kde)<br />
exec startkde<br />
;;<br />
xfce4)<br />
exec startxfce4<br />
;;<br />
icewm)<br />
icewmbg &<br />
icewmtray &<br />
exec icewm<br />
;;<br />
wmaker)<br />
exec wmaker<br />
;;<br />
blackbox)<br />
exec blackbox<br />
;;<br />
*)<br />
exec $DEFAULT_SESSION<br />
;;<br />
esac<br />
</pre><br />
Скачать: http://svn.berlios.de/svnroot/repos/slim/trunk/xinitrc.sample<br />
<br />
Документация Slim: http://slim.berlios.de/manual.php<br />
<br />
==Темы==<br />
Установка тем для Slim:<br />
# pacman -S slim-themes archlinux-themes-slim<br />
<br />
<tt>archlinux-themes-slim</tt> пакеты содержат различные темы.Проверте <tt>/usr/share/slim/themes</tt> чтобы увидеть доступные темы и просмотреть их.<br />
<br />
Измените строку current_theme в /etc/slim.conf из "default" на название темы на ваш выбор: <br />
# nano /etc/slim.conf<br />
<br />
#current_theme default<br />
current_theme archlinux-simplyblack<br />
<br />
Для предварительного просмотра тем, если не установлен Xorg server, выполните команду:<br />
slim -p /usr/share/slim/themes/<theme name><br />
<br />
Для того, чтобы закрыть просмотр, наберите "exit" в поле логина и нажмите Enter.<br />
Дополнительные пакеты тем могут быть найдены в [http://wiki.archlinux.org/index.php/AUR AUR].<br />
<br />
= Советы и Хитрости =<br />
==Изменение курсора==<br />
Если вам не нравится курсор "Х", и вы хотите его изменить, например на стрелку, используйте [http://aur.archlinux.org/packages.php?ID=21053 slim-cursor пакет из AUR].<br />
<br />
После установки, отредактируйте / ETC / slim.conf и раскомментируйте строку:<br />
cursor left_ptr<br />
Это даст вам нормальную стрелку взамен. Эти настройки сделаны для курсора xsetroot .Вы можете посмотреть доступные курсоры [http://cvsweb.xfree86.org/cvsweb/*checkout*/xc/lib/X11/cursorfont.h?rev=HEAD&content-type=text/plain здесь] или в /usr/share/icons/<your-cursor-theme>/cursors/.<br />
<br />
Для того, чтобы изменять тему курсора на экране входа, добавьте в фаил /usr/share/icons/default/index.theme следующее содержание:<br />
[Icon Theme]<br />
Inherits=<your-cursor-theme><br />
Замените <your-cursor-theme> на имя темы курсоров которую вы хотите использовать, например whiteglass.<br />
<br />
==Общие темы для Slim и Рабочего Стола==<br />
Простой способ обмена темами между Slim и вашим рабочим столом, это создание символической ссылки от вашего файла тем рабочего стола до дефолтной темы в Slim.<br />
# mv /usr/share/slim/themes/default/background.jpg /usr/share/slim/themes/default/background.old.jpg<br />
# ln -s /path/to/mywallpaper.jpg /usr/share/slim/themes/default/background.jpg<br />
Теперь ваши темы, обои Slim и рабочего стола будут одинаковыми,будет видно сглаживание и переход при загрузке настольной системы. (Вы должны держать дефолтную тему в файле настроек /etc/slim.conf чтобы этот трюк работал)<br />
<br />
==Выключение, перезагрузка, режим сна, выход, запуск терминала из SLIM==<br />
Вы можете выключать, перезагружать, выходить, и даже запускать терминал с экрана входа SLIM.Для этого введите соответствующее значение в поле имя пользователя и пароля, в поле пароля:<br />
<br />
* Для того, чтобы запускать терминал, введите '''console''' как имя пользователя(устанавливается по умолчанию на xterm, которое должно настраиваться отдельно.В файле <tt>/etc/slim.conf</tt> можно изменить предпочитаемый терминал)<br />
* Для выключения, введите '''halt''' как имя пользователя<br />
* Для перезагрузки, введите '''reboot''' как имя пользователя<br />
* Для выхода, введите '''exit''' как имя пользователя<br />
* Для режима сна, введите '''suspend''' как имя пользователя (Suspend отключён по умолчанию, отредактируйте <tt>/etc/slim.conf</tt> раскомментируйте строку <tt>suspend_cmd</tt> , если необходимо модифицировать приостановить саму команду (e.g. change '''''/usr/sbin/suspend''''' to '''''sudo /usr/sbin/pm-suspend'''''))<br />
<br />
==Ошибка с выключением заставки==<br />
Если вы используете заставку и slim,и иногда вы не можете выключить или перезагрузить из меню в gnome, xfce, lxde or others. и т.д<br />
Проверьте ваши файлы настроек /etc/slim.conf и /etc/splash.conf, установите DEFAULT_TTY=7 также, как xserver_arguments vt07.<br />
<br />
==Информация сесий в Slim==<br />
По умолчанию, Slim не регистрирует сесии в utmp и wtmp какие причины, кто, последний раз.. на недостоверную информацию.<br />
Чтобы это исправить, отредактируйте ваш slim.conf следующим образом:<br />
<br />
sessionstart_cmd /usr/bin/sessreg -a -l $DISPLAY %user<br />
sessionstop_cmd /usr/bin/sessreg -d -l $DISPLAY %user<br />
<br />
==Настройка DPI в Slim==<br />
Если вы установили DPI с аргументом -dpi 96 in /etc/X11/xinit/xserverrc и это не работает со slim. Отредактируйте ваш slim.conf следующим образом:<br />
xserver_arguments -nolisten tcp vt07 <br />
to<br />
xserver_arguments -nolisten tcp vt07 -dpi 96<br />
<br />
==Используйте случайные темы==<br />
Используйте current_theme переменную как запятую, для разделения списка произвольного набора тем.<br />
<br />
==Автомонтирование шифрованной /home при входе в систему==<br />
Можете использовать [https://wiki.archlinux.org/index.php/Pam_mount#Slim pam_mount]<br />
<br />
Пример файла /etc/pam.d/slim:<br />
<br />
auth requisite pam_nologin.so<br />
auth required pam_env.so<br />
auth required pam_unix.so<br />
auth required pam_ecryptfs.so unwrap<br />
auth optional pam_mount.so<br />
account required pam_unix.so<br />
password required pam_ecryptfs.so<br />
password required pam_unix.so<br />
password optional pam_mount.so<br />
session required pam_limits.so<br />
session required pam_unix.so<br />
session optional pam_mount.so<br />
session optional pam_loginuid.so<br />
session optional pam_ck_connector.so<br />
<br />
= См. также =<br />
*[[Добавление менеджера входа (KDM, GDM, or XDM) для автоматической загрузки при старте]]<br />
<br />
= Ссылки =<br />
*[http://slim.berlios.de/ SLiM домашняя страница]</div>
Whgirw
https://wiki.archlinux.org/index.php?title=SLiM_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=189952
SLiM (Русский)
2012-03-18T19:46:19Z
<p>Whgirw: </p>
<hr />
<div>[[Category:Русский]]<br />
{{i18n|SLiM}}<br />
<br />
=Введение=<br />
SLiM - акроним английского словосочетания Simple Login Manager (SLiM), который в переводе на русский звучит как простой менеджер входа. SLIM является простым, легко настраиваемым и может использоваться на системах с высокой и низкой производительностью. SLIM также очень удобен для тех, кто хочет менеджер входа без зависимостей от графического окружения Gnome или KDE, что делает его идеальным для пользователей, работающих с Xfce, Openbox, Fluxbox и т.д<br />
<br />
{{Note| Важно помнить, что в настоящее время нет команды отображения меню в SLIM. Нужно запомнить стандартные команды, перечисленые в [[SLiM (Русский)#Выключение, перезагрузка, режим сна, выход, запуск терминала из SLIM | "Выключение, перезагрузка,...."]] и т.д. Эти команды используются в поле Имя пользователя, которое всегда отображается.}}<br />
<br />
=Установка=<br />
SLiM доступен в репозиториях<br />
# pacman -S slim<br />
Есть также пакет тем<br />
# pacman -S slim-themes<br />
и тема для Arch Linux<br />
# pacman -S archlinux-themes-slim<br />
<br />
=Конфигурация=<br />
<br />
==Включение SLIM==<br />
Обратитесь к [[добавление_экранного_менеджера_входа_в_систему_(KDM,_GDM_или_XDM)_в_автозагрузку | добавлению менеджера входа (KDM, GDM, или XDM) для автоматической загрузки при старте]].<br />
<br />
Самый простой вариант : <br />
В файле /etc/inittab закомментировать строку<br />
id:3:initdefault:<br />
, раскомментировать<br />
id:5:initdefault:<br />
И дописать<br />
x:5:respawn:/usr/bin/slim >/dev/null 2>&1<br />
<br />
==Одиночные Среды==<br />
<br />
Чтобы настроить SLIM загрузить определенную среду, просто отредактируйте '''~/.xinitrc''' чтобы он выглядел следующим образом:<br />
<br />
<pre><br />
#!/bin/sh<br />
<br />
#<br />
# ~/.xinitrc<br />
#<br />
# Executed by startx (запустите ваш оконный менеджер отсюда)<br />
#<br />
<br />
exec [команда сеанса]<br />
</pre><br />
<br />
*Примечание: Если у вас нет файла ~/.xinitrc, вы можете создать его (например с помощью nano). По умолчанию slim ищет этот файл для всех пользователей и будет жаловаться "что не может выполнить команду login " если нет такого файла в домашнем каталоге пользователя.<br />
<br />
Замените '''''[команду сеанса]''''' соответствующей командой вашей вашего сеанса.Для примера:<br />
<br />
Для запуска Openbox: <br />
exec openbox-session<br />
<br />
Для запуска Fluxbox: <br />
exec fluxbox<br />
или<br />
exec startfluxbox<br />
<br />
Для запуска Xfce: <br />
exec startxfce4<br />
<br />
Для запуска GNOME: <br />
exec gnome-session<br />
<br />
Для запуска KDE: <br />
exec startkde<br />
<br />
Для запуска FVWM2: <br />
exec fvwm2<br />
<br />
Для запуска FVWM-crystal: <br />
exec fvwm-crystal<br />
<br />
Для запуска Awesome: <br />
exec awesome<br />
<br />
Для запуска Enlightenment<br />
exec enlightenment_start<br />
<br />
Если ваше рабочее окружение, не перечислено здесь, обратитесь к документации по программному обеспечению<br />
<br />
==Автоматический вход==<br />
Для того, чтобы сделать возможным автоматический вход в систему(без ввода пароля), необходимо раскомментировать следующие строки в /etc/slim.conf<br />
# default_user simone<br />
Раскомментируйте эту строку и замените simone на имя Вашего пользователя.<br />
# auto_login no<br />
Расскоментируйте эту строку и замените no на yes. Это позволит использовать автоматический вход.<br />
<br />
==PolicyKit==<br />
Если у вас возникли проблемы с PolicyKit запустите ConsoleKit ''ck-launch-session'':<br />
<pre><br />
#!/bin/sh<br />
<br />
#<br />
# ~/.xinitrc<br />
#<br />
# Executed by startx (запустите ваш оконный менеджер отсюда)<br />
#<br />
<br />
exec ck-launch-session [команда сеанса]<br />
</pre><br />
<br />
==Выбор окружения==<br />
Экспериментальная возможность.<br />
Если вам нужна возможность выбора окружения рабочего стола из списка, SLiM нужно настроить следующим образом.<br />
<br />
Поместите правило, подобное этому в ваш файл ~/.xinitrc и отредактируйте переменную сесий в /etc/slim.conf, соответственно именам ваших сессий. Вы можете выбрать рабочее окружение во времени входа нажав F1.<br />
<br />
<pre><br />
# сессия, которая начнётся если пользователь не выбрал рабочее окружение<br />
DEFAULT_SESSION=twm<br />
<br />
case $1 in<br />
kde)<br />
exec startkde<br />
;;<br />
xfce4)<br />
exec startxfce4<br />
;;<br />
icewm)<br />
icewmbg &<br />
icewmtray &<br />
exec icewm<br />
;;<br />
wmaker)<br />
exec wmaker<br />
;;<br />
blackbox)<br />
exec blackbox<br />
;;<br />
*)<br />
exec $DEFAULT_SESSION<br />
;;<br />
esac<br />
</pre><br />
Скачать: http://svn.berlios.de/svnroot/repos/slim/trunk/xinitrc.sample<br />
<br />
Документация Slim: http://slim.berlios.de/manual.php<br />
<br />
==Темы==<br />
Установка тем для Slim:<br />
# pacman -S slim-themes archlinux-themes-slim<br />
<br />
<tt>archlinux-themes-slim</tt> пакеты содержат различные темы.Проверте <tt>/usr/share/slim/themes</tt> чтобы увидеть доступные темы и просмотреть их.<br />
<br />
Измените строку current_theme в /etc/slim.conf из "default" на название темы на ваш выбор: <br />
# nano /etc/slim.conf<br />
<br />
#current_theme default<br />
current_theme archlinux-simplyblack<br />
<br />
Для предварительного просмотра тем, если не установлен Xorg server, выполните команду:<br />
slim -p /usr/share/slim/themes/<theme name><br />
<br />
Для того, чтобы закрыть просмотр, наберите "exit" в поле логина и нажмите Enter.<br />
Дополнительные пакеты тем могут быть найдены в [http://wiki.archlinux.org/index.php/AUR AUR].<br />
<br />
= Советы и Хитрости =<br />
==Изменение курсора==<br />
Если вам не нравится курсор "Х", и вы хотите его изменить, например на стрелку, используйте [http://aur.archlinux.org/packages.php?ID=21053 slim-cursor пакет из AUR].<br />
<br />
После установки, отредактируйте / ETC / slim.conf и раскомментируйте строку:<br />
cursor left_ptr<br />
Это даст вам нормальную стрелку взамен. Эти настройки сделаны для курсора xsetroot .Вы можете посмотреть доступные курсоры [http://cvsweb.xfree86.org/cvsweb/*checkout*/xc/lib/X11/cursorfont.h?rev=HEAD&content-type=text/plain здесь] или в /usr/share/icons/<your-cursor-theme>/cursors/.<br />
<br />
Для того, чтобы изменять тему курсора на экране входа, добавьте в фаил /usr/share/icons/default/index.theme следующее содержание:<br />
[Icon Theme]<br />
Inherits=<your-cursor-theme><br />
Замените <your-cursor-theme> на имя темы курсоров которую вы хотите использовать, например whiteglass.<br />
<br />
==Общие темы для Slim и Рабочего Стола==<br />
Простой способ обмена темами между Slim и вашим рабочим столом, это создание символической ссылки от вашего файла тем рабочего стола до дефолтной темы в Slim.<br />
# mv /usr/share/slim/themes/default/background.jpg /usr/share/slim/themes/default/background.old.jpg<br />
# ln -s /path/to/mywallpaper.jpg /usr/share/slim/themes/default/background.jpg<br />
Теперь ваши темы, обои Slim и рабочего стола будут одинаковыми,будет видно сглаживание и переход при загрузке настольной системы. (Вы должны держать дефолтную тему в файле настроек /etc/slim.conf чтобы этот трюк работал)<br />
<br />
==Выключение, перезагрузка, режим сна, выход, запуск терминала из SLIM==<br />
Вы можете выключать, перезагружать, выходить, и даже запускать терминал с экрана входа SLIM.Для этого введите соответствующее значение в поле имя пользователя и пароля, в поле пароля:<br />
<br />
* Для того, чтобы запускать терминал, введите '''console''' как имя пользователя(устанавливается по умолчанию на xterm, которое должно настраиваться отдельно.В файле <tt>/etc/slim.conf</tt> можно изменить предпочитаемый терминал)<br />
* Для выключения, введите '''halt''' как имя пользователя<br />
* Для перезагрузки, введите '''reboot''' как имя пользователя<br />
* Для выхода, введите '''exit''' как имя пользователя<br />
* Для режима сна, введите '''suspend''' как имя пользователя (Suspend отключён по умолчанию, отредактируйте <tt>/etc/slim.conf</tt> раскомментируйте строку <tt>suspend_cmd</tt> , если необходимо модифицировать приостановить саму команду (e.g. change '''''/usr/sbin/suspend''''' to '''''sudo /usr/sbin/pm-suspend'''''))<br />
<br />
==Ошибка с выключением заставки==<br />
Если вы используете заставку и slim,и иногда вы не можете выключить или перезагрузить из меню в gnome, xfce, lxde or others. и т.д<br />
Проверьте ваши файлы настроек /etc/slim.conf и /etc/splash.conf, установите DEFAULT_TTY=7 также, как xserver_arguments vt07.<br />
<br />
==Информация сесий в Slim==<br />
По умолчанию, Slim не регистрирует сесии в utmp и wtmp какие причины, кто, последний раз.. на недостоверную информацию.<br />
Чтобы это исправить, отредактируйте ваш slim.conf следующим образом:<br />
<br />
sessionstart_cmd /usr/bin/sessreg -a -l $DISPLAY %user<br />
sessionstop_cmd /usr/bin/sessreg -d -l $DISPLAY %user<br />
<br />
==Настройка DPI в Slim==<br />
Если вы установили DPI с аргументом -dpi 96 in /etc/X11/xinit/xserverrc и это не работает со slim. Отредактируйте ваш slim.conf следующим образом:<br />
xserver_arguments -nolisten tcp vt07 <br />
to<br />
xserver_arguments -nolisten tcp vt07 -dpi 96<br />
<br />
==Используйте случайные темы==<br />
Используйте current_theme переменную как запятую, для разделения списка произвольного набора тем.<br />
<br />
==Автомонтирование шифрованной /home при входе==<br />
Можете использовать [https://wiki.archlinux.org/index.php/Pam_mount#Slim pam_mount]<br />
<br />
Пример файла /etc/pam.d/slim:<br />
<br />
auth requisite pam_nologin.so<br />
auth required pam_env.so<br />
auth required pam_unix.so<br />
auth required pam_ecryptfs.so unwrap<br />
auth optional pam_mount.so<br />
account required pam_unix.so<br />
password required pam_ecryptfs.so<br />
password required pam_unix.so<br />
password optional pam_mount.so<br />
session required pam_limits.so<br />
session required pam_unix.so<br />
session optional pam_mount.so<br />
session optional pam_loginuid.so<br />
session optional pam_ck_connector.so<br />
<br />
<br />
= См. также =<br />
*[[Добавление менеджера входа (KDM, GDM, or XDM) для автоматической загрузки при старте]]<br />
<br />
= Ссылки =<br />
*[http://slim.berlios.de/ SLiM домашняя страница]</div>
Whgirw
https://wiki.archlinux.org/index.php?title=User_talk:Vadik&diff=175872
User talk:Vadik
2011-12-25T19:33:32Z
<p>Whgirw: Created page with "{{bc|>Тем не менее необходимо внести в файл /etc/locale.conf следующие строки: Зачем? [vadik@arch ~]$ cat /etc/locale.conf c..."</p>
<hr />
<div>{{bc|>Тем не менее необходимо внести в файл /etc/locale.conf следующие строки:<br />
Зачем?<br />
[vadik@arch ~]$ cat /etc/locale.conf<br />
cat: /etc/locale.conf: Нет такого файла или каталога<br />
Система полностью локализована (и консоль и ДЕ).}}<br />
Ну мож тем, у кого не DE будет полезно. У меня jwm, и локаль работает только таким образом</div>
Whgirw
https://wiki.archlinux.org/index.php?title=Localization_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=175865
Localization (Русский)
2011-12-25T17:26:14Z
<p>Whgirw: /* Настройка консоли */</p>
<hr />
<div>[[Category:Русский]]<br />
{{i18n|Internationalisation}}<br />
<br />
= Об этой статье =<br />
Эта статья рассказывает о том, как настроить отображение и ввод русского языка в Arch Linux.<br />
<br />
= Настройка локали =<br />
<br />
В файле /etc/locale.gen раскомментируйте следующую строку:<br />
<br />
<pre><br />
ru_RU.UTF-8 UTF-8<br />
</pre><br />
<br />
<br />
Создайте выбранную вами локаль командой:<br />
<pre><br />
/usr/sbin/locale-gen<br />
</pre><br />
<br />
<br />
Проверьте, что все заявленные локали были созданы:<br />
<pre><br />
locale -a<br />
</pre><br />
<br />
= Настройка консоли = <br />
Несколько слов о том как работает консоль. <br />
<br />
Любой вывод программы перенаправляется консольному драйверу в ядре. Ядро работает только в кодировке unicode. Если программа не использует utf-8 для вывода текста, необходима таблица ACM (Application Character Map), которая будет выполнять соответствующее преобразование из 8-битной кодироки в unicode. Если используется пакет kbd (в arch он устанавливается по умолчанию), то эту таблицу можно найти по адресу /usr/share/kbd/consoletrans. <br />
<br />
Далее ядро должно отобразить символ на экране. Таблица соответствия знаков шрифта кодам unicode называется SFM (Screen Font Map). Она либо находится внутри шрифта (в большинстве случаев) либо подгружается дополнительно (из /usr/share/kbd/unimaps). Сами шрифты располагаются в /usr/share/kbd/consolefonts. <br />
<br />
Кроме этого, нужна ещё клавиатурная раскладка - таблица по переводу скан-кодов клавиатуры в нужный код символа (соответственно может быть либо старая 8 битная либо новая unicode).<br />
<br />
Таким образом, работа по настройке консоли разбивается на пункты (рассмотрен utf вариант)<br />
<br />
1. Найти нормальную клавиатурную раскладку, поддерживающую unicode и ваши любимые способы переключения языков и указать её как KEYMAP="..." в файле rc.conf.<br />
<br />
2. Установить экранный шрифт, имеющий встроенную таблицу SFM и приличное начертание: CONSOLEFONT="...".<br />
<br />
3. Убедиться что необходимость в ACM пропадает (CONSOLEMAP="" - остаётся пустым).<br />
<br />
Вся остальная работа по настройке kbd (типа использования утилит loadkeys и setfont) уже сделана известными людьми, написавшими стартовые файлы системы.<br />
<br />
Пакет kbd поддерживает русские раскладки в utf8. Дополнительные раскладки клавиатуры можно получить установив пакет kbd-ru-keymaps командой<br />
<br />
<pre>pacman -S kbd-ru-keymaps</pre><br />
<br />
или cкачав одну из раскладкок вручную:<br />
<br />
*[http://mlclm.narod.ru/ru-utf.map.gz Русская UTF-8 раскладка клавиатуры с переключением по правой клавише Alt]<br />
*[http://moose.ylsoftware.com/gentoo.ru/ru-mab.map.gz Русская UTF-8 раскладка клавиатуры с переключением по Ctrl-Shift]<br />
<br />
и поместив их в каталог '''/usr/share/kbd/keymaps/i386/qwerty'''<br />
<br />
<br />
Установите шрифт Terminus из репозитория '''community''':<br />
<pre> pacman -S terminus-font</pre><br />
<br />
<br />
Отредактируйте файл /etc/rc.conf :<br />
<br />
<pre>LOCALE="ru_RU.UTF-8"<br />
KEYMAP="ru" # Или ru-mab для раскладки с переключением по Ctrl-Shift<br />
CONSOLEFONT=ter-v16f # Можно поэкспериментировать с другими шрифтами ter-v* из /usr/share/kbd/consolefonts<br />
CONSOLEMAP=""<br />
</pre><br />
<br />
Обратите внимание, что поиск шрифта происходит в /usr/share/kbd/consolefont. При этом после установки многих шрифтов, например, terminus, файлы шрифтов хоть и попадают туда автоматически, но имеют неподдерживаемое расширение psf.gz. Чтобы определенный в переменной CONSOLEFONT шрифт был найден, необходимо переименовать файл шрифта, чтобы его расширение было psfu.gz. Например:<br />
<pre> cp /usr/share/kbd/consolefont/ter-v16f.psf.gz /usr/share/kbd/consolefont/ter-v16f.psfu.gz</pre><br />
<br />
Можно обойтись и без terminus, установив:<br />
CONSOLEFONT=/usr/share/kbd/consolefonts/cyr-sun16<br />
<br />
{{Note|Обратите внимание, что значение ''<nowiki>LOCALE=</nowiki>'' может быть как ''"ru_RU.UTF-8"'', так и ''"ru_RU.utf-8"'' или ''"ru_RU.utf8"''. Но, с целью уменьшения путаницы, все же лучше использовать вариант ''<nowiki>LOCALE=</nowiki>"ru_RU.UTF-8"''.}}<br />
<br />
Можно обойтись без установки пакета kbd-ru-keymaps, вариант с переключение Ctrl+Shift:<br />
<pre>LOCALE="ru_RU.UTF-8"<br />
HARDWARECLOCK="UTC"<br />
TIMEZONE="Europe/Moscow"<br />
KEYMAP="ru"<br />
CONSOLEFONT="ruscii_8x16"<br />
CONSOLEMAP=""<br />
USECOLOR="yes"</pre><br />
{{Note|Текущая версия initscripts не требует наличия в rc.conf переменной ''LOCALE''. Тем не менее необходимо внести в файл /etc/locale.conf следующие строки:}}<br />
<pre>LANG=ru_RU.UTF-8<br />
LC_MESSAGES=ru_RU.UTF-8</pre><br />
<br />
= Настройка X.org =<br />
Установите шрифты ttf-dejavu и ttf-liberation из репозитория '''community''':<br />
<pre>pacman -S ttf-dejavu ttf-liberation</pre><br />
== Настройки клавиатуры ==<br />
<br />
(Начиная с версии Xorg 1.8 [[HAL|HAL]] не используется для настройки)<br />
Создайте файл /etc/hal/fdi/policy/10-keymap.fdi такого содержания:<br />
<br />
<pre><br />
<?xml version="1.0" encoding="utf-8"?><br />
<deviceinfo version="0.2"><br />
<device><br />
<match key="info.capabilities" contains="input.keypad"><br />
<merge key="input.xkb.rules" type="string">base</merge><br />
<merge key="input.xkb.model" type="string">pc105</merge><br />
<merge key="input.x11_driver" type="string">evdev</merge><br />
<merge key="input.xkb.layout" type="string">us,ru</merge><br />
<merge key="input.xkb.variant" type="string">,winkeys</merge><br />
<merge key="input.xkb.options" type="string">grp:rctrl_toggle</merge><br />
</match><br />
</device><br />
</deviceinfo><br />
</pre><br />
<br />
Это простой пример, подходящий для владельцев стандартных устройств ввода. Для владельцев лэптопов, подключающих, допустим, выносную клавиатуру, правила будут сложнее.<br />
<br />
=== Модель клавиатуры ===<br />
<br />
Модель Вашей клавиатуры указана в ключе input.xkb.model. Различные значения для этого ключа можно увидеть в ''/usr/share/X11/xkb/rules/evdev.lst''. В данном примере модель pc105 - стандартная клавиатура.<br />
Например, для клавиатуры Logitech Generic Keyboard строка примет вид <br />
<merge key="input.xkb.model" type="string">logitech_base</merge><br />
<br />
=== Опции раскладок ===<br />
<br />
Параметры ''xkb.layout'' и ''xkb.variant'' указывают соответственно на варианты раскладки. В примере раскладки ''us,ru'' дополнены опцией ''winkeys'' которая расставляет знаки препинания и некоторые символы в соответствии с раскладкой win.<br />
<br />
=== Переключение раскладок ===<br />
<br />
Для настройки переключения между двумя раскладками, используйте опцию значение ключа input.xkb.options. В примере переключение осуществляется по правому Ctrl.<br />
Другой пример: раскладки переключаются комбинацией Ctrl-Shift, при использовании русской раскладки горит лампочка Scroll Lock. , строка опций должна выглядеть следующим образом:<br />
<br />
<merge key="input.xkb.options" type="string">grp:ctrl_shift_toggle,grp_led:scroll</merge><br />
<br />
Возможно будет удобно использовать <Menu> для переключения раскладок и поменять CapsLock и левый Ctrl. Тогда нужно написать так: <br />
<br />
<merge key="input.xkb.options" type="string">grp:menu_toggle,grp_led:scroll,ctrl:swapcaps</merge><br />
<br />
=== Переключение раскладок средствами X.org ===<br />
<br />
Описано на странице [[Xorg_%28%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9%29#.D0.9D.D0.B0.D1.81.D1.82.D1.80.D0.BE.D0.B9.D0.BA.D0.B8_.D0.BA.D0.BB.D0.B0.D0.B2.D0.B8.D0.B0.D1.82.D1.83.D1.80.D1.8B|Xorg (Русский)]]<br />
<br />
==Compose-последовательности==<br />
С помощью клавиши «Compose» можно вводить практически все варианты символов с акцентами, а также разные специальные символы, например кавычки или тире «—», которых нет в стандартных раскладках.<br />
Для этого<br />
* Добавьте в xorg.conf опцию<br />
<pre>Option "XkbOptions" "compose:menu"</pre><br />
* Присвойте переменным окружения GTK_IM_MODULE и QT_IM_MODULE значение xim. Если этот шаг пропустить, все последующие настройки на GTK приложения распространяться не будут (они будут использовать свой метод ввода).<br />
* После этого можно создать в домашнем каталоге файл ~/.XCompose. Первой его строчкой можно включить все стандартные комбинации клавиш:<br />
<pre>include "/usr/share/X11/locale/en_US.UTF-8/Compose"</pre><br />
:а затем можно и задать любые дополнительные последовательности (по образцу как в /usr/share/X11/locale/en_US.UTF-8/Compose). Например,<br />
<pre><br />
<Multi_key> <period> <space> : "…" U2026 # HORIZONTAL ELLIPSIS, многоточие<br />
<Multi_key> <apostrophe> <apostrophe> : "́" U0301 # ударение<br />
</pre><br />
<br />
После этого стало возможным набирать много интересных символов, нажимая вначале клавишу Compose, а потом набирая ту или короткую иную последовательность. Например,<br />
:Compose + O + C даёт © (символ авторского права),<br />
:Compose + O + R даёт ®<br />
[http://webcvs.freedesktop.org/xorg/xc/nls/Compose/en_US.UTF-8?view=co Полный список последовательностей.]<br />
Пример .XCompose:<br />
<pre><br />
# -*- coding: utf-8 -*-<br />
#<br />
# .XCompose<br />
#<br />
# $Id: .XCompose,v 1.31 2008/09/18 17:57:14 deskpot Exp $<br />
<br />
#<br />
# Quotation marks<br />
#<br />
<Multi_key> <Cyrillic_be> : "«" guillemotleft # LEFT DOUBLE ANGLE QUOTATION<br />
<Multi_key> <comma> : "«" guillemotleft # LEFT DOUBLE ANGLE QUOTATION<br />
<Multi_key> <Cyrillic_yu> : "»" guillemotright # RIGHT DOUBLE ANGLE QUOTATION<br />
<Multi_key> <period> : "»" guillemotright # RIGHT DOUBLE ANGLE QUOTATION<br />
<Multi_key> <Cyrillic_BE> : "„" U201e # DOUBLE LOW-9 QUOTATION MARK<br />
<Multi_key> <less> : "„" U201e # DOUBLE LOW-9 QUOTATION MARK<br />
<Multi_key> <Cyrillic_YU> : "“" U201c # LEFT DOUBLE QUOTATION MARK<br />
<Multi_key> <greater> : "“" U201c # LEFT DOUBLE QUOTATION MARK<br />
#<br />
<Multi_key> <Cyrillic_zhe> : "‘" U2018 # LEFT SINGLE QUOTATION MARK<br />
<Multi_key> <semicolon> : "‘" U2018 # LEFT SINGLE QUOTATION MARK<br />
<Multi_key> <Cyrillic_e> : "’" U2019 # RIGHT SINGLE QUOTATION MARK<br />
<Multi_key> <apostrophe> : "’" U2019 # RIGHT SINGLE QUOTATION MARK<br />
<Multi_key> <Cyrillic_ZHE> : "“" U201c # LEFT DOUBLE QUOTATION MARK<br />
<Multi_key> <colon> : "“" U201c # LEFT DOUBLE QUOTATION MARK<br />
<Multi_key> <Cyrillic_E> : "”" U201d # RIGHT DOUBLE QUOTATION MARK<br />
<Multi_key> <quotedbl> : "”" U201d # RIGHT DOUBLE QUOTATION MARK<br />
<br />
#<br />
# Dashes<br />
#<br />
<Multi_key> <minus> : "—" emdash # EM DASH<br />
<Multi_key> <underscore> : "–" endash # EN DASH<br />
<br />
#<br />
# Currencies<br />
#<br />
<Multi_key> <Cyrillic_u> : "€" EuroSign # EURO SIGN<br />
<Multi_key> <e> : "€" EuroSign # EURO SIGN<br />
<Multi_key> <Cyrillic_a> : "£" sterling # POUND SIGN<br />
<Multi_key> <f> : "£" sterling # POUND SIGN<br />
<br />
#<br />
# Trademarks<br />
#<br />
<Multi_key> <Cyrillic_es> : "©" copyright # COPYRIGHT SIGN<br />
<Multi_key> <c> : "©" copyright # COPYRIGHT SIGN<br />
<Multi_key> <Cyrillic_ka> : "®" registered # REGISTERED SIGN<br />
<Multi_key> <r> : "®" registered # REGISTERED SIGN<br />
<Multi_key> <Cyrillic_ie> : "™" U2122 # TRADE MARK SIGN<br />
<Multi_key> <t> : "™" U2122 # TRADE MARK SIGN<br />
<br />
#<br />
# Math<br />
#<br />
<Multi_key> <Cyrillic_ef> : "≈" approximate # ALMOST EQUAL TO<br />
<Multi_key> <a> : "≈" approximate # ALMOST EQUAL TO<br />
<Multi_key> <5> : "‰" U2030 # PER MILLE SIGN<br />
<Multi_key> <equal> : "≠" U2260 # NOT EQUAL TO<br />
<Multi_key> <plus> : "±" plusminus # PLUS-MINUS SIGN<br />
<br />
#<br />
# Misc. typographics<br />
#<br />
<Multi_key> <Cyrillic_yeru> : "§" section # SECTION SIG<br />
<Multi_key> <s> : "§" section # SECTION SIGN<br />
<Multi_key> <Cyrillic_shcha> : "°" degree # DEGREE SIGN<br />
<Multi_key> <o> : "°" degree # DEGREE SIGN<br />
<Multi_key> <space> : " " nobreakspace # NO-BREAK SPACE<br />
<Multi_key> <Cyrillic_ve> : "…" ellipsis # HORIZONTAL ELLIPSIS<br />
<Multi_key> <d> : "…" ellipsis # HORIZONTAL ELLIPSIS<br />
<br />
#<br />
# Missing keys in Russian layout<br />
#<br />
<Multi_key> <3> : "#" numbersign # NUMBER SIGN<br />
<Multi_key> <4> : "$" dollar # DOLLAR SIGN<br />
<Multi_key> <Cyrillic_ha> : "[" bracketleft # LEFT SQUARE BRACKET<br />
<Multi_key> <Cyrillic_hardsign> : "]" bracketright # RIGHT SQUARE BRACKET<br />
<br />
#<br />
# Bindings to ease usage with the Russian `typewriter' layout.<br />
# NB: Unable to bind dollar symbol to be Compose+4, it's Compose+Shift+4.<br />
#<br />
<Multi_key> <2> : "—" emdash # EM DASH<br />
<Multi_key> <8> : "–" endash # EN DASH<br />
<Multi_key> <slash> : "#" numbersign # NUMBER SIGN<br />
<Multi_key> <percent> : "‰" U2030 # PER MILLE SIGN<br />
<Multi_key> <bar> : "±" plusminus # PLUS-MINUS SIGN<br />
</pre><br />
<br />
= Настройка GTK1 =<br />
Отредактируйте файл /etc/gtk/gtkrc.ru :<br />
<pre>style "gtk-default-ru" {<br />
fontset = "-*-arial-medium-r-normal--12-*-*-*-*-*-iso10646-1",\<br />
-*-fixed-medium-r-*-*-14-*-*-*-*-*-iso10646-1"<br />
}<br />
class "GtkWidget" style "gtk-default-ru"</pre><br />
<br />
= Настройка ncurses приложений =<br />
== Midnight Commander (mc) ==<br />
Пакет '''mc''' с версией 4.6.1-5 из репозитория '''extra'''<br>При старом срезе - пакет из репозитория '''community''' mc-utf8.<br>Теперь mc собран с поддержкой юникодной локали и имеет приличный вид.<br />
<br />
== nano ==<br />
С версии 2.0 nano поддерживает utf-8.<br />
<br />
== ncmpc ==<br />
В репозитории extra пакет ncmpc 0.11.1 собран с ncurses без поддержки unicode, а также файл руссификации почему-то в кодировке ISO-8859-1. Решение:<br />
*Скачайте из AUR [http://aur.archlinux.org/packages.php?ID=1947 архив]<br />
*Переместите его в '''/var/abs/local/''' (если вы используете ABS) или в любую другую директорию<br />
*Разархивируйте '''tar -xzf ncmpc-svn.tar.gz'''<br />
*Перейдите в получившуюся директорию<br />
*Выполните '''makepkg -i'''<br />
<br />
== dialog ==<br />
Некоторые скрипты (например, alsaconf) используют программу dialog для вывода сообщений. Чтобы включить в ней поддержку юникода, поставьте пакет dialog-w из community или пересобирите с опцией <code>--with-ncursesw</code><br />
<br />
= Настройка русских man-страниц =<br />
<br />
Установите русские страницы командой<br />
pacman -S man-pages-ru<br />
<br />
Также позаботьтесь о том, чтобы переменная окружения ''LESSCHARSET'' имела значение ''UTF-8'', либо просто заккоментируйте строку '''export LESSCHARSET="latin1"''' в файле ''/etc/profile'', тогда less будет автоматически брать кодировку из локали.<br />
<br />
= Сделаем openoffice русским =<br />
Все просто. Поддержка языков в openoffice реализуется отдельными пакетами.<br />
Смотрим список пакетов:<br />
pacman -Ss openoffice<br />
<br />
Ставим поддержку русского языка<br />
pacman -S openoffice-ru<br />
<br />
<br />
<br />
= Перекодировка тегов MP3 =<br />
<br />
Установите пакет mutagen:<br />
pacman -S mutagen<br />
<br />
В каталоге с вашей коллекцией mp3 файлов выполните команду:<br />
find -iname '*.mp3' -print0 | xargs -0 mid3iconv -eCP1251 --remove-v1<br />
<br />
Команда перекодирует старые теги из кодировки CP1251 в UTF8, запишет тег версии id3v2.4 и удалит теги первой версии.<br />
<br />
Минус способа: не все проигрыватели из ОС Windows понимают теги формата 2.4. Поведение при этом различное: от игнорирования тега, до ругани на битый файл.<br />
<br />
Hint: в mpd после этого нужно перечитать список проигрывания, например так:<br />
mpc update (дождитесь завершения, статус можно смотреть запуская mpc без параметров)<br />
mpc clear<br />
mpc listall | mpc add<br />
<br />
Опционально:<br />
mpc rm all<br />
mpc save all<br />
<br />
[[Category:Русский]]</div>
Whgirw
https://wiki.archlinux.org/index.php?title=Improving_performance&diff=133224
Improving performance
2011-03-09T07:38:56Z
<p>Whgirw: /* Compressing /usr */</p>
<hr />
<div>[[Category: Other desktop user's resources (English)]]<br />
[[Category: HOWTOs (English)]]<br />
{{i18n|Maximizing Performance}}<br />
This article is a retrospective analysis and basic rundown about gaining performance in Arch Linux.<br />
<br />
==The basics==<br />
<br />
===Know your system===<br />
The best way to tune a system is to target the bottlenecks, that is the subsystems that limit the overall speed. They usually can be identified by knowing the specifications of the system, but there are some basic indications:<br />
* If the computer becomes slow when big applications, like openoffice and firefox, are running at the same time, then there is a good chance the amount of RAM is insufficient. To verify available RAM, use this command, and check for the line beginning with -/+buffers:<br />
$ free -m<br />
* If boot time is really slow, and if applications take a lot of time to load the first time they are launched, but run fine afterwards, then the hard drive is probably too slow. The speed of a hard drive can be measured using the hdparm command:<br />
$ hdparm -t /dev/harddrive<br />
This is only the pure read speed of the hard drive, and is not a valid benchmark, but a value superior to 40MB/s can be considered decent on an average system.<br />
* If the CPU load is consistently high even when RAM is available, then lowering CPU usage should be a priority. CPU load can be monitored in many ways, like using the top command:<br />
$ top<br />
* If the only applications lagging are the ones using direct rendering, meaning they use the graphic card, like video players and games, then improving the graphic performance should help. First step would be to verify if direct rendering simply isn't enabled. This is indicated by the glxinfo command:<br />
$ glxinfo | grep direct<br />
<br />
===The first thing to do===<br />
The simplest and most efficient way of improving overall performance is to run lightweight environments and applications.<br />
* Use a [[Window Manager|window manager]] instead of a [[Desktop Environment]]. Choices include [[dwm]], [[Openbox]] and [[JWM]].<br />
* Choose a minimal Desktop Environment over [[GNOME]] and [[KDE]]. Choices include [[LXDE]] and [[Xfce]].<br />
* Using lightweight applications. See [[Lightweight Software]] and the Light and Fast Applications Awards threads in the forum: [http://bbs.archlinux.org/viewtopic.php?id=41168 2007], [http://bbs.archlinux.org/viewtopic.php?id=67951 2008], [http://bbs.archlinux.org/viewtopic.php?id=78490 2009], and [http://bbs.archlinux.org/viewtopic.php?id=88515 2010].<br />
* Remove unnecessary daemons and background what daemons you can in {{Filename|/etc/rc.conf}}.<br />
<br />
===Compromise===<br />
Almost all tuning brings drawbacks. Lighter applications usually come with less features and some tweaks may make a system unstable, or simply require time to implement and maintain. This page tries to highlight those drawbacks, but the final judgment rests on the user.<br />
<br />
===Benchmarking===<br />
The effects of optimization are often difficult to judge. They can however be measured by [[benchmarking]] tools<br />
<br />
==Storage devices==<br />
===Choosing and tuning your filesystem===<br />
Choosing the best filesystem for a specific system is very important because each has its own strengths. The [[Beginner's Guide#Filesystem Types|beginner's guide]] provides a short summary of the most popular ones. You can also find relevant articles [http://wiki.archlinux.org/index.php/Category:File_systems_%28English%29 here].<br />
<br />
====Summary====<br />
*XFS: Excellent performance with large files. Low speed with small files. A good choice for /home.<br />
*Reiserfs: Excellent performance with small files. A good choice for /var.<br />
*Ext3: Average performance, reliable.<br />
*Ext4: Great overall performance, reliable, has performance issues with sqlite and some other databases.<br />
*JFS: Good overall performance, very low CPU usage.<br />
*Btrfs: Great overall performance (better than ext4), reliable (once it becomes stable). Lots of features. Still in heavy development and considered as unstable. Do not use this filesystem yet unless you know what you are doing and are prepared for potential data loss.<br />
<br />
====Mount options====<br />
Mount options offer an easy way to improve speed without reformatting. They can be set using the mount command:<br />
$ mount -o option1,option2 /dev/partition /mnt/partition<br />
To set them permanently, you can modify /etc/fstab to make the relevant line look like this:<br />
/dev/partition /mnt/partition partitiontype option1,option2 0 0<br />
A couple of mount options improving performance on almost all file-systems is {{Codeline|noatime,nodiratime}}. The former is a superset of the latter (which applies to directories only -- {{Codeline|noatime}} applies to both files and directories). In rare cases, for example if you use mutt, it can cause minor problems. You can instead use the {{Codeline|relatime}} option.<br />
<br />
====Ext3====<br />
See [[Ext3 Filesystem Tips]].<br />
<br />
====JFS====<br />
See [[JFS Filesystem#Optimizations| JFS Filesystem]].<br />
<br />
====XFS====<br />
For optimal speed, create an XFS file-system with:<br />
$ mkfs.xfs -l internal,lazy-count=1,size=128m -d agcount=2 /dev/thetargetpartition<br />
An XFS specific mount option that may increase performance is {{Codeline|<nowiki>logbufs=8</nowiki>}}. <br />
<br />
#/etc/fstab<br />
LABEL=XFSHOME /home xfs noatime,logbufs=8 0 1<br />
<br />
As its speed when dealing with small files is poor, users of XFS should consider using [[Improve_Pacman_Performance#pacman-cage|pacman-cage]]. For defragmentation, see [[Defragmentation XFS]].<br />
<br />
==== Reiserfs ====<br />
<br />
The {{Codeline|<nowiki>data=writeback</nowiki>}} mount option improves speed, but may corrupt data during power loss. The {{Codeline|notail}} mount option increases the space used by the filesystem by about 5%, but also improves overall speed. You can also reduce disk load by putting the journal and data on separate drives. This is be done when creating the filesystem: <br />
<br />
$ mkreiserfs –j /dev/hda1 /dev/hdb1<br />
<br />
Replace /dev/hda1 with the partition reserved for the journal, and /dev/hdb1 with the partition for data. You can learn more about reiserfs with this [http://www.funtoo.org/en/articles/linux/ffg/2/ article].<br />
<br />
====BTRFS====<br />
Btrfs is a new filesystem offering online defragmentation, optimized mode for SSDs, writable snapshots, changing size of partition without data loss and many other features. Btrfs is still in active development, and is available in the kernel (marked experimental). See more info on the [http://btrfs.wiki.kernel.org/index.php/Main_Page Btrfs homepage].<br />
<br />
===== mkinitcpio.conf for btrfs =====<br />
<br />
For non-root btrfs filesystems the btrfs module and dependencies are loaded when required. For a root btrfs filesystem you should ensure the initial ramdisk has the correct modules. There is a dependency of the btrfs module on the libcrc32c module. You can add crc32c to the modules line of /etc/mkinitcpio.conf like so:<br />
<br />
MODULES="crc32c libcrc32c zlib_deflate btrfs"<br />
<br />
This avoids pitfalls like "unknown symbol" errors when loading the btrfs modules.<br />
See also [http://aur.archlinux.org/packages.php?ID=33376 mkinitcpio-btrfs].<br />
<br />
===Compressing /usr===<br />
A way to speed up reading from the hard drive is to compress the data, because there is less data to be read. It must however be decompressed, which means a greater CPU load. Some filesystems support transparent compression, most notably btrfs and reiserfs4, but their compression ratio is limited by the 4k block size. A good alternative is to compress /usr in a squashfs file, with a 64k(128k) block size, as instructed in this [http://forums.gentoo.org/viewtopic-t-646289.html Gentoo forums thread]. What this tutorial does is basically to compress the /usr folder into a compressed squashfs file-system, then mounts it with aufs. A lot of space is saved, usually two thirds of the original size of /usr, and applications load faster. However, each time an application is installed or reinstalled, it is written uncompressed, so /usr must be re-compressed periodically. Squashfs is already in the kernel, and aufs2 is in the extra repository, so no kernel compilation is needed if using the stock kernel.<br />
Since the linked guide is for Gentoo the next commands outline the steps especially for Arch. Basically we have got install two packages to get it working:<br />
# pacman -S aufs2 squashfs-tools<br />
This command installs the aufs-modules and some userspace-tools for the squash-filesystem.<br />
Now we need some extra directories where we can store the archive of /usr as read-only and another folder where we can store the data changed after the last compression as writeable:<br />
# mkdir -p /squashed/usr/{ro,rw}<br />
Now that we got a rough setup you should perform a complete system-upgrade since every change of content in /usr after the compression will be excluded from this speedup. If you use prelink you should also perform a complete prelink before creating the archive. Now it is time to invoke the command to compress /usr:<br />
# mksquashfs /usr /squashed/usr/usr.sfs -b 65536<br />
These parameters/options are the ones suggested by the Gentoo link but there might be some room for improvement using some of the options described [http://www.tldp.org/HOWTO/SquashFS-HOWTO/mksqoverview.html#mksqusing here].<br />
Now to get the archive mounted together with the writeable folder it is necessary to edit fstab:<br />
# nano /etc/fstab<br />
Add the following lines:<br />
/squashed/usr/usr.sfs /squashed/usr/ro squashfs loop,ro 0 0 <br />
usr /usr aufs udba=reval,br:/squashed/usr/rw:/squashed/usr/ro 0 0<br />
Now you should be done and able to reboot. The original Author suggests to delete all the old content of /usr, but this might cause some problems if anything goes wrong during some later re-compression. It is more safe to leave the old files in place just to be on the safe side.<br />
<br />
A [http://bbs.archlinux.org/viewtopic.php?pid=714052 bash script] has been created that will automate the process of re-compressing (read updating) the archive since the tutorial is meant for Gentoo and some options don't correlate to what they should be in Arch.<br />
<br />
===Tuning for an SSD===<br />
[[SSD#Tips_for_Maximizing_SSD_Performance]]<br />
<br />
==CPU==<br />
The only way to directly improve CPU speed is overclocking. As it is a complicated and risky task, it is not recommended for anyone except experts. The best way to overclock is through the BIOS. When purchasing your system, keep in mind that most Intel motherboards are notorious for disabling the capacity to overclock.<br />
<br />
A way to modify performance ([http://lkml.org/lkml/2009/9/6/136 ref]) is to use Con Kolivas' desktop-centric kernel patchset, which, among other things, replaces the Completely Fair Scheduler (CFS) with the Brain Fuck Scheduler (BFS).<br />
<br />
Kernel PKGBUILDs that include the BFS patch can be installed from the [[AUR]] or [[Unofficial_User_Repositories]]. See the respective pages for [http://aur.archlinux.org/packages.php?ID=32877 kernel26-ck], [http://aur.archlinux.org/packages.php?ID=36384 kernel26-bfs] or [http://aur.archlinux.org/packages.php?ID=40191 kernel26-pf] for more information on their additional patches.<br />
<br />
{{Note|BFS/CK are designed for desktop/laptop use and not servers. They provide low latency and work well for 16 CPUs or less. Also, Con Kolivas suggests setting HZ to 1000. For more information, see the [http://ck.kolivas.org/patches/bfs/bfs-faq.txt BFS FAQ] and [http://www.kernel.org/pub/linux/kernel/people/ck/patches/2.6/2.6.37/2.6.37-ck1/patches/ ck patches].}}<br />
===[[Verynice]]===<br />
[http://thermal.cnde.iastate.edu/~sdh4/verynice/ Verynice] is a daemon, available on [http://aur.archlinux.org/packages.php?ID=6403 AUR], for dynamically adjusting the nice levels of executables. The nice level represent the priority of the executable when allocating CPU resources. Simply define executables for which responsiveness is important, like X or multimedia applications, as ''goodexe'' in {{filename|/etc/verynice.conf}}. Similarly, CPU-hungry executables running in the background, like make, can be defined as ''badexe''. This prioritisation greatly improves system responsiveness under heavy load.<br />
<br />
<br />
===[[Ulatencyd]]===<br />
Ulatency is a daemon that controls how the Linux kernel will spend it's resources on the running processes. It uses dynamic cgroups to give the kernel hints and limitations on processes.<br />
<br />
==Network==<br />
See relevant section in [[General Recommendations#Networking|General Recomendations]].<br />
<br />
==Graphics==<br />
<br />
===Xorg.conf configuration===<br />
Graphic performance heavily depends on the settings in {{Filename|/etc/X11/xorg.conf}}. There are tutorials for [[Nvidia]], [[ATI]] and [[Intel]] cards. Improper settings may stop Xorg from working, so caution is advised.<br />
<br />
===Driconf===<br />
Driconf is a small utility that allows you to change the direct rendering settings for open source drivers. Enabling HyperZ can drastically improve performance.<br />
<br />
===GPU Overclocking===<br />
Overclocking a graphics card is typically more expedient than with a CPU, since there are readily accessible software packages which allow for on-the-fly GPU clock adjustments. For ATI users, get [http://aur.archlinux.org/packages.php?ID=2128 rovclock], and Nvidia users should get nvclock in the extra repository. Intel chipsets users can install [http://www.gmabooster.com/ GMABooster] from [http://aur.archlinux.org/packages.php?ID=28197 AUR]<br />
<br />
The changes can be made permanent by running the appropriate command after X boots, for example by adding it to {{Filename|~/.xinitrc}}. A safer approach would be to only apply the overclocked settings when needed.<br />
<br />
==RAM and swap==<br />
<br />
=== Swappiness ===<br />
<br />
The swappiness represent how much the kernel prefers swap to RAM. Setting it to a very low value, meaning the kernel will almost always use RAM, is known to improve responsiveness on many systems. To do that, simply add those line to {{Filename|/etc/sysctl.conf}}:<br />
<br />
vm.swappiness=20<br />
vm.vfs_cache_pressure=50<br />
<br />
To test and more on why this may work, take a look at this [http://rudd-o.com/en/linux-and-free-software/tales-from-responsivenessland-why-linux-feels-slow-and-how-to-fix-that article].<br />
<br />
===Compcache===<br />
[http://code.google.com/p/compcache/ Compcache], also known as the ramzswap kernel module, creates a swap device in RAM and compresses it. That means that part of the RAM can hold much more information, but uses more CPU. Still, is it much quicker than a hard drive swap. If a system often falls back to swap, this could improve responsiveness. Compcache is available in the [http://aur.archlinux.org/packages.php?ID=40063 AUR].<br />
<br />
It is also possible (and recommended) to tell compcache to fall back on the hard drive swap when full. To do this, define a backing swap device in the configuration file. This swap device must not be in use when compcache is started, so remove it from your /etc/fstab!<br />
<br />
This is also a good way to reduce disk read/write cycles due to swap on SSDs.<br />
<br />
===Mounting /tmp to RAM===<br />
This will make your system a tiny bit faster, but will take up some of your RAM. It also reduces disk read/write cycles, and is therefore a good choice if using an SSD or if you have RAM to spare. Simply add this line to {{Filename|/etc/fstab}} and reboot:<br />
tmpfs /tmp tmpfs defaults,noatime,nodev,nosuid,mode=1777 0 0<br />
<br />
===Using the graphic card's RAM===<br />
In the unlikely case that you have very little RAM and a surplus of video RAM, you can use the latter as swap. See [[Swap on video ram]].<br />
<br />
=== Preloading ===<br />
Preloading is the action of putting and keeping target files into the RAM. The practical use is that preloaded applications always start very quickly, because reading from the RAM is always quicker than from the hard drive. However, part of your RAM will be dedicated to this task, but no more than if you kept the application open. Therefore, preloading is best used with heavy, often-used applications, like firefox and openoffice.<br />
==== Go-preload ====<br />
[http://aur.archlinux.org/packages.php?ID=34207 Go-preload] is a small daemon created in the [http://forums.gentoo.org/viewtopic-t-789818-view-next.html?sid=5457cff93039fc7d4a3e445ef90f9821 gentoo forum]. To use it, first run this command in a terminal for each program you want to preload at boot:<br />
# gopreload-prepare program<br />
Then, as instructed, press enter when the program is fully loaded. This will add a list of files needed by the program in {{Filename|/usr/share/gopreload/enabled}}. To load all lists at boot, simply add gopreload to your DAEMONS array in {{Filename|/etc/rc.conf}}. To disable the loading of a program, remove the appropriate list in {{Filename|/usr/share/gopreload/enabled}}, or move it to {{Filename|/usr/share/gopreload/disabled}}.<br />
====Preload====<br />
A more automated, albeit less KISS, approach is used by [[Preload]]. All you have to do is add it to your DAEMONS array in {{Filename|/etc/rc.conf}}. It will monitor the most used files on your system, and with time build its own list of files to preload at boot.<br />
====Readahead====<br />
[[Readahead]] is a tool that can cache files before needed and help you accelerating program loading.<br />
<br />
==Boot time==<br />
You can find tutorials with good tips in the articles [[Tweaking for a faster boot time]], [[Speedup boot]] and [[Improve Boot Performance]].<br />
<br />
===Suspend to ram===<br />
The best way to reduce boot time is not booting at all. Consider [[Suspend to RAM|suspending your system to ram]] instead.<br />
<br />
===Kernel boot options===<br />
Some boot options can decrease kernel boot time. The {{Codeline|fastboot}} option usually can take off one second or so. Also, if you see a message saying "Waiting 8s for device XXX" at boot, adding {{Codeline|<nowiki>rootdelay=1</nowiki>}} can reduce the waiting time, but be careful, as it may break the booting process. Those options are set in {{Filename|/boot/grub/menu.lst}} or {{Filename|/etc/lilo.conf}}, depending on which bootloader you use.<br />
<br />
===Custom kernel===<br />
Compiling a custom kernel will reduce boot time and memory usage, but can be long, complicated and even painful. It usually is not worth the effort, but can be very interesting and a great learning experience. If you really know what you are doing, start [[Kernel Compilation|here]].<br />
<br />
===Speed Up udev===<br />
<br />
Performance gains can be realized by bypassing the blacklisting logic present in the {{Filename|/lib/udev/load-modules.sh}} script. See [[Speed_Up_udev]] for additional details.<br />
<br />
==Application-specific tips==<br />
===Firefox===<br />
The [[Firefox]] article offers good tips; most notably [[Firefox#Speed up rendering by disabling pango |disabling pango]], [[Firefox#Speed-Up Firefox by Defragmenting the Profile's SQLite Databases|cleaning the sqlite database]], and using [[Firefox#Firefox customized for Speed|firefox-pgo]]. See also: [[Speed-up Firefox using tmpfs]], and [[Firefox Tips and Tweaks#Turning off anti-phishing to speedup Firefox|Turning off anti-phishing]].<br />
<br />
===Gcc/Makepkg===<br />
See [[Ccache]].<br />
<br />
===Mkinitcpio===<br />
User josh_ from the forum has made impressive changes to the mkinitcpio script, making it two or three times faster. While waiting for these changes to be implemented, you can get them [http://bbs.archlinux.org/viewtopic.php?id=79898 here].<br />
<br />
===OpenOffice===<br />
See [[OpenOffice#Speed up OpenOffice|Speed up OpenOffice]].<br />
<br />
===Pacman===<br />
See [[Improve Pacman Performance]].<br />
<br />
===SSH===<br />
See [[SSH#Speed up SSH|Speed up SSH]].</div>
Whgirw
https://wiki.archlinux.org/index.php?title=ECryptfs_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=131322
ECryptfs (Русский)
2011-02-17T17:01:06Z
<p>Whgirw: /* Введение */</p>
<hr />
<div>[[Category:Security (Русский)]]<br />
[[Category:File systems (Русский)]]<br />
[[Category:HOWTOs (Русский)]]<br />
{{i18n|Шифрование системы с помощью eCryptfs}}<br />
<br />
= Введение =<br />
В статье описывается базовое использование [https://launchpad.net/ecryptfs eCryptfs]. Статья проведёт вас через процесс установки зашифрованной домашней директории,<br />
в которой вы можете хранить личные/секретные данные. Если вы не уверены, нужно ли вам шифрование, прочтите сначала [[System_Encryption_with_LUKS_for_dm-crypt|dm-crypt]].<br />
<br />
Реализация eCryptfs отличается от реализации dm-crypt, которая шифрует блочное устройство полностью, а eCryptfs шифрует вайловую систему - тоесть каждый файл поотдельности. О сравнении двух методов шифрования можно прочитать на [http://ecryptfs.sourceforge.net/ecryptfs-faq.html#compare].<br />
<br />
Если коротко, то eCryptfs не нуждается в резервировании места на диске(создание специального раздела). eCryptfs может быть смонтирован в любую директорию и шифровать её содержимое(например домашняя директория! пользователя или любая директория в сети). Все метаданные для расшифровки хранятся в заголовках файлов, поэтому зашифрованые файлы можно перемещать, копировать, делать резервные копии. Есть и другие плюсы данного метода, как и минусы. Самый большой минус - eCryptfs не может шифровать весь раздел/жёсткий диск. По этому eCryptfs не может зашифровать раздел swap(но вы можете комбинировать eCryptfs и dm-crypt).<br />
<br />
= Основы =<br />
eCryptfs входит в ядро с версии 2.6.19, но для работы с ней, вам нужны дополнительные инструменты: [http://aur.archlinux.org/packages.php?ID=8397 ecryptfs-utils] и [http://aur.archlinux.org/packages.php?ID=6895 keyutils].<br />
<br />
После установки загрузите модуль ядра:<br />
# modprobe ecryptfs<br />
<br />
Пакет ecryptfs-utils нужен для управления ключами для доступа к зашифрованым данным. Некоторые скрипы из этого пакета помогут автоматизировать весь процесс (''ecryptfs-setup-private'') или помут в комбинировании eCryptfs и dm-crypt для шифрования раздела swap. Мы не будем использовать эти скрипты, а сделаем всё в ручном режиме для лучшего понимания принципа работы данного метода.<br />
<br />
Прежде чем мы начнём, я советую вам прочитать документацию по eCryptfs(man).<br />
<br />
<br />
== Установка ==<br />
Для начала создайте директории, которые вы хотите зашифровать. В этом примере мы назовём директорию - Private.<br />
$ su -<br />
# mkdir -m 700 /home/username/.Private<br />
# mkdir -m 500 /home/username/Private<br />
# chown username:username /home/username/{.Private,Private}<br />
<br />
В сумме получается:<br />
* Зашифрованые данные будут храниться в ~/.Private<br />
* Когда эта директория смонтированна, данные будут доступны в ~/Private<br />
** Когда директория не смонтированна, данные в неё не могут быть записаны<br />
** Когда директория смонтированна, права доступа к ней такие-же как и у ~/.Private<br />
<br />
<br />
eCryptfs может быть смонтированны поверх ~/Private.<br />
# mount -t ecryptfs /home/username/.Private /home/username/Private<br />
<br />
Вам нужно будет ввести пароль и выбрать некоторые опции с которыми директория будет монтироватся в будущем. Так-же вы можете задать несколько различных ключей для шифрования различных данных(об этом ниже). Для краткости мы опишем процесс с одним ключём. <br />
Пример:<br />
Key type: passphrase<br />
Passphrase: ThisIsAVeryWeakPassphrase<br />
Cypher: aes<br />
Key byte: 16<br />
Plaintext passtrough: no<br />
Filename encryption: no<br />
Add signature to cache: yes <br />
<br />
В сумме получается:<br />
* Ваш ключ это ваша так называемая '''mount passphrase''' хранится в виде хэша+соль.<br />
** По теминологии eCryptfs этот ключ называется "file encryption key, encryption key", или '''fekek'''.<br />
* eCryptfs поддерживает несколько методов шифрования AES, blowfish, twofish...<br />
* <br />
* Plaintext passtrough разрешает сохранять и работать с '''не зашифрованными данными''' внутри ~/.Private.<br />
* Шифрование файловой ситемы доступно с версии ядра 2.6.29.<br />
** По теминологии eCryptfs этот ключ, который служит для шифрования имён файлов называется "filename encryption key" или '''fnek'''<br />
* Сигнатура ключа(ей) хранится в {{Filename|/root/.ecryptfs/sig-cache.txt}}.<br />
<br />
<br />
Т.к. мы хотим монтировать директории без прав супер-пользователя, нам нужно переместить директорию с конфигурацией eCryptfs в нашу домашнюю директорию и сделать нас её владельцем:<br />
# mv /root/.ecryptfs /home/username<br />
# chown username:username /home/username/.ecryptfs<br />
<br />
<br />
Установка на этом законченна и директория смонтирована. Вы можете размещать любые файлы в ~/Private и они будут прозрачно зашифрованы. Теперь отмонтируйте директорию и если вы попробуете прочитать содетжимое файлов, вы увидете, что они зашифрованы. Как получить к ним доступ? Смотрите следующий шаг.<br />
<br />
<br />
== Монтирование ==<br />
Когда вам снова понадобятся ваши файлы, вы можете повторить процедуру монтирования описанную выше ислпользую тот-же ключ и опции.<br />
<br />
Каждый раз проделывать эти операции может быть утомительно. Вариант номер один: передать все опции команде монтирования кроме ключа.<br />
<br />
$ sudo mount -t ecryptfs /home/username/.Private /home/username/Private -o ecryptfs_cipher=aes,ecryptfs_key_bytes=16,key=passphrase<br />
<br />
Вариант номер два(рекомендован): добавить строку в '''{{Filename|/etc/fstab}}''':<br />
<br />
# eCryptfs mount points<br />
/home/username/.Private /home/username/Private ecryptfs rw,user,noauto,ecryptfs_sig=XY,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecrypfs_unlink_sigs 0 0<br />
<br />
<br />
ПРИМЕЧАНИЕ:<br />
<br />
* Параметр '''user''' позволяет монтирование с ограничеными правами<br />
* В параметре '''ecryptfs_sig''' замените строку ''XY'' значением сигнатуры (можно взять из '''mtab''' или {{Filename|sig-cache.txt}})<br />
* Если было разрешено шифрование имён файлов, то нужно поставить дополнительный параметр монтирования '''ecryptfs_fnek_sig'''=''XY'', где ''XY'' тоже значение сигнатуры, что и в параметре '''ecryptfs_sig'''<br />
* Последний параметр '''ecrypfs_unlink_sigs''' говорит о том, что при размонтировании ключ из брелка будет удалён<br />
<br />
<br />
Поскольку в процессе размонтирования ключ удаляется из брелка ядра, то для последующего монтировании там необходимо заново создать ключ. Для этого используется утилиты '''ecryptfs-add-passphrase''' или '''ecryptfs-manager''':<br />
<br />
После ввода пароля шифрования можно произвести монтирование:<br />
<br />
$ ecryptfs-add-passphrase<br />
Passphrase: ThisIsAVeryWeakPassphrase<br />
$ mount -i /home/username/Private<br />
<br />
Обратите внимание на параметр '''{{Codeline|-i}}'''. Он предотвращает вызов помощника монтирования. Это означает, что при использовании параметра {{Codeline|-i}} по умолчанию при монтировании будут применены параметры '''nosuid, noexec''' and '''nodev'''. Если в шифрованой папке необходимо иметь также и исполняемые файлы, то можно добавить параметр '''exec''' в файле fstab в строке команды.<br />
<br />
Не лишне также будет вспомнить об утилите '''keyctl''', входящую в состав пакета ''keyutils'', установленного ранее. Она может быть использована для более продвинутого управления ключами. Нижеследующий пример демонстрирует команду для отображения списка имеющихся ключей и команду для очистки этого списка:<br />
$ keyctl list @u<br />
$ keyctl clear @u<br />
<br />
== Применение ==<br />
Помимо использования шифрованой папки для хранения критичных файлов и прочих данных не для чужих глаз, можно так же хранить и данные приложений. К примеру ''Firefox'' имеет не только встроеный менеждер паролей, но и историю посещений и кэш страниц, что может представлять уязвимость. Меры защиты очень просты:<br />
$ mv ~/.mozilla ~/Private/mozilla<br />
$ ln -s ~/Private/mozilla ~/.mozilla<br />
<br />
== Удаление ==<br />
Удаление зашифрованой папки производится после её размонтирования. Если содержащиеся в ней файлы нужно сохранить, то это делается перед её размонтированием.<br />
<br />
== Backup ==<br />
Setup explained here separates the directory with encrypted data from the mount point, so the encrypted data is available for backup at any time. With an overlay mount (i.e. ''~/Secret'' mounted over ''~/Secret'') the lower, encrypted, data is harder to get to. Today when cronjobs and other automation software do automatic backups the risk of leaking your sensitive data is higher.<br />
<br />
We explained earlier that all cryptographic metadata is stored in the headers of files. You can easily do backups, or incremental backups, of your '''~/.Private''' directory, treating it like any other directory.<br />
<br />
= Advanced =<br />
This wiki article covers only the basic setup of a private encrypted directory. There is however another article about eCryptfs on Arch Linux, which covers encryption of your entire $HOME and encrypting swap space without breaking hibernation (suspend to disk).<br />
<br />
That article includes many more steps (i.e. using PAM modules and automatic mounting) and the author was opposed to replicating it here, because there is just no single "right" way to do it. The author proposes some solutions and discusses the security implications, but they are his solutions and as such might not be the best nor are they endorsed by the eCryptfs project in any way.<br />
<br />
Article: [http://sysphere.org/~anrxc/j/articles/ecryptfs/index.html eCryptfs and $HOME] by Adrian C. (anrxc).<br />
<br />
== PAM Mount ==<br />
The above "''eCryptfs and $HOME''" article uses a shell init file to mount the home directory. The same can be done using [http://aur.archlinux.org/packages.php?ID=1976 pam_mount] with the added benefit that home is un-mounted when all sessions are logged out. As eCryptfs needs the {{Codeline|-i}} switch, the ''lclmount'' setting will need to be changed. I use the following in {{Filename|/etc/security/pam_mount.conf.xml}}:<br />
<lclmount>mount -i %(VOLUME) "%(before=\"-o\" OPTIONS)"</lclmount><br />
<br />
Remember to also set the volume definition (preferably to {{Filename|~/.pam_mount.conf.xml}} and uncomment luserconf).<br />
<pam_mount><br />
<volume noroot="1" fstype="ecryptfs" path="/home/user/.Private" mountpoint="/home/user"/><br />
</pam_mount><br />
<br />
''noroot'' is needed (at least in my configuration) because the encryption key will be added to the user's keyring.<br />
<br />
<br />
To avoid wasting time needlessly unwrapping the passphrase you can create a script that will check ''pmvarrun'' to see the number of open sessions:<br />
#!/bin/sh<br />
#<br />
# /usr/local/bin/doecryptfs<br />
<br />
exit $(/usr/sbin/pmvarrun -u$PAM_USER -o0)<br />
<br />
With the following line added before the eCryptfs unwrap module in your PAM stack:<br />
auth [success=ignore default=1] pam_exec.so quiet /usr/local/bin/doecryptfs<br />
auth required pam_ecryptfs.so unwrap<br />
The article suggests adding these to {{Filename|/etc/pam.d/login}}, but the changes will need to be added to all other places you login, such as {{Filename|/etc/pam.d/kde}}.</div>
Whgirw
https://wiki.archlinux.org/index.php?title=ECryptfs_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=131307
ECryptfs (Русский)
2011-02-17T14:11:34Z
<p>Whgirw: /* Removal */</p>
<hr />
<div>[[Category:Security (Русский)]]<br />
[[Category:File systems (Русский)]]<br />
[[Category:HOWTOs (Русский)]]<br />
{{i18n|Шифрование системы с помощью eCryptfs}}<br />
<br />
= Введение =<br />
В статье описывается базовое использование [https://launchpad.net/ecryptfs eCryptfs]. Статья проведёт вас через процесс установки защифрованной домашней директории,<br />
в которой вы можете хранить личные/секретные данные. Если вы не уверены, нужно ли вам шифрование, прочтите сначала [[System_Encryption_with_LUKS_for_dm-crypt|dm-crypt]].<br />
<br />
Реализация eCryptfs отличается от реализации dm-crypt, которая шифрует блочное устройство полностью, а eCryptfs шифрует вайловую систему - тоесть каждый файл поотдельности. О сравнении двух методов шифрования можно прочитать на [http://ecryptfs.sourceforge.net/ecryptfs-faq.html#compare].<br />
<br />
Если коротко, то eCryptfs не нуждается в резервировании места на диске(создание специального раздела). eCryptfs может быть смонтирован в любую директорию и шифровать её содержимое(например домашняя директория! пользователя или любая директория в сети). Все метаданные для расшифровки хранятся в заголовках файлов, поэтому зашифрованые файлы можно перемещать, копировать, делать резервные копии. Есть и другие плюсы данного метода, как и минусы. Самый большой минус - eCryptfs не может шифровать весь раздел/жёсткий диск. По этому eCryptfs не может зашифровать раздел swap(но вы можете комбинировать eCryptfs и dm-crypt).<br />
<br />
<br />
= Основы =<br />
eCryptfs входит в ядро с версии 2.6.19, но для работы с ней, вам нужны дополнительные инструменты: [http://aur.archlinux.org/packages.php?ID=8397 ecryptfs-utils] и [http://aur.archlinux.org/packages.php?ID=6895 keyutils].<br />
<br />
После установки загрузите модуль ядра:<br />
# modprobe ecryptfs<br />
<br />
Пакет ecryptfs-utils нужен для управления ключами для доступа к зашифрованым данным. Некоторые скрипы из этого пакета помогут автоматизировать весь процесс (''ecryptfs-setup-private'') или помут в комбинировании eCryptfs и dm-crypt для шифрования раздела swap. Мы не будем использовать эти скрипты, а сделаем всё в ручном режиме для лучшего понимания принципа работы данного метода.<br />
<br />
Прежде чем мы начнём, я советую вам прочитать документацию по eCryptfs(man).<br />
<br />
<br />
== Установка ==<br />
Для начала создайте директории, которые вы хотите зашифровать. В этом примере мы назовём директорию - Private.<br />
$ su -<br />
# mkdir -m 700 /home/username/.Private<br />
# mkdir -m 500 /home/username/Private<br />
# chown username:username /home/username/{.Private,Private}<br />
<br />
В сумме получается:<br />
* Зашифрованые данные будут храниться в ~/.Private<br />
* Когда эта директория смонтированна, данные будут доступны в ~/Private<br />
** Когда директория не смонтированна, данные в неё не могут быть записаны<br />
** Когда директория смонтированна, права доступа к ней такие-же как и у ~/.Private<br />
<br />
<br />
eCryptfs может быть смонтированны поверх ~/Private.<br />
# mount -t ecryptfs /home/username/.Private /home/username/Private<br />
<br />
Вам нужно будет ввести пароль и выбрать некоторые опции с которыми директория будет монтироватся в будущем. Так-же вы можете задать несколько различных ключей для шифрования различных данных(об этом ниже). Для краткости мы опишем процесс с одним ключём. <br />
Пример:<br />
Key type: passphrase<br />
Passphrase: ThisIsAVeryWeakPassphrase<br />
Cypher: aes<br />
Key byte: 16<br />
Plaintext passtrough: no<br />
Filename encryption: no<br />
Add signature to cache: yes <br />
<br />
В сумме получается:<br />
* Ваш ключ это ваша так называемая '''mount passphrase''' хранится в виде хэша+соль.<br />
** По теминологии eCryptfs этот ключ называется "file encryption key, encryption key", или '''fekek'''.<br />
* eCryptfs поддерживает несколько методов шифрования AES, blowfish, twofish...<br />
* <br />
* Plaintext passtrough разрешает сохранять и работать с '''не зашифрованными данными''' внутри ~/.Private.<br />
* Шифрование файловой ситемы доступно с версии ядра 2.6.29.<br />
** По теминологии eCryptfs этот ключ, который служит для шифрования имён файлов называется "filename encryption key" или '''fnek'''<br />
* Сигнатура ключа(ей) хранится в {{Filename|/root/.ecryptfs/sig-cache.txt}}.<br />
<br />
<br />
Т.к. мы хотим монтировать директории без прав супер-пользователя, нам нужно переместить директорию с конфигурацией eCryptfs в нашу домашнюю директорию и сделать нас её владельцем:<br />
# mv /root/.ecryptfs /home/username<br />
# chown username:username /home/username/.ecryptfs<br />
<br />
<br />
Установка на этом законченна и директория смонтирована. Вы можете размещать любые файлы в ~/Private и они будут прозрачно зашифрованы. Теперь отмонтируйте директорию и если вы попробуете прочитать содетжимое файлов, вы увидете, что они зашифрованы. Как получить к ним доступ? Смотрите следующий шаг.<br />
<br />
<br />
== Монтирование ==<br />
Когда вам снова понадобятся ваши файлы, вы можете повторить процедуру монтирования описанную выше ислпользую тот-же ключ и опции.<br />
<br />
Каждый раз проделывать эти операции может быть утомительно. Вариант номер один: передать все опции команде монтирования кроме ключа.<br />
<br />
$ sudo mount -t ecryptfs /home/username/.Private /home/username/Private -o ecryptfs_cipher=aes,ecryptfs_key_bytes=16,key=passphrase<br />
<br />
Вариант номер два(рекомендован): добавить строку в '''{{Filename|/etc/fstab}}''':<br />
<br />
# eCryptfs mount points<br />
/home/username/.Private /home/username/Private ecryptfs rw,user,noauto,ecryptfs_sig=XY,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecrypfs_unlink_sigs 0 0<br />
<br />
<br />
ПРИМЕЧАНИЕ:<br />
<br />
* Параметр '''user''' позволяет монтирование с ограничеными правами<br />
* В параметре '''ecryptfs_sig''' замените строку ''XY'' значением сигнатуры (можно взять из '''mtab''' или {{Filename|sig-cache.txt}})<br />
* Если было разрешено шифрование имён файлов, то нужно поставить дополнительный параметр монтирования '''ecryptfs_fnek_sig'''=''XY'', где ''XY'' тоже значение сигнатуры, что и в параметре '''ecryptfs_sig'''<br />
* Последний параметр '''ecrypfs_unlink_sigs''' говорит о том, что при размонтировании ключ из брелка будет удалён<br />
<br />
<br />
Поскольку в процессе размонтирования ключ удаляется из брелка ядра, то для последующего монтировании там необходимо заново создать ключ. Для этого используется утилиты '''ecryptfs-add-passphrase''' или '''ecryptfs-manager''':<br />
<br />
После ввода пароля шифрования можно произвести монтирование:<br />
<br />
$ ecryptfs-add-passphrase<br />
Passphrase: ThisIsAVeryWeakPassphrase<br />
$ mount -i /home/username/Private<br />
<br />
Обратите внимание на параметр '''{{Codeline|-i}}'''. Он предотвращает вызов помощника монтирования. Это означает, что при использовании параметра {{Codeline|-i}} по умолчанию при монтировании будут применены параметры '''nosuid, noexec''' and '''nodev'''. Если в шифрованой папке необходимо иметь также и исполняемые файлы, то можно добавить параметр '''exec''' в файле fstab в строке команды.<br />
<br />
Не лишне также будет вспомнить об утилите '''keyctl''', входящую в состав пакета ''keyutils'', установленного ранее. Она может быть использована для более продвинутого управления ключами. Нижеследующий пример демонстрирует команду для отображения списка имеющихся ключей и команду для очистки этого списка:<br />
$ keyctl list @u<br />
$ keyctl clear @u<br />
<br />
== Применение ==<br />
Помимо использования шифрованой папки для хранения критичных файлов и прочих данных не для чужих глаз, можно так же хранить и данные приложений. К примеру ''Firefox'' имеет не только встроеный менеждер паролей, но и историю посещений и кэш страниц, что может представлять уязвимость. Меры защиты очень просты:<br />
$ mv ~/.mozilla ~/Private/mozilla<br />
$ ln -s ~/Private/mozilla ~/.mozilla<br />
<br />
== Удаление ==<br />
Удаление зашифрованой папки производится после её размонтирования. Если содержащиеся в ней файлы нужно сохранить, то это делается перед её размонтированием.<br />
<br />
== Backup ==<br />
Setup explained here separates the directory with encrypted data from the mount point, so the encrypted data is available for backup at any time. With an overlay mount (i.e. ''~/Secret'' mounted over ''~/Secret'') the lower, encrypted, data is harder to get to. Today when cronjobs and other automation software do automatic backups the risk of leaking your sensitive data is higher.<br />
<br />
We explained earlier that all cryptographic metadata is stored in the headers of files. You can easily do backups, or incremental backups, of your '''~/.Private''' directory, treating it like any other directory.<br />
<br />
= Advanced =<br />
This wiki article covers only the basic setup of a private encrypted directory. There is however another article about eCryptfs on Arch Linux, which covers encryption of your entire $HOME and encrypting swap space without breaking hibernation (suspend to disk).<br />
<br />
That article includes many more steps (i.e. using PAM modules and automatic mounting) and the author was opposed to replicating it here, because there is just no single "right" way to do it. The author proposes some solutions and discusses the security implications, but they are his solutions and as such might not be the best nor are they endorsed by the eCryptfs project in any way.<br />
<br />
Article: [http://sysphere.org/~anrxc/j/articles/ecryptfs/index.html eCryptfs and $HOME] by Adrian C. (anrxc).<br />
<br />
== PAM Mount ==<br />
The above "''eCryptfs and $HOME''" article uses a shell init file to mount the home directory. The same can be done using [http://aur.archlinux.org/packages.php?ID=1976 pam_mount] with the added benefit that home is un-mounted when all sessions are logged out. As eCryptfs needs the {{Codeline|-i}} switch, the ''lclmount'' setting will need to be changed. I use the following in {{Filename|/etc/security/pam_mount.conf.xml}}:<br />
<lclmount>mount -i %(VOLUME) "%(before=\"-o\" OPTIONS)"</lclmount><br />
<br />
Remember to also set the volume definition (preferably to {{Filename|~/.pam_mount.conf.xml}} and uncomment luserconf).<br />
<pam_mount><br />
<volume noroot="1" fstype="ecryptfs" path="/home/user/.Private" mountpoint="/home/user"/><br />
</pam_mount><br />
<br />
''noroot'' is needed (at least in my configuration) because the encryption key will be added to the user's keyring.<br />
<br />
<br />
To avoid wasting time needlessly unwrapping the passphrase you can create a script that will check ''pmvarrun'' to see the number of open sessions:<br />
#!/bin/sh<br />
#<br />
# /usr/local/bin/doecryptfs<br />
<br />
exit $(/usr/sbin/pmvarrun -u$PAM_USER -o0)<br />
<br />
With the following line added before the eCryptfs unwrap module in your PAM stack:<br />
auth [success=ignore default=1] pam_exec.so quiet /usr/local/bin/doecryptfs<br />
auth required pam_ecryptfs.so unwrap<br />
The article suggests adding these to {{Filename|/etc/pam.d/login}}, but the changes will need to be added to all other places you login, such as {{Filename|/etc/pam.d/kde}}.</div>
Whgirw
https://wiki.archlinux.org/index.php?title=ECryptfs_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=131306
ECryptfs (Русский)
2011-02-17T14:03:49Z
<p>Whgirw: /* Usage */</p>
<hr />
<div>[[Category:Security (Русский)]]<br />
[[Category:File systems (Русский)]]<br />
[[Category:HOWTOs (Русский)]]<br />
{{i18n|Шифрование системы с помощью eCryptfs}}<br />
<br />
= Введение =<br />
В статье описывается базовое использование [https://launchpad.net/ecryptfs eCryptfs]. Статья проведёт вас через процесс установки защифрованной домашней директории,<br />
в которой вы можете хранить личные/секретные данные. Если вы не уверены, нужно ли вам шифрование, прочтите сначала [[System_Encryption_with_LUKS_for_dm-crypt|dm-crypt]].<br />
<br />
Реализация eCryptfs отличается от реализации dm-crypt, которая шифрует блочное устройство полностью, а eCryptfs шифрует вайловую систему - тоесть каждый файл поотдельности. О сравнении двух методов шифрования можно прочитать на [http://ecryptfs.sourceforge.net/ecryptfs-faq.html#compare].<br />
<br />
Если коротко, то eCryptfs не нуждается в резервировании места на диске(создание специального раздела). eCryptfs может быть смонтирован в любую директорию и шифровать её содержимое(например домашняя директория! пользователя или любая директория в сети). Все метаданные для расшифровки хранятся в заголовках файлов, поэтому зашифрованые файлы можно перемещать, копировать, делать резервные копии. Есть и другие плюсы данного метода, как и минусы. Самый большой минус - eCryptfs не может шифровать весь раздел/жёсткий диск. По этому eCryptfs не может зашифровать раздел swap(но вы можете комбинировать eCryptfs и dm-crypt).<br />
<br />
<br />
= Основы =<br />
eCryptfs входит в ядро с версии 2.6.19, но для работы с ней, вам нужны дополнительные инструменты: [http://aur.archlinux.org/packages.php?ID=8397 ecryptfs-utils] и [http://aur.archlinux.org/packages.php?ID=6895 keyutils].<br />
<br />
После установки загрузите модуль ядра:<br />
# modprobe ecryptfs<br />
<br />
Пакет ecryptfs-utils нужен для управления ключами для доступа к зашифрованым данным. Некоторые скрипы из этого пакета помогут автоматизировать весь процесс (''ecryptfs-setup-private'') или помут в комбинировании eCryptfs и dm-crypt для шифрования раздела swap. Мы не будем использовать эти скрипты, а сделаем всё в ручном режиме для лучшего понимания принципа работы данного метода.<br />
<br />
Прежде чем мы начнём, я советую вам прочитать документацию по eCryptfs(man).<br />
<br />
<br />
== Установка ==<br />
Для начала создайте директории, которые вы хотите зашифровать. В этом примере мы назовём директорию - Private.<br />
$ su -<br />
# mkdir -m 700 /home/username/.Private<br />
# mkdir -m 500 /home/username/Private<br />
# chown username:username /home/username/{.Private,Private}<br />
<br />
В сумме получается:<br />
* Зашифрованые данные будут храниться в ~/.Private<br />
* Когда эта директория смонтированна, данные будут доступны в ~/Private<br />
** Когда директория не смонтированна, данные в неё не могут быть записаны<br />
** Когда директория смонтированна, права доступа к ней такие-же как и у ~/.Private<br />
<br />
<br />
eCryptfs может быть смонтированны поверх ~/Private.<br />
# mount -t ecryptfs /home/username/.Private /home/username/Private<br />
<br />
Вам нужно будет ввести пароль и выбрать некоторые опции с которыми директория будет монтироватся в будущем. Так-же вы можете задать несколько различных ключей для шифрования различных данных(об этом ниже). Для краткости мы опишем процесс с одним ключём. <br />
Пример:<br />
Key type: passphrase<br />
Passphrase: ThisIsAVeryWeakPassphrase<br />
Cypher: aes<br />
Key byte: 16<br />
Plaintext passtrough: no<br />
Filename encryption: no<br />
Add signature to cache: yes <br />
<br />
В сумме получается:<br />
* Ваш ключ это ваша так называемая '''mount passphrase''' хранится в виде хэша+соль.<br />
** По теминологии eCryptfs этот ключ называется "file encryption key, encryption key", или '''fekek'''.<br />
* eCryptfs поддерживает несколько методов шифрования AES, blowfish, twofish...<br />
* <br />
* Plaintext passtrough разрешает сохранять и работать с '''не зашифрованными данными''' внутри ~/.Private.<br />
* Шифрование файловой ситемы доступно с версии ядра 2.6.29.<br />
** По теминологии eCryptfs этот ключ, который служит для шифрования имён файлов называется "filename encryption key" или '''fnek'''<br />
* Сигнатура ключа(ей) хранится в {{Filename|/root/.ecryptfs/sig-cache.txt}}.<br />
<br />
<br />
Т.к. мы хотим монтировать директории без прав супер-пользователя, нам нужно переместить директорию с конфигурацией eCryptfs в нашу домашнюю директорию и сделать нас её владельцем:<br />
# mv /root/.ecryptfs /home/username<br />
# chown username:username /home/username/.ecryptfs<br />
<br />
<br />
Установка на этом законченна и директория смонтирована. Вы можете размещать любые файлы в ~/Private и они будут прозрачно зашифрованы. Теперь отмонтируйте директорию и если вы попробуете прочитать содетжимое файлов, вы увидете, что они зашифрованы. Как получить к ним доступ? Смотрите следующий шаг.<br />
<br />
<br />
== Монтирование ==<br />
Когда вам снова понадобятся ваши файлы, вы можете повторить процедуру монтирования описанную выше ислпользую тот-же ключ и опции.<br />
<br />
Каждый раз проделывать эти операции может быть утомительно. Вариант номер один: передать все опции команде монтирования кроме ключа.<br />
<br />
$ sudo mount -t ecryptfs /home/username/.Private /home/username/Private -o ecryptfs_cipher=aes,ecryptfs_key_bytes=16,key=passphrase<br />
<br />
Вариант номер два(рекомендован): добавить строку в '''{{Filename|/etc/fstab}}''':<br />
<br />
# eCryptfs mount points<br />
/home/username/.Private /home/username/Private ecryptfs rw,user,noauto,ecryptfs_sig=XY,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecrypfs_unlink_sigs 0 0<br />
<br />
<br />
ПРИМЕЧАНИЕ:<br />
<br />
* Параметр '''user''' позволяет монтирование с ограничеными правами<br />
* В параметре '''ecryptfs_sig''' замените строку ''XY'' значением сигнатуры (можно взять из '''mtab''' или {{Filename|sig-cache.txt}})<br />
* Если было разрешено шифрование имён файлов, то нужно поставить дополнительный параметр монтирования '''ecryptfs_fnek_sig'''=''XY'', где ''XY'' тоже значение сигнатуры, что и в параметре '''ecryptfs_sig'''<br />
* Последний параметр '''ecrypfs_unlink_sigs''' говорит о том, что при размонтировании ключ из брелка будет удалён<br />
<br />
<br />
Поскольку в процессе размонтирования ключ удаляется из брелка ядра, то для последующего монтировании там необходимо заново создать ключ. Для этого используется утилиты '''ecryptfs-add-passphrase''' или '''ecryptfs-manager''':<br />
<br />
После ввода пароля шифрования можно произвести монтирование:<br />
<br />
$ ecryptfs-add-passphrase<br />
Passphrase: ThisIsAVeryWeakPassphrase<br />
$ mount -i /home/username/Private<br />
<br />
Обратите внимание на параметр '''{{Codeline|-i}}'''. Он предотвращает вызов помощника монтирования. Это означает, что при использовании параметра {{Codeline|-i}} по умолчанию при монтировании будут применены параметры '''nosuid, noexec''' and '''nodev'''. Если в шифрованой папке необходимо иметь также и исполняемые файлы, то можно добавить параметр '''exec''' в файле fstab в строке команды.<br />
<br />
Не лишне также будет вспомнить об утилите '''keyctl''', входящую в состав пакета ''keyutils'', установленного ранее. Она может быть использована для более продвинутого управления ключами. Нижеследующий пример демонстрирует команду для отображения списка имеющихся ключей и команду для очистки этого списка:<br />
$ keyctl list @u<br />
$ keyctl clear @u<br />
<br />
== Применение ==<br />
Помимо использования шифрованой папки для хранения критичных файлов и прочих данных не для чужих глаз, можно так же хранить и данные приложений. К примеру ''Firefox'' имеет не только встроеный менеждер паролей, но и историю посещений и кэш страниц, что может представлять уязвимость. Меры защиты очень просты:<br />
$ mv ~/.mozilla ~/Private/mozilla<br />
$ ln -s ~/Private/mozilla ~/.mozilla<br />
<br />
== Removal ==<br />
If you want to move a file out of the private directory just move it to it's new destination while ~/Private is mounted. Also note that there are no special steps involved if you want to remove your private directory. Make sure it is un-mounted and delete ~/.Private, along with all the files.<br />
<br />
== Backup ==<br />
Setup explained here separates the directory with encrypted data from the mount point, so the encrypted data is available for backup at any time. With an overlay mount (i.e. ''~/Secret'' mounted over ''~/Secret'') the lower, encrypted, data is harder to get to. Today when cronjobs and other automation software do automatic backups the risk of leaking your sensitive data is higher.<br />
<br />
We explained earlier that all cryptographic metadata is stored in the headers of files. You can easily do backups, or incremental backups, of your '''~/.Private''' directory, treating it like any other directory.<br />
<br />
= Advanced =<br />
This wiki article covers only the basic setup of a private encrypted directory. There is however another article about eCryptfs on Arch Linux, which covers encryption of your entire $HOME and encrypting swap space without breaking hibernation (suspend to disk).<br />
<br />
That article includes many more steps (i.e. using PAM modules and automatic mounting) and the author was opposed to replicating it here, because there is just no single "right" way to do it. The author proposes some solutions and discusses the security implications, but they are his solutions and as such might not be the best nor are they endorsed by the eCryptfs project in any way.<br />
<br />
Article: [http://sysphere.org/~anrxc/j/articles/ecryptfs/index.html eCryptfs and $HOME] by Adrian C. (anrxc).<br />
<br />
== PAM Mount ==<br />
The above "''eCryptfs and $HOME''" article uses a shell init file to mount the home directory. The same can be done using [http://aur.archlinux.org/packages.php?ID=1976 pam_mount] with the added benefit that home is un-mounted when all sessions are logged out. As eCryptfs needs the {{Codeline|-i}} switch, the ''lclmount'' setting will need to be changed. I use the following in {{Filename|/etc/security/pam_mount.conf.xml}}:<br />
<lclmount>mount -i %(VOLUME) "%(before=\"-o\" OPTIONS)"</lclmount><br />
<br />
Remember to also set the volume definition (preferably to {{Filename|~/.pam_mount.conf.xml}} and uncomment luserconf).<br />
<pam_mount><br />
<volume noroot="1" fstype="ecryptfs" path="/home/user/.Private" mountpoint="/home/user"/><br />
</pam_mount><br />
<br />
''noroot'' is needed (at least in my configuration) because the encryption key will be added to the user's keyring.<br />
<br />
<br />
To avoid wasting time needlessly unwrapping the passphrase you can create a script that will check ''pmvarrun'' to see the number of open sessions:<br />
#!/bin/sh<br />
#<br />
# /usr/local/bin/doecryptfs<br />
<br />
exit $(/usr/sbin/pmvarrun -u$PAM_USER -o0)<br />
<br />
With the following line added before the eCryptfs unwrap module in your PAM stack:<br />
auth [success=ignore default=1] pam_exec.so quiet /usr/local/bin/doecryptfs<br />
auth required pam_ecryptfs.so unwrap<br />
The article suggests adding these to {{Filename|/etc/pam.d/login}}, but the changes will need to be added to all other places you login, such as {{Filename|/etc/pam.d/kde}}.</div>
Whgirw
https://wiki.archlinux.org/index.php?title=ECryptfs_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=131305
ECryptfs (Русский)
2011-02-17T13:41:02Z
<p>Whgirw: /* Монтирование */</p>
<hr />
<div>[[Category:Security (Русский)]]<br />
[[Category:File systems (Русский)]]<br />
[[Category:HOWTOs (Русский)]]<br />
{{i18n|Шифрование системы с помощью eCryptfs}}<br />
<br />
= Введение =<br />
В статье описывается базовое использование [https://launchpad.net/ecryptfs eCryptfs]. Статья проведёт вас через процесс установки защифрованной домашней директории,<br />
в которой вы можете хранить личные/секретные данные. Если вы не уверены, нужно ли вам шифрование, прочтите сначала [[System_Encryption_with_LUKS_for_dm-crypt|dm-crypt]].<br />
<br />
Реализация eCryptfs отличается от реализации dm-crypt, которая шифрует блочное устройство полностью, а eCryptfs шифрует вайловую систему - тоесть каждый файл поотдельности. О сравнении двух методов шифрования можно прочитать на [http://ecryptfs.sourceforge.net/ecryptfs-faq.html#compare].<br />
<br />
Если коротко, то eCryptfs не нуждается в резервировании места на диске(создание специального раздела). eCryptfs может быть смонтирован в любую директорию и шифровать её содержимое(например домашняя директория! пользователя или любая директория в сети). Все метаданные для расшифровки хранятся в заголовках файлов, поэтому зашифрованые файлы можно перемещать, копировать, делать резервные копии. Есть и другие плюсы данного метода, как и минусы. Самый большой минус - eCryptfs не может шифровать весь раздел/жёсткий диск. По этому eCryptfs не может зашифровать раздел swap(но вы можете комбинировать eCryptfs и dm-crypt).<br />
<br />
<br />
= Основы =<br />
eCryptfs входит в ядро с версии 2.6.19, но для работы с ней, вам нужны дополнительные инструменты: [http://aur.archlinux.org/packages.php?ID=8397 ecryptfs-utils] и [http://aur.archlinux.org/packages.php?ID=6895 keyutils].<br />
<br />
После установки загрузите модуль ядра:<br />
# modprobe ecryptfs<br />
<br />
Пакет ecryptfs-utils нужен для управления ключами для доступа к зашифрованым данным. Некоторые скрипы из этого пакета помогут автоматизировать весь процесс (''ecryptfs-setup-private'') или помут в комбинировании eCryptfs и dm-crypt для шифрования раздела swap. Мы не будем использовать эти скрипты, а сделаем всё в ручном режиме для лучшего понимания принципа работы данного метода.<br />
<br />
Прежде чем мы начнём, я советую вам прочитать документацию по eCryptfs(man).<br />
<br />
<br />
== Установка ==<br />
Для начала создайте директории, которые вы хотите зашифровать. В этом примере мы назовём директорию - Private.<br />
$ su -<br />
# mkdir -m 700 /home/username/.Private<br />
# mkdir -m 500 /home/username/Private<br />
# chown username:username /home/username/{.Private,Private}<br />
<br />
В сумме получается:<br />
* Зашифрованые данные будут храниться в ~/.Private<br />
* Когда эта директория смонтированна, данные будут доступны в ~/Private<br />
** Когда директория не смонтированна, данные в неё не могут быть записаны<br />
** Когда директория смонтированна, права доступа к ней такие-же как и у ~/.Private<br />
<br />
<br />
eCryptfs может быть смонтированны поверх ~/Private.<br />
# mount -t ecryptfs /home/username/.Private /home/username/Private<br />
<br />
Вам нужно будет ввести пароль и выбрать некоторые опции с которыми директория будет монтироватся в будущем. Так-же вы можете задать несколько различных ключей для шифрования различных данных(об этом ниже). Для краткости мы опишем процесс с одним ключём. <br />
Пример:<br />
Key type: passphrase<br />
Passphrase: ThisIsAVeryWeakPassphrase<br />
Cypher: aes<br />
Key byte: 16<br />
Plaintext passtrough: no<br />
Filename encryption: no<br />
Add signature to cache: yes <br />
<br />
В сумме получается:<br />
* Ваш ключ это ваша так называемая '''mount passphrase''' хранится в виде хэша+соль.<br />
** По теминологии eCryptfs этот ключ называется "file encryption key, encryption key", или '''fekek'''.<br />
* eCryptfs поддерживает несколько методов шифрования AES, blowfish, twofish...<br />
* <br />
* Plaintext passtrough разрешает сохранять и работать с '''не зашифрованными данными''' внутри ~/.Private.<br />
* Шифрование файловой ситемы доступно с версии ядра 2.6.29.<br />
** По теминологии eCryptfs этот ключ, который служит для шифрования имён файлов называется "filename encryption key" или '''fnek'''<br />
* Сигнатура ключа(ей) хранится в {{Filename|/root/.ecryptfs/sig-cache.txt}}.<br />
<br />
<br />
Т.к. мы хотим монтировать директории без прав супер-пользователя, нам нужно переместить директорию с конфигурацией eCryptfs в нашу домашнюю директорию и сделать нас её владельцем:<br />
# mv /root/.ecryptfs /home/username<br />
# chown username:username /home/username/.ecryptfs<br />
<br />
<br />
Установка на этом законченна и директория смонтирована. Вы можете размещать любые файлы в ~/Private и они будут прозрачно зашифрованы. Теперь отмонтируйте директорию и если вы попробуете прочитать содетжимое файлов, вы увидете, что они зашифрованы. Как получить к ним доступ? Смотрите следующий шаг.<br />
<br />
<br />
== Монтирование ==<br />
Когда вам снова понадобятся ваши файлы, вы можете повторить процедуру монтирования описанную выше ислпользую тот-же ключ и опции.<br />
<br />
Каждый раз проделывать эти операции может быть утомительно. Вариант номер один: передать все опции команде монтирования кроме ключа.<br />
<br />
$ sudo mount -t ecryptfs /home/username/.Private /home/username/Private -o ecryptfs_cipher=aes,ecryptfs_key_bytes=16,key=passphrase<br />
<br />
Вариант номер два(рекомендован): добавить строку в '''{{Filename|/etc/fstab}}''':<br />
<br />
# eCryptfs mount points<br />
/home/username/.Private /home/username/Private ecryptfs rw,user,noauto,ecryptfs_sig=XY,ecryptfs_cipher=aes,ecryptfs_key_bytes=16,ecrypfs_unlink_sigs 0 0<br />
<br />
<br />
ПРИМЕЧАНИЕ:<br />
<br />
* Параметр '''user''' позволяет монтирование с ограничеными правами<br />
* В параметре '''ecryptfs_sig''' замените строку ''XY'' значением сигнатуры (можно взять из '''mtab''' или {{Filename|sig-cache.txt}})<br />
* Если было разрешено шифрование имён файлов, то нужно поставить дополнительный параметр монтирования '''ecryptfs_fnek_sig'''=''XY'', где ''XY'' тоже значение сигнатуры, что и в параметре '''ecryptfs_sig'''<br />
* Последний параметр '''ecrypfs_unlink_sigs''' говорит о том, что при размонтировании ключ из брелка будет удалён<br />
<br />
<br />
Поскольку в процессе размонтирования ключ удаляется из брелка ядра, то для последующего монтировании там необходимо заново создать ключ. Для этого используется утилиты '''ecryptfs-add-passphrase''' или '''ecryptfs-manager''':<br />
<br />
После ввода пароля шифрования можно произвести монтирование:<br />
<br />
$ ecryptfs-add-passphrase<br />
Passphrase: ThisIsAVeryWeakPassphrase<br />
$ mount -i /home/username/Private<br />
<br />
Обратите внимание на параметр '''{{Codeline|-i}}'''. Он предотвращает вызов помощника монтирования. Это означает, что при использовании параметра {{Codeline|-i}} по умолчанию при монтировании будут применены параметры '''nosuid, noexec''' and '''nodev'''. Если в шифрованой папке необходимо иметь также и исполняемые файлы, то можно добавить параметр '''exec''' в файле fstab в строке команды.<br />
<br />
Не лишне также будет вспомнить об утилите '''keyctl''', входящую в состав пакета ''keyutils'', установленного ранее. Она может быть использована для более продвинутого управления ключами. Нижеследующий пример демонстрирует команду для отображения списка имеющихся ключей и команду для очистки этого списка:<br />
$ keyctl list @u<br />
$ keyctl clear @u<br />
<br />
== Usage ==<br />
Besides using your private directory as storage for sensitive files, and private data, you can also use it to protect application data. Take ''Firefox'' for an example, not only does it have an internal password manager but the browsing history and cache can also be sensitive. Protecting it is easy:<br />
$ mv ~/.mozilla ~/Private/mozilla<br />
$ ln -s ~/Private/mozilla ~/.mozilla<br />
<br />
== Removal ==<br />
If you want to move a file out of the private directory just move it to it's new destination while ~/Private is mounted. Also note that there are no special steps involved if you want to remove your private directory. Make sure it is un-mounted and delete ~/.Private, along with all the files.<br />
<br />
== Backup ==<br />
Setup explained here separates the directory with encrypted data from the mount point, so the encrypted data is available for backup at any time. With an overlay mount (i.e. ''~/Secret'' mounted over ''~/Secret'') the lower, encrypted, data is harder to get to. Today when cronjobs and other automation software do automatic backups the risk of leaking your sensitive data is higher.<br />
<br />
We explained earlier that all cryptographic metadata is stored in the headers of files. You can easily do backups, or incremental backups, of your '''~/.Private''' directory, treating it like any other directory.<br />
<br />
= Advanced =<br />
This wiki article covers only the basic setup of a private encrypted directory. There is however another article about eCryptfs on Arch Linux, which covers encryption of your entire $HOME and encrypting swap space without breaking hibernation (suspend to disk).<br />
<br />
That article includes many more steps (i.e. using PAM modules and automatic mounting) and the author was opposed to replicating it here, because there is just no single "right" way to do it. The author proposes some solutions and discusses the security implications, but they are his solutions and as such might not be the best nor are they endorsed by the eCryptfs project in any way.<br />
<br />
Article: [http://sysphere.org/~anrxc/j/articles/ecryptfs/index.html eCryptfs and $HOME] by Adrian C. (anrxc).<br />
<br />
== PAM Mount ==<br />
The above "''eCryptfs and $HOME''" article uses a shell init file to mount the home directory. The same can be done using [http://aur.archlinux.org/packages.php?ID=1976 pam_mount] with the added benefit that home is un-mounted when all sessions are logged out. As eCryptfs needs the {{Codeline|-i}} switch, the ''lclmount'' setting will need to be changed. I use the following in {{Filename|/etc/security/pam_mount.conf.xml}}:<br />
<lclmount>mount -i %(VOLUME) "%(before=\"-o\" OPTIONS)"</lclmount><br />
<br />
Remember to also set the volume definition (preferably to {{Filename|~/.pam_mount.conf.xml}} and uncomment luserconf).<br />
<pam_mount><br />
<volume noroot="1" fstype="ecryptfs" path="/home/user/.Private" mountpoint="/home/user"/><br />
</pam_mount><br />
<br />
''noroot'' is needed (at least in my configuration) because the encryption key will be added to the user's keyring.<br />
<br />
<br />
To avoid wasting time needlessly unwrapping the passphrase you can create a script that will check ''pmvarrun'' to see the number of open sessions:<br />
#!/bin/sh<br />
#<br />
# /usr/local/bin/doecryptfs<br />
<br />
exit $(/usr/sbin/pmvarrun -u$PAM_USER -o0)<br />
<br />
With the following line added before the eCryptfs unwrap module in your PAM stack:<br />
auth [success=ignore default=1] pam_exec.so quiet /usr/local/bin/doecryptfs<br />
auth required pam_ecryptfs.so unwrap<br />
The article suggests adding these to {{Filename|/etc/pam.d/login}}, but the changes will need to be added to all other places you login, such as {{Filename|/etc/pam.d/kde}}.</div>
Whgirw
https://wiki.archlinux.org/index.php?title=IceWM&diff=121562
IceWM
2010-11-16T19:35:24Z
<p>Whgirw: /* External Resources */</p>
<hr />
<div>[[Category:Stacking WMs (English)]]<br />
{{i18n|IceWM}}<br />
{{stub}}<br />
<br />
== What is IceWM? ==<br />
In Unix computing, IceWM is a window manager for the X Window System graphical infrastructure, written by Marko Maček. It was coded from scratch in C++ and is released under the terms of the GNU Lesser General Public License. It is relatively lightweight in terms of memory and CPU usage, and comes with themes that allow it to imitate the UI of Windows 95, OS/2, Motif, and other graphical user interfaces. (Source: [http://en.wikipedia.org/wiki/Icewm Wikipedia])<br />
<br />
== Installation ==<br />
IceWM is available in [extra] and therefore easily installable:<br />
<pre><br />
# pacman -S icewm<br />
</pre><br />
<br />
Alternatively, the latest version from the testing branch ({{Package AUR|icewm-testing}}) and CVS version ({{Package AUR|icewm-cvs}}) are available from the [[AUR]]. These versions add new features such as RandR support.<br />
<br />
== Configuration ==<br />
Although IceWM configuration is originally text-based, there are GUI-based tools available, notably icewm-utils in [community]. However these tools are relatively old and most users prefer to simply edit the text configuration files.<br />
<br />
To change your icewm configuration from the default, simply copy the default configuration files from <tt>/usr/share/icewm/</tt> to <tt>~/.icewm/</tt>, for example: <br />
<br />
{{Note | Do this as a regular user, not as root.}}<br />
<br />
$ mkdir ~/.icewm/<br />
$ cp -R /usr/share/icewm/* ~/.icewm/<br />
<br />
{{Filename|preferences}} is the core configuration file for IceWM.<br />
{{Filename|menu}} controls the contents of the IceWM application menu.<br />
{{Filename|keys}} allows the user to customize keyboard shortcuts.<br />
<br />
=== Menu ===<br />
MenuMaker (available in [Community]) is a Python script that automatically populates your applications menu based on what is installed in your system. Although this may result in a menu filled with many unwanted applcations, it may still be preferable to manually editing the menu configuration file. When running MenuMaker, use the -f flag to overwrite an existing menu file:<br />
<pre><br />
# mmaker -f icewm<br />
</pre> <br />
<br />
=== Themes ===<br />
Although some themes are included by default, there is a much larger and better selection in the verified [http://aur.archlinux.org/packages.php?do_Details=1&ID=5719&O=0&L=0&C=0&K=icewm&SB=n&SO=a&PP=25&do_MyPackages=0&do_Orphans=0&SeB=nd icewm-themes] package in the repository. Although many have a spartan, 'old Windows' feel, some (ElbergBlue, liquid, etc.) have a more modern look.<br />
<br />
You can also visit [http://www.box-look.org/index.php?xcontentmode=7311 box-look.org] for more themes.<br />
<br />
== File Managers ==<br />
It should be noted that IceWM is a window manager only and therefore does not include a file manager. [[PCManFM]] and Rox Filer enable desktop icons, but iDesk can also be used to achieve this functionality.<br />
{{Note|For a greater listing of file managers, examine the [[:Category:File managers (English)|File managers]] category listing.}}<br />
<br />
== Related Articles ==<br />
* [[Xinitrc]]<br />
<br />
== External Resources ==<br />
* [http://www.icewm.org/ Official IceWM website]<br />
* [http://en.gentoo-wiki.com/wiki/IceWM IceWM - Gentoo Linux Wiki]<br />
* [http://www.osnews.com/story.php/7774/IceWM--The-Cool-Window-Manager/ IceWM - The Cool Window Manager] - Detailed introduction on OSNews<br />
* [http://polishlinux.org/apps/window-managers/icewm-a-desktop-for-windows-emmigrants/ IceWM - A desktop for Windows emigrants] - Overview and tutorial from polishlinux.org</div>
Whgirw
https://wiki.archlinux.org/index.php?title=JWM&diff=118643
JWM
2010-10-04T10:28:44Z
<p>Whgirw: </p>
<hr />
<div>[[Category:Stacking WMs (English)]]<br />
{{i18n|JWM}}<br />
<br />
{{Article summary start}}<br />
{{Article summary text|This article attempts to walk users through the installation and configuration of the JWM window manager.}}<br />
{{Article summary end}}<br />
<br />
= Introduction =<br />
'''JWM''' (Joe's Window Manager) is a featherweight [[Window Manager|window manager]] for the [[Wikipedia:X_Window_System|X11 Window System]] written in [http://en.wikipedia.org/wiki/C_(programming_language) C]; it's under active development and is maintained by [http://joewing.net/about.shtml Joe Wingbermuehle]. <i>...[A]lthough development on JWM has slowed quite a bit, [Joe Wingbermuehle is] still working on it on and off and...will hopefully have a new release ready one of these days</i>.<sup>[1]</sup> JWM uses approximately 5 MB of resident memory under normal operating conditions. As of January 2009, the size of the version present in the [[Official Repositories|official Arch Linux repositories]] is under 76 KB packaged (compare to [[Dwm|dwm]] at under 17 KB) and under 171 KB installed (compare to dwm at 68 KB). A minimally compiled version consumes approximately 136 KB of disk space and occupies under 1500 KB of resident memory. <br />
<br />
JWM is generally regarded as the lightest and fastest stacking window manager available for X11 and is the default window manager base for distributions such as [http://www.puppylinux.org/ Puppy Linux] and [http://damnsmalllinux.org/ Damn Small Linux]. Numerous options allow for great flexibility of layout. Some of the more outstanding features of JWM include ease of configuration (a single [[Wikipedia:XML|XML]] file), native support for customizable panels and buttons and its inclusion of a [[Wikipedia:Taskbar|system tray]] dock.<br />
<br />
<sup>[1]</sup> Wingbermuehle, Joe. <u>News</u>. 06 Sep. 2008. 11 Feb. 2009 <http://joewing.net/index.shtml>.<br />
<br />
= Package Installation =<br />
<br />
{{Package Official|JWM}} is part of the [[Official Repositories|official Arch Linux [community] repository]].<br />
<br />
# pacman -S jwm<br />
<br />
{{Warning|Recent SVN snapshots (e.g. 493) exhibit broken Hyper key mask behavior.|}}<br />
<br />
= Starting JWM =<br />
* Run the xinit program to start the X server and the JWM client program:<br />
$ xinit /usr/bin/jwm<br />
<br />
* Alternatively, add the appropriate entry (e.g. <tt>/usr/bin/jwm</tt> or <tt>exec ck-launch-session /usr/bin/jwm</tt>) in your [[Xinitrc|.xinitrc]] file and run:<br />
$ startx<br />
<br />
* See the ArchWiki entry [[Start X at Boot]] for additional details.<br />
<br />
= Configuration =<br />
== Creating ~/.jwmrc ==<br />
In adherence to the principles of [[The_Arch_Way|The Arch Way]], the look, feel and function of the JWM desktop is controlled by way of a single configuration file: {{Filename|~/.jwmrc}}<br><br />
A sample configuration file is installed upon program installation and is located at {{Filename|/etc/system.jwmrc}}. Create {{Filename|~/.jwmrc}}:<br />
<br />
$ touch {{Filename|~/.jwmrc}}<br />
or<br />
$ cp -i {{Filename|/etc/system.jwmrc}} {{Filename|~/.jwmrc}}<br />
<br />
All that is left at this point is to establish the environment by editing the XML {{Filename|.jwmrc}} file.<br />
* [http://joewing.net/programs/jwm/config.shtml JWM Configuration] details the complete list of tags, attributes and values available for JWM.<br />
<br />
== Overview of Selected Tags ==<br />
<br />
=== <StartupCommand> ===<br />
* Load and fork [http://parcellite.sourceforge.net/ Parcellite] as a background [http://en.wikipedia.org/wiki/Daemon_(computer_software) daemon] when JWM starts:<br />
<StartupCommand>parcellite -d</StartupCommand><br />
<br />
* Quietly connect to and fork the [[Rxvt-unicode|urxvtd]] [http://en.wikipedia.org/wiki/Daemon_(computer_software) daemon] to the current <tt>$DISPLAY</tt> when JWM starts:<br />
<StartupCommand>urxvtd -q -o -f</StartupCommand><br />
<br />
* Recursively force the removal of selected directories as a general housekeeping measure when JWM starts:<br />
<StartupCommand>rm -rf $HOME/.adobe $HOME/.cache $HOME/.local/share/Trash $HOME/.macromedia $HOME/.recently-used.xbel $HOME/.Xauthority</StartupCommand><br />
<br />
* Enable [[DPMS]] (Energy Star) to turn monitor 0:0 off to its lowest state of power consumption state after 900 seconds of screen idle after JWM starts:<br />
<StartupCommand>xset -display :0.0 dpms 0 0 600</StartupCommand><br />
<br />
{{Note|Run the {{filename|xdpyinfo}} command (owned by {{Package Official|xorg-utils}}) to reveal the name of the current display.}}<br />
<br />
=== <Program> ===<br />
* Open [[Thunar]] in a specified directory:<br />
<Program label="Thunar">thunar ~/Desktop</Program><br />
<br />
* Connect to the local [http://www.cups.org/ CUPS] web interface using the preferred web application ([http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html xdg-open]):<br />
<Program label="CUPS Printing">xdg-open [http://www.cups.org/articles.php?L274 http://localhost:631]</Program><br />
<br />
* Iconize and start [http://filezilla-project.org/ FileZilla] with Site Manager opened:<br />
<Program icon="filezilla.png">filezilla -s</Program><br />
<br />
=== <Menu> ===<br />
* Create containers for a list of additional programs to display as a submenus under <tt><RootMenu></tt>:<br />
<Menu label="Sample"><br />
<Program label="Xfburn">xfburn -d</Program><br />
<Program label="urxvt Client">urxvtc</Program><br />
</Menu><br />
<br />
<Menu label="Example"><br />
<Program label="Opera">opera -nolirc -nomail</Program><br />
<Program label="Writer">/opt/openoffice/program/swriter -nologo</Program><br />
</Menu><br />
<br />
=== <RootMenu> ===<br />
* Create a menu container displaying the <tt>label="Test"</tt> of <tt>height="24"</tt> pixels and bound to the left mouse button <code>onroot="1"</code> under <tt><RootMenu></tt>:<br />
<br />
<RootMenu labeled="true" label="Test" height="24" onroot="1"><br />
<Program label="Thunar">thunar ~/Desktop</Program><br />
<Program label="CUPS Printing">xdg-open http://localhost:631</Program><br />
<Program icon="filezilla.png">filezilla -s</Program><br />
<Menu label="Sample"><br />
<Program label="Xfburn">xfburn -d</Program><br />
<Program label="urxvt Client">urxvtc</Program><br />
</Menu><br />
<Menu label="Example"><br />
<Program label="Opera">opera -nolirc -nomail</Program><br />
<Program label="Writer">/usr/lib/openoffice/program/swriter -nologo</Program><br />
</Menu><br />
</RootMenu><br />
<br />
* Create a <i>nested</i> menu container with no label, of <tt>height="32"</tt> pixels, and bound to the right mouse button <code>onroot="3"</code> under <tt><RootMenu></tt>:<br />
<br />
<RootMenu height="32" onroot="3"><br />
<Program label="Thunar">thunar ~/Desktop</Program><br />
<Program label="CUPS Printing">xdg-open http://localhost:631</Program><br />
<Program icon="filezilla.png" label="FileZilla">filezilla -s</Program><br />
<Menu label="Sample"><br />
<Program label="Xfburn">xfburn -d</Program><br />
<Program label="urxvt Client">urxvtc</Program><br />
<Menu label="Example"><br />
<Program label="Opera">opera -nolirc -nomail</Program><br />
<Program label="Writer">/usr/lib/openoffice/program/swriter -nologo</Program><br />
</Menu><br />
</Menu><br />
</RootMenu><br />
<br />
=== <Groups> ===<br />
* Preserve panel space by not displaying <tt>Squeeze</tt> and <tt>Xarchiver</tt> within the <tt><Tasklist></tt>:<br />
<br />
<Group><br />
<Class>Squeeze</Class><br />
<Class>Xarchiver</Class><br />
<Option>nolist</Option><br />
</Group><br />
<br />
* Always start <tt>Firefox</tt> maximized on <tt>desktop:2</tt> without a title bar:<br />
<Group><br />
<Class>Firefox</Class><br />
<Option>maximized</Option><br />
<Option>desktop:2</Option><br />
<Option>notitle</Option><br />
</Group><br />
<br />
==== Window Class ====<br />
<br />
The [http://www.xfree86.org/current/xprop.1.html xprop] utility displays window and font properties in an X server.<br />
<br />
* Set xprop to display the window class name of an application:<br />
xprop WM_CLASS <br />
<br />
* Click on the desired application window to display the string name of the window class:<br />
WM_CLASS(STRING) = "urxvt", "URxvt"<br />
<br />
xprop is part of the {{Package Official|xorg-utils}} package in the Arch Linux [extra] repository.<br />
# pacman -S xorg-utils<br />
<br />
=== <TrayButton> ===<br />
<br />
* Create a panel <tt><TrayButton></tt> displaying the <tt>label="Pattern"</tt> which launches the <tt>root:1</tt> menu:<br />
<br />
<TrayButton label="Pattern">root:1</TrayButton><br />
<br />
=== <Swallow> ===<br />
<br />
* Integrate, or <tt><Swallow></tt> into the tray the program whose <tt>name=wicd-gtk</tt> and allow the named program to execute the command <code>wicd-gtk</code><br />
<br />
<Swallow name="wicd-gtk"><br />
wicd-gtk<br />
</Swallow><br />
<br />
=== <Tray> ===<br />
* Create a panel <tt><Tray></tt> of <tt>height="24"</tt> pixels offset <tt>x="0"</tt> pixels from the left of the screen and <tt>y="0"</tt> from the top of the screen. Display within the panel:<br />
<br />
# A menu <tt><TrayButton></tt> which displays the <tt>root:1</tt> menu.<br />
# A <tt><TaskList/></tt> which displays running applications within the current desktop.<br />
# A <tt><TrayButton></tt> with the text <tt>label="X"</tt> that minimizes open windows to show the root window, or desktop.<br />
# A virtual desktop <tt><Pager/></tt> showing available workspaces.<br />
# The <tt><Swallow></tt> integration of the [[Wicd | Wicd]] network applet.<br />
## It is currently recommended to set <tt>wicd-gtk</tt> within the <StartupCommand> tag.<br />
# For supported applications, a system tray area for programs to <tt><Dock/></tt>.<br />
# A <tt><Clock></tt> which displays the date and time in the specified format.<br />
## [[Wikipedia:Man_page|Man]] <tt>strftime</tt> for time and date character conversion specifications.<br />
<br />
<Tray x="0" y="0" height="24"><br />
<TrayButton label="Pattern">root:1</TrayButton><br />
<TaskList/> <br />
<TrayButton label="X">showdesktop</TrayButton><br />
<Pager/><br />
<Swallow name="wicd-gtk"><br />
wicd-client<br />
</Swallow><br />
<Dock/><br />
<Clock format="%a %b %d %l:%M %p"></Clock><br />
</Tray><br />
<br />
=== <Key> ===<br />
* Bind the <tt>F1</tt> key to launch and display the <tt>root:3</tt> menu:<br />
<Key key="F1">root:1</Key><br />
<br />
* Bind the <tt>Super+l</tt> key combination to lock the screen ([http://www.jwz.org/xscreensaver/ XScreenSaver])<br />
<Key mask="S" key="l">exec:xscreensaver-command -lock</Key><br />
<br />
{{Note| Run the {{filename|xev}} command (owned by {{Package Official|xorg-utils}}) to print the contents of keybound X events to standard output.}}<br />
<br />
=== <Include> ===<br />
Elaborate configurations often <tt><Include></tt> files for ease of maintenance and control<br />
<br />
<Key key="F1">root:1</Key><br />
<Include>./.jwmrc-super-hyper-keys</Include> <br />
<Key mask="S" key="l">exec:xscreensaver-command -lock</Key><br />
<br />
Contents of an example <tt>~/.jwmrc-super-hyper-keys</tt>:<br />
<br />
<Key mask="PH" key="t">exec:thunderbird -addressbook</Key><br />
<Key mask="PH" key="h">exec:htop -u USER --sort-key PERCENT_MEM</Key><br />
<Key mask="PH" key="c">exec:catfish --hidden --path=/usr</Key><br />
<br />
=== <RestartCommand> ===<br />
* Call [http://en.wikipedia.org/wiki/Sync_(Unix) sync] to flush file system buffers before dismounting all mounted [[TrueCrypt|TrueCrypt]] volumes when the user logs out of the current X session:<br />
<RestartCommand>sync; truecrypt -d</RestartCommand><br />
* The <tt><<RestartCommand></tt>< complements, or can take the place of {{filename|$HOME/.bash_logout}} for users working in an X environment.<br />
<br />
=== <ShutdownCommand> ===<br />
* Recursively force the removal of the contents of the <tt>Trash</tt> folder when JWM shuts down<br />
<ShutdownCommand>rm -rf ~/.local/share/Trash/*</ShutdownCommand><br />
{{Note|<tt><ShutdownCommand></tt> does not appear to behave as expected when using <tt>dbus-send</tt> <tt>Shutdown</tt> or <tt>Stop</tt> commands.}}<br />
<br />
== Verifying Configuration Changes ==<br />
$ jwm -p<br />
Runs the native configuration file checking utility of JWM and returns syntax errors (including associated line numbers) present in the configuration file, if any. If the syntax is correct and the configuration file is deemed properly marked up, there is no error code returned. Changes in the configuration file are available immediately after restarting, or refreshing JWM via the <code><Restart/></code> command. There is no need to restart the X server for changes to apply. The <code><Restart/></code> command is made available to the user as a command on the initial root menu. <b>Users are recommended to use this tool in between configuration changes</b> in order to ensure valid markup and a stable environment.<br />
<br />
== Additional Troubleshooting ==<br />
<br />
If X is not already running on <tt>tty1</tt>, <tt>Ctrl+Alt+F1</tt> will allow you to review standard output errors and messages. Man the <tt>script</tt> command for details on how to create a typescript of what is printed to the terminal.<br />
<br />
= Useful Tips & Tricks =<br />
<br />
== Additional Applications ==<br />
* [http://palcal.sourceforge.net/ pal] can be run within <tt><Clock></tt> to provide calendaring support and todo and event lists features.<br />
<Clock format="%a %b %d %l:%M %p">xterm -hold -e pal</Clock><br />
* [http://www.xfce.org/projects/orage/ Orage] can be run within <tt><Clock></tt> to provide calendaring support and todo and event lists features.<br />
* [http://tools.suckless.org/slock slock] can be bound to <tt><Program></tt> and/or <tt><Key></tt> to provide a featherweight X screen lock solution.<br />
* [http://parcellite.sourceforge.net/ Parcellite] can be swallowed within a tray(s) to serve as a lightweight [http://en.wikipedia.org/wiki/X_Window_System X11] clipboard manager.<br />
* [[Conky | Conky]] can be run within the <tt><StartupCommand></tt> to provide the display of various data streams (e.g. battery life and AC adapter status for notebooks).<br />
* [http://pcmanfm.sourceforge.net/ PCMan File Manager] can be used to manage the desktop. The advantage of using PCMan File Manager is that it also doubles as a powerful GUI file manager.<br />
* [http://www.xfce.org/projects/xfdesktop/ Xfce Desktop Manager] (or xfdesktop) can be used to manage the desktop. To circumvent the issue of xfdesktop redrawing over the root desktop window of Conky:<br />
# Review the [http://conky.sourceforge.net/faq.html Conky FAQ] for workarounds in {{Filename|~/.conkyrc}} <br />
# <tt><Group></tt> Conky and specify the following <tt><Option></tt> tags in {{Filename|~/.jwmrc}} <br />
<Group><br />
<Class>Conky</Class><br />
<Option>nolist</Option><br />
<Option>noborder</Option><br />
<Option>notitle</Option><br />
<Option>sticky</Option><br />
</Group><br />
<br />
== Xinitrc Startup Applications ==<br />
Startup applications can be executed outside of the <tt><StartupCommand></tt> by including the appropriate options in <tt>~./xinitrc</tt><br />
<br />
<pre>#!/bin/bash<br />
<br />
/usr/bin/parcellite -d &<br />
/usr/bin/Thunar --daemon &<br />
/usr/bin/urxvtd -q -f -o &<br />
/usr/bin/xcalib -d :0 /usr/share/color/icc/P221W-Native.icc &<br />
/usr/bin/nvidia-settings -a GPUOverclockingState=1 -a GPU2DClockFreqs=640,655 -a GPU3DClockFreqs=640,655 &<br />
/usr/bin/setxkbmap -option terminate:ctrl_alt_bksp &<br />
export OPERAPLUGINWRAPPER_PRIORITY=0<br />
export OPERA_KEEP_BLOCKED_PLUGIN=0<br />
exec ck-launch-session /usr/bin/jwm</pre><br />
<br />
== Improve <Tasklist> Contrast ==<br />
<br />
Change the default <tt><Tasklist></tt> settings to match the improved contrast style of the default <tt><MenuStyle></tt> and active <tt><WindowStyle></tt><br />
<br />
<TaskListStyle><br />
<strike><ActiveForeground>black</ActiveForeground></strike><br />
<strike><ActiveBackground>gray90:gray70</ActiveBackground></strike><br />
</TaskListStyle><br />
<br />
<TaskListStyle><br />
<ActiveForeground>white</ActiveForeground><br />
<ActiveBackground>#70849d:#2e3a67</ActiveBackground><br />
</TaskListStyle><br />
<br />
== Power & Event Management ==<br />
Power and event management commands can be run within <tt><Key></tt> and/or <tt><Program></tt> tags.<br><br />
=== Logout & Refresh ===<br />
<tt><Exit/></tt> (Logout) is the menu command to cleanly log out of the current X server.<br><br />
<tt><Restart/></tt> (Refresh) is the menu command tag which reinitializes the configuration file and updates menus and keybindings accordingly.<br> <br />
<tt><Restart/></tt> and <tt><Exit/></tt> can be bound to the <tt>Ctrl+Alt</tt> modified keys following the example syntax below: <br />
<br />
<Key mask="CA" key="r">exec:jwm -restart</Key><br />
<Key mask="CA" key="e">exec:jwm -exit</Key><br />
<br />
=== Reboot & Shutdown ===<br />
A system with [[sudo | sudo]] installed and properly configured can be rebooted with the <tt>Restart</tt> and <tt>Poweroff</tt> menu options.<br />
<Program label="Restart">sudo reboot</Program><br />
<Program label="Poweroff">sudo poweroff</Program><br />
See the [[Allow users to shutdown|ArchWiki entry regarding allowing users to shutdown]] for additional information.<br />
<br />
{{Box Note|For users wishing to power down a system, 'poweroff' or 'shutdown -P now' may be preferable to 'shutdown -h now' as it leaves no doubt as to the intention of the user initiated command.|}}<br />
<br />
System power and event management can also be handled by [[HAL]] via [http://www.freedesktop.org/wiki/Software/dbus dbus-send] message signals without the need to modify the sudoers file.<br />
<Program label="Restart">dbus-send --system --print-reply --dest=org.freedesktop.Hal /org/freedesktop/Hal/devices/computer org.freedesktop.Hal.Device.SystemPowerManagement.Reboot</Program><br />
<Program label="Shutdown">dbus-send --system --print-reply --dest=org.freedesktop.Hal /org/freedesktop/Hal/devices/computer org.freedesktop.Hal.Device.SystemPowerManagement.Shutdown</Program><br />
<br />
<Key mask="H" key="F4">exec:dbus-send --system --print-reply --dest=org.freedesktop.Hal /org/freedesktop/Hal/devices/computer org.freedesktop.Hal.Device.SystemPowerManagement.Suspend int32:0</Key<br />
<Key mask="H" key="F12>exec:dbus-send --system --print-reply --dest=org.freedesktop.Hal /org/freedesktop/Hal/devices/computer org.freedesktop.Hal.Device.SystemPowerManagement.Hibernate</Key><br />
<br />
System power management can also be handled by [http://www.freedesktop.org/wiki/Software/ConsoleKit ConsoleKit] and [http://upower.freedesktop.org/ UPower] via dbus-send message signals without the need to modify the sudoers file. HAL is not required in this case.<br />
<Program label="Restart">dbus-send --system --print-reply --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Restart</Program><br />
<Program label="Poweroff">dbus-send --system --print-reply --dest=org.freedesktop.ConsoleKit /org/freedesktop/ConsoleKit/Manager org.freedesktop.ConsoleKit.Manager.Stop</Program><br />
<br />
<Key mask="H" key="F4">exec:dbus-send --print-reply --system --dest=org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower.Suspend</Key><br />
<Key mask="H" key="F12>exec:dbus-send --print-reply --system --dest=org.freedesktop.UPower /org/freedesktop/UPower org.freedesktop.UPower.Hibernate</Key><br />
<br />
== Custom Minimal Build ==<br />
Gains in UI response can be gleaned by not using menu icons and by disabling the use of [http://en.wikipedia.org/wiki/Xft Xft] fonts. Further gains can be accomplished by removing support for external libraries with a custom build. The result is also a reduction in resource requirements. A minimal build compiled with Xft support and using Xft fonts is allocated approximately 3 MB of resident and 1.5 MB of shared memory. The same build compiled without Xft support is allocated under 1.5 MB and approximately 1.2 MB, respectively. See the [[Arch Build System]] page for further details.<br />
<br />
=== Minimal PKGBUILD Example ===<br />
<br />
<pre>pkgname=jwm<br />
pkgver=2.0.1<br />
pkgrel=100<br />
pkgdesc="A lightweight window manager for the X11 Window System"<br />
arch=('i686' 'x86_64')<br />
url="http://joewing.net/programs/jwm/"<br />
license=('GPL2')<br />
depends=('libx11')<br />
backup=('etc/system.jwmrc')<br />
source=(http://joewing.net/programs/jwm/releases/jwm-$pkgver.tar.bz2)<br />
md5sums=('48f323cd78ea891172b2a61790e8c0ec')<br />
<br />
build() {<br />
cd ${srcdir/${pkgname}-${pkgver}<br />
<br />
./configure --disable-confirm --disable-icons --disable-png \ <br />
--disable-xpm --disable-jpeg --disable-fribidi --disable-xinerama \<br />
--disable-shape --disable-xft --disable-xrender --disable-debug \ <br />
--prefix=/usr --sysconfdir=/etc<br />
<br />
make<br />
make BINDIR=$pkgdir/usr/bin \<br />
MANDIR=$pkgdir/usr/share/man \<br />
SYSCONF=$pkgdir/etc install<br />
}</pre><br />
<br />
=== Minimal Font Suggestions ===<br />
<br />
<pre><WindowStyle><br />
<Font>-*-fixed-*-r-*-*-10-*-*-*-*-*-*-*</Font><br />
<br />
<TaskListStyle><br />
<Font>-*-fixed-*-r-*-*-13-*-*-*-*-*-*-*</Font><br />
<br />
<TrayStyle><br />
<Font>-*-fixed-*-r-*-*-13-*-*-*-*-*-*-*</Font></pre><br />
<br />
* Man <tt>xfontsel</tt> and review the [[Wikipedia:X_logical_font_description|X Logical Font Description]] article for additional details and pattern descriptions.<br />
<br />
== Manual Tiling Support ==<br />
Tiling support can be added to JWM through the use of the [http://github.com/TheWanderer/poor-man-s-tiling-window-manager/tree/master Poor Man's Tiling Window Manager] python script. Assuming <tt>manage.py</tt> is located in a command directory as part of the local <tt>PATH</tt>, various tiling actions can be keybound according to the example below:<br />
<br />
<Key mask="H" key="Up">exec:manage.py swap</Key><br />
<Key mask="H" key="Down">exec:manage.py cycle</Key><br />
<Key mask="H" key="Left">exec:manage.py left</Key><br />
<Key mask="H" key="Right">exec:manage.py right</Key><br />
<br />
{{Note|Run the {{filename|env}} command to list the modified environments of the current user.}}<br />
<br />
= Package Removal =<br />
<br />
To remove the JWM package while retaining its configuration files and dependencies: <br />
# pacman -R jwm<br />
To remove the JWM package and its configuration files while retaining its dependencies: <br />
# pacman -Rn jwm<br />
To remove the JWM package and dependencies not required by any other packages while retaining its configuration files: <br />
# pacman -Rs jwm<br />
To remove the JWM package, its configuration files and dependencies not required by any other packages: <br />
# pacman -Rns jwm<br />
<br />
{{Note|Pacman will not remove configuration files outside of the defaults that were created during package installation. This includes {{Filename|~/.jwmrc}}}}<br />
<br />
= Additional Resources =<br />
* [http://joewing.net/programs/jwm/index.shtml Joe's Window Manager] - Official Site<br />
<br />
Examples of what can be accomplished with a bit of creativity and substitution can be found at:<br />
* [http://puppylinux.org/wikka/JoesWindowManager PuppyLinux : JoesWindowManager] <br />
* [http://www.murga-linux.com/puppy/viewtopic.php?t=23260 Puppy Linux JWM Themes Exchange]</div>
Whgirw
https://wiki.archlinux.org/index.php?title=GRUB_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=116474
GRUB (Русский)
2010-09-05T15:33:52Z
<p>Whgirw: /* Постоянное наименование устройств */</p>
<hr />
<div>[[Category:Процесс Загрузки]]<br />
[[Category:Руководства]]<br />
{{i18n|GRUB2}}<br />
{{Article summary start}}<br />
{{Article summary text|Covers various aspects of the next generation of the GRand Unified Bootloader (GRUB2).}}<br />
{{Article summary end}}<br />
<br />
<br />
[http://www.gnu.org/software/grub/grub-2.en.html GRUB2] - это следующее поколение GRand Uniform Bootloader (GRUB). GRUB2 основывается на [http://www.nongnu.org/pupa/ PUPA], который является исследовательским проектом, изучающим следующее поколение GRUB. GRUB 2 был переписан с нуля, чтобы исключить мусор и внедрить модульность и портативность.<br />
<br />
Вкратце, загрузчик - это первая программа, которая загружается при старте компьютера. Она отвечает за загрузку и передачу управления ядру Linux. Ядро, в свою очередь, запускает остальную часть операционной системы.<br />
<br />
В данный момент, GRUB де-фа́кто является стандартным загрузчиком LINUX, и в скором времени будет заменён на GRUB2. Когда это случится, "GRUB" станет "GRUB Legacy". <br />
<br />
== Предисловие ==<br />
GRUB2 до сих пор разрабатывается, и мы вынужденны сделать предупреждение. '''Считайте, что вы предупреждены!''' GRUB2 может не оправдать ожиданий, новшества могут отсутствовать, функциональность может изменится. Если нет особой причины использовать GRUB2, пользователь должен использовать более стабильный [[GRUB]].<br />
<br />
=== Замечание для текущих пользователей GRUB ===<br />
<br />
* Существуют различия между командами GRUB и GRUB2. Изучите [http://grub.enbug.org/CommandList команды GRUB2].<br />
<br />
* GRUB2 теперь ''модульный'' и больше не требует "stage 1.5". В результате, загрузчик сам по себе ограничен -- модули загружаются с жёсткого диска по надобности для расширения функциональности.<br />
<br />
* Наименования устройств изменились между GRUB и GRUB2. Разделы нумеруются с 1, приводы с 0. Например, {{Filename|/dev/sda1}} будет ссылатся на {{Codeline|(hd0,1)}} в GRUB2.<br />
<br />
== Установка ==<br />
<br />
GRUB2 может быть установлен через pacman (и заменит grub, если он установлен):<br />
# pacman -S grub2<br />
Также, GRUB2 должен быть установлен в загрузочный сектор диска или раздела, чтобы быть загрузчиком. Это описано в секции [[#Установка загрузчика]].<br />
<br />
=== Установка GRUB2 в процессе установки Arch Linux ===<br />
<br />
* Убедитесь, что сеть правильно настроена.<br />
* Пропустите шаг '''Установка загрузчика''' и выйдите из установщика.<br />
* Из живого окружения установщика, измените корневую папку на установленную систему:<br />
# mount -o bind /dev /mnt/dev<br />
# chroot /mnt bash<br />
* Установите пакет GRUB2:<br />
# pacman -S grub2<br />
<br />
=== Установка загрузчика ===<br />
<br />
GRUB2 должен быть установлен из живого окружения или напрямую из консоли установщика Arch.<br />
<br />
В большинстве случаев, для установки GRUB2 будет достаточно запустить команду '''grub-install''' от пользователя root:<br />
# grub-install /dev/sda<br />
<br />
где {{Filename|/dev/sda}} это место установки (в этом случае, это MBR первого диска SATA).Если вы используете [[LVM]] для вашего {{Filename|/boot}}, вы можете установить GRUB2 на различные физические диски.<br />
<br />
Если при этом происходит ошибка:<br />
<br />
grub-probe: error: Cannot get the real path of '/dev/fd0'<br />
Auto-detection of a filesystem module failed.<br />
Please specify the module with the option '--modules' explicitly.<br />
<br />
Попробуйте добавить {{Codeline|--recheck}} в аргументы как показано ниже:<br />
# grub-install --recheck /dev/sda<br />
<br />
== Настройка ==<br />
<br />
Файл настройки находится в {{Filename|/boot/grub/grub.cfg}}. Редактируйте его так, как сочтёте нужным.<br />
<br />
=== grub-mkconfig ===<br />
<br />
Скрипт grub-mkconfig может быть использован для генерации файла {{Filename|grub.cfg}}. Чтобы получить файл {{Filename|grub.cfg}}, выполните команду:<br />
# grub-mkconfig -o /boot/grub/grub.cfg<br />
<br />
=== grub.cfg ===<br />
<br />
Основные файлы grub используют следующие опции:<br />
* {{Codeline|(hdX,Y)}} - раздел {{Codeline|Y}} на диске {{Codeline|X}}, нумерация разделов начинается с 1,дисков с 0<br />
* {{Codeline|1=set default=N}} - это загрузка записи с номером N, которую делает загрузчик после истечения таймера на действие пользователя.<br />
* {{Codeline|1=set timeout=M}} - это время {{Codeline|M}} ожидания в секундах для выбора пользователя, до того, как система по умолчанию не будет загружена.<br />
* {{Codeline|<nowiki>menuentry "title" {entry options}</nowiki>}} - это название загрузочной записи {{Codeline|title}}<br />
* {{Codeline|1=set root=(hdX,Y)}} устанавливает загрузочный раздел, где хранится ядро и модули GRUB (boot может быть не отдельным разделом, а просто папкой в корневом разделе ({{Filename|/}})<br />
<br />
Пример конфигурации:<br />
<br />
{{File<br />
|name=/boot/grub/grub.cfg<br />
|content=<nowiki><br />
# Config file for GRUB2 - The GNU GRand Unified Bootloader<br />
# /boot/grub/grub.cfg<br />
<br />
# DEVICE NAME CONVERSIONS<br />
#<br />
# Linux Grub<br />
# -------------------------<br />
# /dev/fd0 (fd0)<br />
# /dev/sda (hd0)<br />
# /dev/sdb2 (hd1,2)<br />
# /dev/sda3 (hd0,3)<br />
#<br />
<br />
# Timeout for menu<br />
set timeout=5<br />
<br />
# Set default boot entry as Entry 0<br />
set default=0<br />
<br />
# (0) Arch Linux<br />
menuentry "Arch Linux" {<br />
set root=(hd0,1)<br />
linux /vmlinuz26 root=/dev/sda3 ro<br />
initrd /kernel26.img<br />
}<br />
<br />
## (1) Windows<br />
#menuentry "Windows" {<br />
#set root=(hd0,3)<br />
#chainloader +1<br />
#}<br />
</nowiki>}}<br />
<br />
Если у вас нет отдельного раздела boot, {{Codeline|'/boot'}} должен присутствовать в указании пути в {{Filename|grub.cfg}}. Пример:<br />
<br />
# (0) Arch Linux<br />
menuentry "Arch Linux" {<br />
set root=(hd0,1)<br />
linux /boot/vmlinuz26 root=/dev/sda1 ro<br />
initrd /boot/kernel26.img<br />
}<br />
<br />
=== Мультизагрузка ===<br />
<br />
Существует два самых распространённых пути настройки файла {{Filename|grub.cfg}}.<br />
<br />
==== С GNU/Linux ====<br />
<br />
Если другой дистрибутив на разделе {{Filename|sda2}}:<br />
<br />
menuentry "Other Linux" {<br />
set root=(hd0,2)<br />
linux /boot/vmlinuz (add other options here as required)<br />
initrd /boot/initrd.img (if the other kernel uses/needs one)<br />
}<br />
<br />
==== С Windows ====<br />
<br />
Добавьте это в конец файла {{Filename|/boot/grub/grub.cfg}}. В этом случае ваш Windows находится на разделе {{Filename|sda3}}.<br />
<br />
# (2) Windows XP<br />
menuentry "Windows XP" {<br />
set root=(hd0,3)<br />
chainloader +1<br />
}<br />
<br />
==== С Windows при помощи EasyBCD и NeoGRUB ====<br />
<br />
До тех пор, пока EasyBCD's NeoGRUB не совместимы с форматом меню GRUB2, установите цепную загрузку через них, заменив содержимое файла {{Filename|C:\NST\menu.lst}} на строки, подобные следующим:<br />
<br />
default 0<br />
timeout 1<br />
<br />
title Chainload into GRUB v2<br />
root (hd0,7)<br />
kernel /boot/grub/core.img<br />
<br />
===Визуальная настройка===<br />
<br />
В GRUB2 это возможно сделать, меняя вид меню.<br />
<br />
====Фоновое изображение и растровые шрифты====<br />
<br />
GRUB2 имеет поддержку фоновых изображений и растровых шрифтов в формате pf2. Шрифты unifont включены в пакет grub2 под именем {{Filename|unicode.pf2}}, или, как только ascii знаки, под именем {{Filename|ascii.pf2}}. Поддерживаемые форматы изображений включают tga, png и jpeg, (обеспечивается загрузкой нужных модулей). Максимальное поддерживаемое разрешение зависит от вашего оборудования. Пример настройки, устанавливающий tga файл как фоновое изображение показан ниже:<br />
<br />
if loadfont /usr/share/grub/unicode.pf2 ; then<br />
set gfxmode="1024x768x32"<br />
insmod gfxterm<br />
insmod vbe<br />
terminal_output gfxterm<br />
if terminal_output gfxterm; then true ; else<br />
terminal gfxterm<br />
fi<br />
fi<br />
insmod tga<br />
background_image /boot/grub/archlinux.tga<br />
<br />
{{Note|Если этот пример вам не подходит, попробуйте заменить {{Codeline|1=gfxmode="1024x768x32"}} на {{Codeline|1=vbemode="0x105"}}.}}<br />
{{Note|Чтобы показать все режимы, которые вы можете использовать, введите команду {{Codeline|1=vbeinfo}} в командной строке grub2 (вы должны загрузить модуль vbe перед этим).}}<br />
{{Note|Если у вас Grub установлен на отдельный раздел, /boot/grub/archlinux.tga заменяется на /grub/archlinux.tga.}}<br />
<br />
====Цвета меню====<br />
<br />
Чтобы изменить цвета в GRUB2, вы должны сделать настройку в файле {{Filename|/boot/grub/grub.cfg}}. Например, цвета по умолчанию для Arch:<br />
<br />
set menu_color_normal=light-blue/black<br />
set menu_color_highlight=light-cyan/blue<br />
<br />
Доступные цвета для GRUB2 находятся на сайте: http://www.gnu.org/software/grub/manual/html_node/color.html.<br />
<br />
====Скрытое меню====<br />
<br />
Для скрытого меню вставьте эти строки в файл grub.cfg после инициализации картинки, но до ''menuentries'' (например: background_image /boot/grub/archlinux.tga).<br />
<br />
set timeout=5<br />
<br />
echo -n "Press ESC to see the menu... "<br />
if sleep --verbose --interruptible 5 ; then<br />
set timeout=0<br />
fi<br />
<br />
====Установка разрешения буфера кадров====<br />
<br />
Чтобы изменить разрешение буфера кадров в grub2, добавьте строку, подобную этой, в раздел ''linux'' в grub.cfg:<br />
<br />
video=vesafb:mode=1024x768-32 vga=790<br />
<br />
В следующей формулировке, режим=<разрешение>-<глубина цвета> vga=<разрешение буфера кадров> используется, где разрешение буфера кадров можно найти по следующей схеме:<br />
<br />
+-------------------------------------------------+<br />
| 640x480 800x600 1024x768 1280x1024<br />
----+--------------------------------------------<br />
256 | 0x301=769 0x303=771 0x305=773 0x307=775<br />
32K | 0x310=784 0x313=787 0x316=790 0x319=793<br />
64K | 0x311=785 0x314=788 0x317=791 0x31A=794<br />
16M | 0x312=786 0x315=789 0x318=792 0x31B=795<br />
+-------------------------------------------------+<br />
<br />
Убедитесь, что вы вставили следующую строку где-нибудь, (insmod обычно можно найти на верху файла grub.cfg):<br />
<br />
insmod vbe<br />
<br />
=== Другие настойки ===<br />
<br />
==== LVM ====<br />
<br />
Если вы используете [[LVM]] для {{Filename|/boot}}, добавьте следующую строку после до строк menuentry:<br />
<br />
insmod lvm<br />
<br />
и обозначьте ваш root в menuentry как:<br />
<br />
set root=(''lvm_group_name''-''lvm_logical_boot_partition_name'')<br />
<br />
Пример:<br />
<br />
# (0) Arch Linux<br />
menuentry "Arch Linux" {<br />
insmod lvm<br />
set root=(VolumeGroup-lv_boot)<br />
# you can only set following two lines<br />
linux /vmlinuz26 root=/dev/mapper/VolumeGroup-root ro<br />
initrd /kernel26.img<br />
}<br />
<br />
==== Постоянное наименование устройств ====<br />
<br />
Чтобы просмотреть UUIDs, наберите:<br />
# blkid<br />
<br />
Замените линию {{Codeline|root}} следующей:<br />
<br />
linux /vmlinuz26 root=/dev/disk/by-uuid/<UUID> ro<br />
<br />
Тем не менее, вы ещё должны установить упоминание о Grub2's в раздел root. Чтобы сделать это, используйте команду {{Codeline|search}}. Так мы устанавливаем переменную grub'а "root" через поиск раздела по его UUID'у:<br />
<br />
search --fs-uuid <UUID> --set=root<br />
Пример содержимого загрузочной записи, использующей Постоянное наименование устройств будет выглядеть так:<br />
<br />
menuentry "Arch Linux" {<br />
search --fs-uuid 355ccb5c-99e1-400d-b612-451f9247e35e --set root<br />
linux /boot/vmlinuz26 root=/dev/disk/by-uuid/355ccb5c-99e1-400d-b612-451f9247e35e ro<br />
initrd /boot/kernel26.img<br />
}<br />
<br />
==== Использование меток ====<br />
<br />
Есть возможность использовать метки - легко читаемые записи, присоединяемые к файловым системам при помощи опции {{Codeline|--label}} в {{Codeline|search}}. Сначала, пометьте ваши сущестующие разделы:<br />
<br />
# tune2fs -L a <LABEL> <PARTITION><br />
<br />
Затем, добавьте содержимое используя метки. Например:<br />
<br />
menuentry "Arch Linux, session texte" {<br />
search --label archroot --set root<br />
linux /boot/vmlinuz26 root=/dev/disk/by-label/archroot ro<br />
initrd /boot/kernel26.img<br />
}<br />
<br />
== Использование командной строки ==<br />
<br />
Так как MBR слишком мал, чтобы хранить все модули GRUB2, здесь располагаются только меню и несколько базовых команд. Основная часть функциональности GRUB2 заложена в модулях в {{Filename|/boot/grub}}, которые загружаются по надобности. В случае возникновения ошибки GRUB2 может не загрузится. Тогда появится командная строка.<br />
<br />
GRUB2 поддерживает много консолей. Если есть проблема чтения меню, но загрузчик может найти диски, вас перебросит в "нормальную" консоль.<br />
<br />
sh:grub><br />
<br />
Если проблема серьёзная, (напримерЮ GRUB не может найти требуемые файлы),вас перебросит в консоль "восстановления".<br />
<br />
grub rescue><br />
<br />
Консоль восстановления - это ограниченная версия обычной консоли, с меньшей функциональностью. Если вы переброшены в консоль восстановления, сначала попытаетесь загрузить модуль нормальной консоли, затем запустите её.<br />
<br />
grub rescue> set prefix=(hdX,Y)/boot/grub<br />
grub rescue> insmod (hdX,Y)/boot/grub/normal.mod<br />
rescue:grub> normal<br />
<br />
== Использование консоли восстановления ==<br />
<br />
Сначала прочтите [[#Использование командной строки]]. Если невозможно активировать нормальную консоль, возможным решением может стать загрузка с Живого CD (LiveCD), или с других дисков восстановления чтобы исправить настройки и переустановить GRUB. Тем не менее, загрузочные диски не всегда доступны или необходимы.<br />
<br />
Доступные команды в этой консоли включают "insmod", "ls", "set", и "unset". В следующем примере используется "set" и "insmod". "set" изменяет переменные, а "insmod" загружает модули для повышения функциональности.<br />
<br />
Перед началом, пользователь должен знать местоположение своей папки {{Filename|/boot}} (будь она отдельным разделом, или подпапкой в корневом разделе):<br />
<br />
grub rescue> set prefix=(hdX,Y)/boot/grub<br />
<br />
Где Х - это номер физического диска и Y - номер раздела.<br />
<br />
Чтобы расширить возможности консоли, загрузите модуль "linux":<br />
<br />
grub rescue> insmod (hdX,Y)/boot/grub/linux.mod<br />
<br />
{{Note|Если у вас отдельный boot раздел, исключите {{Filename|/boot}} из пути, (например, пишите {{Codeline|1=set prefix=(hdX,Y)/grub}} и {{Codeline|insmod (hdX,Y)/grub/linux.mod}}).}}<br />
<br />
Это описание "linux" и "initrd" команд, которые должны быть вам знакомы (смотри [[#Настройка]]).<br />
<br />
Например, загрузка Arch Linux:<br />
<br />
set root=(hd0,5)<br />
linux /boot/vmlinuz26 root=/dev/sda5<br />
initrd /boot/kernel26.img<br />
boot<br />
<br />
С отдельным разделом boot измените пути, как было описано выше. Например:<br />
<br />
set root=(hd0,5)<br />
linux /vmlinuz26 root=/dev/sda6<br />
initrd /kernel26.img<br />
boot<br />
<br />
После успешной загрузки Arch Linux, пользователь сможет подкорректировать {{Filename|grub.cfg}} и затем запустить:<br />
<br />
# grub-install /dev/sda<br />
<br />
для того, чтобы переустановить GRUB2 и полностью устранить проблему. Измените {{Filename|/dev/sda}}, если требуется. Смотрите [[#Установка загрузчика]] для детальной информации.<br />
<br />
== Примеры исправления проблем ==<br />
<br />
Добавьте сюда сами.<br />
<br />
=== Сообщение об ошибке msdos-style ===<br />
<br />
grub-setup: warn: This msdos-style partition label has no post-MBR gap; embedding won't be possible!<br />
grub-setup: warn: Embedding is not possible. GRUB can only be installed in this setup by using blocklists.<br />
However, blocklists are UNRELIABLE and its use is discouraged.<br />
grub-setup: error: If you really want blocklists, use --force.<br />
<br />
Эта ошибка может возникнуть, когда вы попытаетесь установить в виртуальную машину VMware. Читайте больше об этом [http://bbs.archlinux.org/viewtopic.php?pid=581760#p581760 здесь].<br />
<br />
Это также может случится, если первый раздел начинается сразу после MBR, без необходимого места в 60 блоков перед первым разделом.<br />
<br />
=== Grub-install вызывает зависание grub2 / legacy grub ===<br />
Отключите флоппи дисковод в биосе, даже если у вас его нет. Попробуйте использовать также --no-floppy и удалить fd0 строку из /boot/grub/device.map. Тем не менее, без отключения его в биосе, GRUB2 может всё равно не работать.<br />
<br />
=== Прочее ===<br />
Я не нашёл, как удалять grub1, и установил grub2 в MBR, но после этого он не стал по умолчанию загружаться. Загружался по умолчанию grub1. Лёгкий способ это исправить, это переименовать {{Filename|menu.lst.pacsave}} или подобное, в {{Filename|menu.lst}} (в /boot/grub/) для каждой строки меню, для которой вы хотите использовать grub2. В конце введите {{Codeline|"chainloader +1"}}. Это даст команду grub1 вернуть контроль к grub2.<br />
<br />
Возможное решение: Допустим, boot раздел {{Codeline|(hd0,1)}}, и корневой раздел {{Codeline|(hd0,3)}} (grub2 наименование). grub-setup ищет {{Filename|(hd0,3)/boot/grub/core.img}}. Он не может его найти просто потому, что он в {{Filename|(hd0,1)/grub/core.img}}. Я скопировал папку grub в мою корневую дерикторию, и всё заработало отлично:<br />
<br />
Например (от root:)<br />
# mount /boot<br />
# cp -a /boot/grub /<br />
# umount /boot<br />
# mv /grub /boot/<br />
# grub-install /dev/sda</div>
Whgirw
https://wiki.archlinux.org/index.php?title=GRUB_(%D0%A0%D1%83%D1%81%D1%81%D0%BA%D0%B8%D0%B9)&diff=116466
GRUB (Русский)
2010-09-05T13:05:18Z
<p>Whgirw: /* grub.cfg */</p>
<hr />
<div>[[Category:Процесс Загрузки]]<br />
[[Category:Руководства]]<br />
{{i18n|GRUB2}}<br />
{{Article summary start}}<br />
{{Article summary text|Covers various aspects of the next generation of the GRand Unified Bootloader (GRUB2).}}<br />
{{Article summary end}}<br />
<br />
<br />
[http://www.gnu.org/software/grub/grub-2.en.html GRUB2] - это следующее поколение GRand Uniform Bootloader (GRUB). GRUB2 основывается на [http://www.nongnu.org/pupa/ PUPA], который является исследовательским проектом, изучающим следующее поколение GRUB. GRUB 2 был переписан с нуля, чтобы исключить мусор и внедрить модульность и портативность.<br />
<br />
Вкратце, загрузчик - это первая программа, которая загружается при старте компьютера. Она отвечает за загрузку и передачу управления ядру Linux. Ядро, в свою очередь, запускает остальную часть операционной системы.<br />
<br />
В данный момент, GRUB де-фа́кто является стандартным загрузчиком LINUX, и в скором времени будет заменён на GRUB2. Когда это случится, "GRUB" станет "GRUB Legacy". <br />
<br />
== Предисловие ==<br />
GRUB2 до сих пор разрабатывается, и мы вынужденны сделать предупреждение. '''Считайте, что вы предупреждены!''' GRUB2 может не оправдать ожиданий, новшества могут отсутствовать, функциональность может изменится. Если нет особой причины использовать GRUB2, пользователь должен использовать более стабильный [[GRUB]].<br />
<br />
=== Замечание для текущих пользователей GRUB ===<br />
<br />
* Существуют различия между командами GRUB и GRUB2. Изучите [http://grub.enbug.org/CommandList команды GRUB2].<br />
<br />
* GRUB2 теперь ''модульный'' и больше не требует "stage 1.5". В результате, загрузчик сам по себе ограничен -- модули загружаются с жёсткого диска по надобности для расширения функциональности.<br />
<br />
* Наименования устройств изменились между GRUB и GRUB2. Разделы нумеруются с 1, приводы с 0. Например, {{Filename|/dev/sda1}} будет ссылатся на {{Codeline|(hd0,1)}} в GRUB2.<br />
<br />
== Установка ==<br />
<br />
GRUB2 может быть установлен через pacman (и заменит grub, если он установлен):<br />
# pacman -S grub2<br />
Также, GRUB2 должен быть установлен в загрузочный сектор диска или раздела, чтобы быть загрузчиком. Это описано в секции [[#Установка загрузчика]].<br />
<br />
=== Установка GRUB2 в процессе установки Arch Linux ===<br />
<br />
* Убедитесь, что сеть правильно настроена.<br />
* Пропустите шаг '''Установка загрузчика''' и выйдите из установщика.<br />
* Из живого окружения установщика, измените корневую папку на установленную систему:<br />
# mount -o bind /dev /mnt/dev<br />
# chroot /mnt bash<br />
* Установите пакет GRUB2:<br />
# pacman -S grub2<br />
<br />
=== Установка загрузчика ===<br />
<br />
GRUB2 должен быть установлен из живого окружения или напрямую из консоли установщика Arch.<br />
<br />
В большинстве случаев, для установки GRUB2 будет достаточно запустить команду '''grub-install''' от пользователя root:<br />
# grub-install /dev/sda<br />
<br />
где {{Filename|/dev/sda}} это место установки (в этом случае, это MBR первого диска SATA).Если вы используете [[LVM]] для вашего {{Filename|/boot}}, вы можете установить GRUB2 на различные физические диски.<br />
<br />
Если при этом происходит ошибка:<br />
<br />
grub-probe: error: Cannot get the real path of '/dev/fd0'<br />
Auto-detection of a filesystem module failed.<br />
Please specify the module with the option '--modules' explicitly.<br />
<br />
Попробуйте добавить {{Codeline|--recheck}} в аргументы как показано ниже:<br />
# grub-install --recheck /dev/sda<br />
<br />
== Настройка ==<br />
<br />
Файл настройки находится в {{Filename|/boot/grub/grub.cfg}}. Редактируйте его так, как сочтёте нужным.<br />
<br />
=== grub-mkconfig ===<br />
<br />
Скрипт grub-mkconfig может быть использован для генерации файла {{Filename|grub.cfg}}. Чтобы получить файл {{Filename|grub.cfg}}, выполните команду:<br />
# grub-mkconfig -o /boot/grub/grub.cfg<br />
<br />
=== grub.cfg ===<br />
<br />
Основные файлы grub используют следующие опции:<br />
* {{Codeline|(hdX,Y)}} - раздел {{Codeline|Y}} на диске {{Codeline|X}}, нумерация разделов начинается с 1,дисков с 0<br />
* {{Codeline|1=set default=N}} - это загрузка записи с номером N, которую делает загрузчик после истечения таймера на действие пользователя.<br />
* {{Codeline|1=set timeout=M}} - это время {{Codeline|M}} ожидания в секундах для выбора пользователя, до того, как система по умолчанию не будет загружена.<br />
* {{Codeline|<nowiki>menuentry "title" {entry options}</nowiki>}} - это название загрузочной записи {{Codeline|title}}<br />
* {{Codeline|1=set root=(hdX,Y)}} устанавливает загрузочный раздел, где хранится ядро и модули GRUB (boot может быть не отдельным разделом, а просто папкой в корневом разделе ({{Filename|/}})<br />
<br />
Пример конфигурации:<br />
<br />
{{File<br />
|name=/boot/grub/grub.cfg<br />
|content=<nowiki><br />
# Config file for GRUB2 - The GNU GRand Unified Bootloader<br />
# /boot/grub/grub.cfg<br />
<br />
# DEVICE NAME CONVERSIONS<br />
#<br />
# Linux Grub<br />
# -------------------------<br />
# /dev/fd0 (fd0)<br />
# /dev/sda (hd0)<br />
# /dev/sdb2 (hd1,2)<br />
# /dev/sda3 (hd0,3)<br />
#<br />
<br />
# Timeout for menu<br />
set timeout=5<br />
<br />
# Set default boot entry as Entry 0<br />
set default=0<br />
<br />
# (0) Arch Linux<br />
menuentry "Arch Linux" {<br />
set root=(hd0,1)<br />
linux /vmlinuz26 root=/dev/sda3 ro<br />
initrd /kernel26.img<br />
}<br />
<br />
## (1) Windows<br />
#menuentry "Windows" {<br />
#set root=(hd0,3)<br />
#chainloader +1<br />
#}<br />
</nowiki>}}<br />
<br />
Если у вас нет отдельного раздела boot, {{Codeline|'/boot'}} должен присутствовать в указании пути в {{Filename|grub.cfg}}. Пример:<br />
<br />
# (0) Arch Linux<br />
menuentry "Arch Linux" {<br />
set root=(hd0,1)<br />
linux /boot/vmlinuz26 root=/dev/sda1 ro<br />
initrd /boot/kernel26.img<br />
}<br />
<br />
=== Мультизагрузка ===<br />
<br />
Существует два самых распространённых пути настройки файла {{Filename|grub.cfg}}.<br />
<br />
==== С GNU/Linux ====<br />
<br />
Если другой дистрибутив на разделе {{Filename|sda2}}:<br />
<br />
menuentry "Other Linux" {<br />
set root=(hd0,2)<br />
linux /boot/vmlinuz (add other options here as required)<br />
initrd /boot/initrd.img (if the other kernel uses/needs one)<br />
}<br />
<br />
==== С Windows ====<br />
<br />
Добавьте это в конец файла {{Filename|/boot/grub/grub.cfg}}. В этом случае ваш Windows находится на разделе {{Filename|sda3}}.<br />
<br />
# (2) Windows XP<br />
menuentry "Windows XP" {<br />
set root=(hd0,3)<br />
chainloader +1<br />
}<br />
<br />
==== С Windows при помощи EasyBCD и NeoGRUB ====<br />
<br />
До тех пор, пока EasyBCD's NeoGRUB не совместимы с форматом меню GRUB2, установите цепную загрузку через них, заменив содержимое файла {{Filename|C:\NST\menu.lst}} на строки, подобные следующим:<br />
<br />
default 0<br />
timeout 1<br />
<br />
title Chainload into GRUB v2<br />
root (hd0,7)<br />
kernel /boot/grub/core.img<br />
<br />
===Визуальная настройка===<br />
<br />
В GRUB2 это возможно сделать, меняя вид меню.<br />
<br />
====Фоновое изображение и растровые шрифты====<br />
<br />
GRUB2 имеет поддержку фоновых изображений и растровых шрифтов в формате pf2. Шрифты unifont включены в пакет grub2 под именем {{Filename|unicode.pf2}}, или, как только ascii знаки, под именем {{Filename|ascii.pf2}}. Поддерживаемые форматы изображений включают tga, png и jpeg, (обеспечивается загрузкой нужных модулей). Максимальное поддерживаемое разрешение зависит от вашего оборудования. Пример настройки, устанавливающий tga файл как фоновое изображение показан ниже:<br />
<br />
if loadfont /usr/share/grub/unicode.pf2 ; then<br />
set gfxmode="1024x768x32"<br />
insmod gfxterm<br />
insmod vbe<br />
terminal_output gfxterm<br />
if terminal_output gfxterm; then true ; else<br />
terminal gfxterm<br />
fi<br />
fi<br />
insmod tga<br />
background_image /boot/grub/archlinux.tga<br />
<br />
{{Note|Если этот пример вам не подходит, попробуйте заменить {{Codeline|1=gfxmode="1024x768x32"}} на {{Codeline|1=vbemode="0x105"}}.}}<br />
{{Note|Чтобы показать все режимы, которые вы можете использовать, введите команду {{Codeline|1=vbeinfo}} в командной строке grub2 (вы должны загрузить модуль vbe перед этим).}}<br />
{{Note|Если у вас Grub установлен на отдельный раздел, /boot/grub/archlinux.tga заменяется на /grub/archlinux.tga.}}<br />
<br />
====Цвета меню====<br />
<br />
Чтобы изменить цвета в GRUB2, вы должны сделать настройку в файле {{Filename|/boot/grub/grub.cfg}}. Например, цвета по умолчанию для Arch:<br />
<br />
set menu_color_normal=light-blue/black<br />
set menu_color_highlight=light-cyan/blue<br />
<br />
Доступные цвета для GRUB2 находятся на сайте: http://www.gnu.org/software/grub/manual/html_node/color.html.<br />
<br />
====Скрытое меню====<br />
<br />
Для скрытого меню вставьте эти строки в файл grub.cfg после инициализации картинки, но до ''menuentries'' (например: background_image /boot/grub/archlinux.tga).<br />
<br />
set timeout=5<br />
<br />
echo -n "Press ESC to see the menu... "<br />
if sleep --verbose --interruptible 5 ; then<br />
set timeout=0<br />
fi<br />
<br />
====Установка разрешения буфера кадров====<br />
<br />
Чтобы изменить разрешение буфера кадров в grub2, добавьте строку, подобную этой, в раздел ''linux'' в grub.cfg:<br />
<br />
video=vesafb:mode=1024x768-32 vga=790<br />
<br />
В следующей формулировке, режим=<разрешение>-<глубина цвета> vga=<разрешение буфера кадров> используется, где разрешение буфера кадров можно найти по следующей схеме:<br />
<br />
+-------------------------------------------------+<br />
| 640x480 800x600 1024x768 1280x1024<br />
----+--------------------------------------------<br />
256 | 0x301=769 0x303=771 0x305=773 0x307=775<br />
32K | 0x310=784 0x313=787 0x316=790 0x319=793<br />
64K | 0x311=785 0x314=788 0x317=791 0x31A=794<br />
16M | 0x312=786 0x315=789 0x318=792 0x31B=795<br />
+-------------------------------------------------+<br />
<br />
Убедитесь, что вы вставили следующую строку где-нибудь, (insmod обычно можно найти на верху файла grub.cfg):<br />
<br />
insmod vbe<br />
<br />
=== Другие настойки ===<br />
<br />
==== LVM ====<br />
<br />
Если вы используете [[LVM]] для {{Filename|/boot}}, добавьте следующую строку после до строк menuentry:<br />
<br />
insmod lvm<br />
<br />
и обозначьте ваш root в menuentry как:<br />
<br />
set root=(''lvm_group_name''-''lvm_logical_boot_partition_name'')<br />
<br />
Пример:<br />
<br />
# (0) Arch Linux<br />
menuentry "Arch Linux" {<br />
insmod lvm<br />
set root=(VolumeGroup-lv_boot)<br />
# you can only set following two lines<br />
linux /vmlinuz26 root=/dev/mapper/VolumeGroup-root ro<br />
initrd /kernel26.img<br />
}<br />
<br />
==== Постоянное наименование устройств ====<br />
<br />
Чтобы просмотреть UUIDs, наберите:<br />
# blkid<br />
<br />
Замените линию {{Codeline|root}} следующей:<br />
<br />
linux /vmlinuz26 root=/dev/disk/by-uuid/<UUID> ro<br />
<br />
Тем не менее, вы ещё должны установить упоминание о Grub2's в раздел root. Чтобы сделать это, используйте команду {{Codeline|search}}:<br />
<br />
search --fs-uuid <UUID> --set root<br />
<br />
Пример содержимого загрузочной записи, использующей Постоянное наименование устройств будет выглядеть так:<br />
<br />
menuentry "Arch Linux" {<br />
search --fs-uuid 355ccb5c-99e1-400d-b612-451f9247e35e --set root<br />
linux /boot/vmlinuz26 root=/dev/disk/by-uuid/355ccb5c-99e1-400d-b612-451f9247e35e ro<br />
initrd /boot/kernel26.img<br />
}<br />
<br />
<br />
==== Использование меток ====<br />
<br />
Есть возможность использовать метки - легко читаемые записи, присоединяемые к файловым системам при помощи опции {{Codeline|--label}} в {{Codeline|search}}. Сначала, пометьте ваши сущестующие разделы:<br />
<br />
# tune2fs -L a <LABEL> <PARTITION><br />
<br />
Затем, добавьте содержимое используя метки. Например:<br />
<br />
menuentry "Arch Linux, session texte" {<br />
search --label archroot --set root<br />
linux /boot/vmlinuz26 root=/dev/disk/by-label/archroot ro<br />
initrd /boot/kernel26.img<br />
}<br />
<br />
== Использование командной строки ==<br />
<br />
Так как MBR слишком мал, чтобы хранить все модули GRUB2, здесь располагаются только меню и несколько базовых команд. Основная часть функциональности GRUB2 заложена в модулях в {{Filename|/boot/grub}}, которые загружаются по надобности. В случае возникновения ошибки GRUB2 может не загрузится. Тогда появится командная строка.<br />
<br />
GRUB2 поддерживает много консолей. Если есть проблема чтения меню, но загрузчик может найти диски, вас перебросит в "нормальную" консоль.<br />
<br />
sh:grub><br />
<br />
Если проблема серьёзная, (напримерЮ GRUB не может найти требуемые файлы),вас перебросит в консоль "восстановления".<br />
<br />
grub rescue><br />
<br />
Консоль восстановления - это ограниченная версия обычной консоли, с меньшей функциональностью. Если вы переброшены в консоль восстановления, сначала попытаетесь загрузить модуль нормальной консоли, затем запустите её.<br />
<br />
grub rescue> set prefix=(hdX,Y)/boot/grub<br />
grub rescue> insmod (hdX,Y)/boot/grub/normal.mod<br />
rescue:grub> normal<br />
<br />
== Использование консоли восстановления ==<br />
<br />
Сначала прочтите [[#Использование командной строки]]. Если невозможно активировать нормальную консоль, возможным решением может стать загрузка с Живого CD (LiveCD), или с других дисков восстановления чтобы исправить настройки и переустановить GRUB. Тем не менее, загрузочные диски не всегда доступны или необходимы.<br />
<br />
Доступные команды в этой консоли включают "insmod", "ls", "set", и "unset". В следующем примере используется "set" и "insmod". "set" изменяет переменные, а "insmod" загружает модули для повышения функциональности.<br />
<br />
Перед началом, пользователь должен знать местоположение своей папки {{Filename|/boot}} (будь она отдельным разделом, или подпапкой в корневом разделе):<br />
<br />
grub rescue> set prefix=(hdX,Y)/boot/grub<br />
<br />
Где Х - это номер физического диска и Y - номер раздела.<br />
<br />
Чтобы расширить возможности консоли, загрузите модуль "linux":<br />
<br />
grub rescue> insmod (hdX,Y)/boot/grub/linux.mod<br />
<br />
{{Note|Если у вас отдельный boot раздел, исключите {{Filename|/boot}} из пути, (например, пишите {{Codeline|1=set prefix=(hdX,Y)/grub}} и {{Codeline|insmod (hdX,Y)/grub/linux.mod}}).}}<br />
<br />
Это описание "linux" и "initrd" команд, которые должны быть вам знакомы (смотри [[#Настройка]]).<br />
<br />
Например, загрузка Arch Linux:<br />
<br />
set root=(hd0,5)<br />
linux /boot/vmlinuz26 root=/dev/sda5<br />
initrd /boot/kernel26.img<br />
boot<br />
<br />
С отдельным разделом boot измените пути, как было описано выше. Например:<br />
<br />
set root=(hd0,5)<br />
linux /vmlinuz26 root=/dev/sda6<br />
initrd /kernel26.img<br />
boot<br />
<br />
После успешной загрузки Arch Linux, пользователь сможет подкорректировать {{Filename|grub.cfg}} и затем запустить:<br />
<br />
# grub-install /dev/sda<br />
<br />
для того, чтобы переустановить GRUB2 и полностью устранить проблему. Измените {{Filename|/dev/sda}}, если требуется. Смотрите [[#Установка загрузчика]] для детальной информации.<br />
<br />
== Примеры исправления проблем ==<br />
<br />
Добавьте сюда сами.<br />
<br />
=== Сообщение об ошибке msdos-style ===<br />
<br />
grub-setup: warn: This msdos-style partition label has no post-MBR gap; embedding won't be possible!<br />
grub-setup: warn: Embedding is not possible. GRUB can only be installed in this setup by using blocklists.<br />
However, blocklists are UNRELIABLE and its use is discouraged.<br />
grub-setup: error: If you really want blocklists, use --force.<br />
<br />
Эта ошибка может возникнуть, когда вы попытаетесь установить в виртуальную машину VMware. Читайте больше об этом [http://bbs.archlinux.org/viewtopic.php?pid=581760#p581760 здесь].<br />
<br />
Это также может случится, если первый раздел начинается сразу после MBR, без необходимого места в 60 блоков перед первым разделом.<br />
<br />
=== Grub-install вызывает зависание grub2 / legacy grub ===<br />
Отключите флоппи дисковод в биосе, даже если у вас его нет. Попробуйте использовать также --no-floppy и удалить fd0 строку из /boot/grub/device.map. Тем не менее, без отключения его в биосе, GRUB2 может всё равно не работать.<br />
<br />
=== Прочее ===<br />
Я не нашёл, как удалять grub1, и установил grub2 в MBR, но после этого он не стал по умолчанию загружаться. Загружался по умолчанию grub1. Лёгкий способ это исправить, это переименовать {{Filename|menu.lst.pacsave}} или подобное, в {{Filename|menu.lst}} (в /boot/grub/) для каждой строки меню, для которой вы хотите использовать grub2. В конце введите {{Codeline|"chainloader +1"}}. Это даст команду grub1 вернуть контроль к grub2.<br />
<br />
Возможное решение: Допустим, boot раздел {{Codeline|(hd0,1)}}, и корневой раздел {{Codeline|(hd0,3)}} (grub2 наименование). grub-setup ищет {{Filename|(hd0,3)/boot/grub/core.img}}. Он не может его найти просто потому, что он в {{Filename|(hd0,1)/grub/core.img}}. Я скопировал папку grub в мою корневую дерикторию, и всё заработало отлично:<br />
<br />
Например (от root:)<br />
# mount /boot<br />
# cp -a /boot/grub /<br />
# umount /boot<br />
# mv /grub /boot/<br />
# grub-install /dev/sda</div>
Whgirw