- Linux сервер на usb-флэшке
- Настройка USB-сервера Ubuntu на базе usbip
- Установка и запуск
- Настройка клиента
- Автозапуск
- Автозапуск сервера
- Автозапуск клиента Windows
- Возможные проблемы
- 1. usbip_common_mod.ko and usbip.ko must be loaded
- 2. /usr/sbin/usbipd: No such file or directory
- 3. usbip: error: failed to open /usr/share/hwdata//usb.ids
- 4. usbip err . recv op_common
- 5. (attach_device) cannot find device
- 6. udev_device_new_from_subsystem_sysname failed
- Ubuntu Documentation
- Outline
- Introduction
- Prerequisites
- Dummy headlines
- Notes about speed
- Notes about size
- Notes about bootability
- The flash hardware
- Creating a bootable Ubuntu USB flash drive from Windows
- Rufus
- balenaEtcher
- Pendrivelinux’s Universal USB Installer
- UNetbootin
- Win32 Disk Imager
- Creating a bootable Ubuntu USB flash drive from Ubuntu
- Install and run Startup Disk Creator alias usb-creator
- UNetbootin
- mkusb — dd image of iso file to USB device safely
- Creating a bootable Ubuntu USB flash drive from Mac OSX
- Test if running in UEFI mode
Linux сервер на usb-флэшке
В интернете много мануалов о том, как правильно поставить линукс на флэшку, чтобы она не померла (отключить журнал, noatime, ramfs etc). Но неужели нет готового образа, где все уже настроено?
Что у меня сейчас:
- Сервер HP MicroServer Gen8.
- В нем есть один жесткий диск (btrfs).
- На флэшке стоит Rockstor.
Что не нравится:
- После перезагрузки rockstor не всегда поднимается корректно (не монтирует разделы, не запускает некоторые docker-контейнеры).
- Демо-лицензия на ilo закончилась, а если система с флэшки ip не получила, то нет ssh — приходится помучиться, чтобы все оживить.
- Простую систему, которая получает ip по dhcp поднимает ssh.
- ФС флэшки вообще можно ro монтировать, когда она в сервер воткнута, чтобы не думать о ее скорой кончине. Если нужны какие-то доп-настройки — переткнул в комп и поправил.
- Система на фэлешке монтирует btrfs разделы с основного жесткого диска и запускает docker-контейнеры (можно будет bash-скриптами запилить).
Пока писал, подумал: а CoreOS мне не подойдет. (UPD: СoreOS больше 4 гигов весит, слишком жирный).
ramfs это не то что бы против износа флешки, это прежде всего ускорение, особенно если usb 2.0. Да и так обычные флешки не особо быстро читаются.
Но в целом это какая-то дичь грузить сервер с флешки, особенно если в нём есть винт. По идее с такими требованиями вам нужно искать среди дистров для маршрутизаторов.
Но в целом это какая-то дичь грузить сервер с флешки, особенно если в нём есть винт.
Суть в том, что после того, как сервер загрузился, читать с rootfs больше не нужно же. А если произошел какой-то сбой — перезалил образ на флэшку и все снова работает. А вот поставить систему заново на винт — это уже не очень удобно (сервер в труднодоступном месте, монитора клавиатуры у него нет, ilo без лицензии не дает виртуальной консоли).
Rockstor неплохо работает, но иногда глючит. Поэтому хочется простого линукса + баш-скриптов написать под мои простые нужды (transmission и plex).
Держать в сервере флешку с каким-нибудь Линуксом для восстановления/установки основной системы это одно, ЕМНИП iLO и без лицензии позволяет выбрать порядок загрузки.
Держать же ядро, dhcp клиента и sshd это другое, их же обновлять надо. Но в общем то дело ваше, я просто рассуждаю на тему, «почему нет готового образа, где всё такое уже настроено».
Хорошо, скажу немного по другому. Я не могу установить систему на сам сервер: нет монитора и клавиатуры, а remote console в ilo без лицензии не работает. Поэтому мне нужна система на флэшке, которая загрузится и даст ssh.
Судя по тому, что вы говорите, это вполне себе обычная задача, чтобы починить основную систему. Так что такие системы должны быть готовые.
чтобы она не померла (отключить журнал, noatime, ramfs etc)
А почему и на флешку btrfs не поставишь?
У меня на ней без всяких таких жертв давно живёт домашний компьютер, ну понятно что флешка должна быть очень хорошая.
Источник
Настройка USB-сервера Ubuntu на базе usbip
В инструкции описан процесс настройки бесплатного решения для редиректа USB устройства с сервера на любой другой компьютер сети. Это может пригодиться, например, для проброса USB токена на виртуальную машину или несетевого принтера. В рамках примера сервер будет на Linux Ubuntu, клиент — на Windows (проверено на 7, 10, Server 2008 и 2012).
Установка и запуск
В Ubuntu установка инструмента проброса USB выполняется следующей командой:
apt-get install linux-tools-`uname -r`
* в моем случае была выполнена установка linux-tools-4.4.0-128-generic, где 4.4.0-128-generic — версия ядра, используемого в Ubuntu.
Подгружаем модули драйверов USB:
Запускаем usbip в качестве демона:
Смотрим список подключенных USB устройств:
root@usb:/usr/src# usbip list -l
— busid 2-1.3 (8564:1000)
Transcend Information, Inc. : JetFlash (8564:1000)
— busid 2-1.4 (1c4f:0026)
SiGma Micro : Keyboard (1c4f:0026)
Теперь можно расшарить флешку:
usbip bind -b 2-1.3
Должны увидеть на подобие:
usbip: info: bind device on busid 2-1.3: complete
Настройка клиента
Выполним настройку на базе операционной системы Windows.
Скачиваем драйвер и утилиту для Windows. Распаковываем архив usbip.zip.
Открываем диспетчер устройств (команда devmgmt.msc или правой кнопкой по Этот компьютер в проводнике — Управление — Диспетчер устройств).
Кликаем по Действие — Установить старое устройство:
Выбираем ручную установку устройства — показать все устройства — Установка с диска и выбираем файл USBIPEnum.inf (находится в каталоге usbip, который мы распаковали ранее).
Будет обнаружено устройство USB/IP Enumerator — кликаем Далее, чтобы его установить. Мы должны его увидеть среди системных устройств.
Теперь открываем командную строку (cmd.exe) и переходим в распакованный каталог, например:
* где C:\Users\user\Downloads\usbip — полный путь до папки.
Смотрим список расшаренных USB устройств на сервере:
usbip -l 192.168.0.15
* где 192.168.0.15 — IP-адрес сервера USB.
Мы получим ответ, на подобие этого:
C:\Users\user\Downloads\usbip>usbip -l 192.168.0.15
— 192.168.0.15
2-1.3: unknown vendor : unknown product (8564:1000)
: /sys/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.3
: (Defined at Interface level) (00/00/00)
Теперь можно примонтировать устройство:
usbip.exe -a 192.168.0.15 2-1.3
* если увидим ошибку . cannot find device, переходим к решению.
Автозапуск
Данная инструкция предполагала разовый запуск как сервера, так и клиента. После перезапуска системы, работоспособность будет потеряна до повторного ввода команд. Попробуем настроить автоматический запуск сервера и клиента.
Автозапуск сервера
Добавляем модули в автозапуск:
usbip-core
usbip-host
vhci-hcd
Создаем юнит в systemd:
[Service]
ExecStart=/scripts/usbipd
Type=oneshot
RemainAfterExit=yes
Перечитываем конфигурацию systemd и разрешаем запуск созданного нами юнита:
systemctl enable usbipd
Создаем каталог хранения скрипта и сам скрипт:
usbipd -D
usbip bind -b $bindID
usbip attach —remote=localhost —busid=$bindID
sleep 2
usbip detach —port=00
Разрешаем запуск скрипта:
chmod +x /scripts/usbipd
systemctl start usbipd
systemctl status usbipd
Для окончательного тестирования можно перезагрузить сервер.
Автозапуск клиента Windows
Пишем небольшой батник:
cd C:\Users\user\Downloads\usbip
usbip.exe -a 192.168.0.15 2-1.3
* C:\Users\user\Downloads\usbip — путь, где хранится распакованная утилита; 192.168.0.15 — адрес сервера USB; 2-1.3 — идентификатор USB устройства на сервере.
Сохраняем скрипт с расширением bat или cmd. Запускаем планировщик заданий и добавляем новую задачу.
На вкладке Общие отмечаем Выполнять вне зависимости от регистрации пользователя и ставим галочку Выполнить с наивысшими правами:
В триггерах выбираем При запуске системы:
На вкладке Действия выбираем Запуск программы и прописываем путь до скрипта, который мы сохранили ранее:
На вкладке Параметры ставим галочку При сбое выполнения перезапускать через и снимаем галочку Останавливать задачу, выполняемую дольше:
Для проверки, можно запустить вручную задачу на исполнение или перезагрузить компьютер.
Возможные проблемы
1. usbip_common_mod.ko and usbip.ko must be loaded
Ошибка появляется при попытке выполнить usbipd -D.
Причина: был установлен пакет usbip вместо linux-tools- .
Решение: удаляем usbip:
apt-get remove usbip
Ставим нужный пакет:
apt-get install linux-tools-`uname -r`
2. /usr/sbin/usbipd: No such file or directory
Данная ошибка также появляется при попытке выполнить usbipd -D.
Причина: Нужный бинарник для запуска находится по другому пути — /usr/bin/usbipd.
Решение: создаем симлинк:
ln -s /usr/bin/usbipd /usr/sbin/usbipd
3. usbip: error: failed to open /usr/share/hwdata//usb.ids
Выскакивает при попытке посмотреть список устройств командой usbip list -l.
Причина: необходимый файл usb.ids находится в другой директории.
Решение: создаем каталог /usr/share/hwdata:
Создаем симлинк на существующий файл:
ln -s /usr/share/misc/usb.ids /usr/share/hwdata/usb.ids
4. usbip err . recv op_common
При попытке запустить утилиту в командной строке Windows получаем ошибки:
usbip err: usbip_network.c: 121 (usbip_recv_op_common) recv op_common, -1
usbip err: usbip.c: 216 (query_exported_devices) recv op_common
usbip err: usbip.c: 288 (show_exported_devices) query
Причина: ошибка в бинарном файле для Windows.
Решение: открыть exe-файл в HEX редакторе, например, HxD. И в адресах смещения 00000CBC и 00000E0A заменить 06 на 11:
5. (attach_device) cannot find device
При попытке монтирования устройства в Windows, выскакивает ошибка с похожим текстом:
usbip err: usbip_windows.c: 829 (attach_device) cannot find device
Причина: недоработка серверного ПО — при расшаривании USB не считывается количество дескрипторов.
Решение: примонтировать устройство на сервере с последующим отмонтированием:
usbip attach —remote=localhost —busid=2-1.3
* в моем случае устройство имеет идентификатор 2-1.3.
* смотрим номер порта, на котором висит наше примонтированное устройство.
usbip detach —port=00
6. udev_device_new_from_subsystem_sysname failed
При попытке монтирования устройства на клиенте получаем ошибку с текстом:
libusbip: error: udev_device_new_from_subsystem_sysname failed
usbip: error: open vhci_driver
usbip: error: query
Причина: не подключен модуль vhci-hcd.
Решение: разово выполняем команду:
и добавляем в файл /etc/modules строку vhci-hcd.
Источник
Ubuntu Documentation
Outline
The general procedure to install Ubuntu (or Ubuntu flavour, Kubuntu, Lubuntu, Xubuntu, . ) from a USB flash drive is:
Get the correct Ubuntu installation file, ‘the iso file’, via this link or Ubuntu flavour via this link. Download the iso file into your running computer (for example into the directory Downloads in the internal drive, not into the USB flash drive that you want to make into a USB boot drive).
Check with md5sum (or another checksum tool) that the download was good.
Try Ubuntu (Kubuntu, Lubuntu, Xubuntu, . ) before installing it.
See also: Installation/FromUSBStickQuick for beginners starting from Windows.
Introduction
Ubuntu can be installed from a USB flash drive. This may be necessary for most new portable computers without DVD drives and is handy for others because a USB flash drive is so convenient. Also, you can configure Ubuntu on the USB flash drive to save changes you make, unlike a read-only CD/DVD disk.
Booting from a USB flash drive created with usb-creator alias Startup Disk Creator and mkusb will behave just as if you had booted from the install CD. It will show the language selection and then the install menu, from which you can install Ubuntu onto the computer’s hard drive or launch the LiveCD environment. Other utilities, e.g. UNetbootin, may create slightly different boot drives or if on UEFI might not work at all with Debian iso files due to a bug
Note: This article uses the term «USB flash drive» alongside USB stick, USB drive, USB device, USB pendrive and thumb drive.
Prerequisites
To create a USB installation device, you will need:
a 4 GB USB flash device/drive/stick. If the iso file is smaller than 2 GB, it is possible to use a 2 GB USB device, at least with some of the methods. Files on this USB device will be erased, so backup the files you want to keep before making the device bootable. Some of the tools require that this USB device is properly formatted and mounted while other tools will overwrite whatever is on the target device. Please follow the instructions for each tool.
an Ubuntu flavour ISO file downloaded from an official web page, ubuntu.com/download or http://releases.ubuntu.com, stored in your running computer (for example in the directory Downloads in the internal drive, not in the USB flash drive that you want to make into a USB boot drive).
Check with md5sum (or another checksum tool) that the download was good. In Linux there is the tool ‘md5sum’. In Windows you can do it with Rufus: click on the circle with a tick mark (more about Rufus here.)
Dummy headlines
After a major remake of this help page the following headlines are kept here because they may be linked to from other web sites. Several other headlines further down in the page are also kept for this reason.
Notes about speed
Notes about size
Notes about bootability
The flash hardware
There is a detailed description at the sub-page /pre
Creating a bootable Ubuntu USB flash drive from Windows
There are various methods available for Windows to create a bootable Ubuntu USB flash drive.
NEVER try to use one of your hard disk drives or partitions in this process unless you really know what you are doing, as data will get erased.
Rufus
Rufus is the tool in Windows that is recommended officially by Ubuntu. A tutorial is available from here.
balenaEtcher
Pendrivelinux’s Universal USB Installer
UNetbootin
Win32 Disk Imager
There is a detailed description at /fromWindows including Rufus, balena Etcher, Universal USB Installer, Unetbootin and Win32 Disk Imager.
Creating a bootable Ubuntu USB flash drive from Ubuntu
Install and run Startup Disk Creator alias usb-creator
The Ubuntu Startup Disk Creator is dedicated to creating USB boot drives for Ubuntu and Ubuntu family flavours (Kubuntu, Lubuntu . Xubuntu).
You can find usb-creator-gtk by typing «Startup Disk Creator» (Ubuntu Desktop) or usb-creator-kde in K-Menu—>Applications—>System—>Startup Disk Creator (Kubuntu). If it is not there, then you can install it using the Ubuntu Software Center.
- Insert and mount the USB drive. Inserting the USB drive should auto-mount it.
- Start the Startup Disk Creator
- In the top pane of the Startup Disk Creator, pick the .iso file that you downloaded.
- If the .iso file isn’t listed, click «Other» to locate and select the .iso file that you downloaded.
- In the bottom pane of the Startup Disk Creator, pick the target device, the USB flash drive. If more than one choice, please check carefully, until you are sure that you will be writing to the correct device.
- After checking that you are pointing to the correct target device, the USB flash drive, you can start the action.
You must enter a password because this is a risky operation. Use the password of the current user ID (the same as for login and running tasks with 'sudo'. Password is not required when installing from a ‘live’ system (booted from a DVD disk or another USB flash drive).
The Startup Disk Creator clones the iso file, which means that you need neither erase nor format the target drive. It will be completely overwritten anyway by the cloning process. The Startup Disk Creator looks like this in Ubuntu 18.04 LTS:
Notes
NEVER try to use one of your hard disk drives or SSDs or partitions in this process unless you really know what you are doing, as data will get erased.
There are bugs that affect the Ubuntu Startup Disk Creator, when you run it in old Ubuntu versions in BIOS mode and try to create USB boot drives with other versions. In the Ubuntu Startup Disk Creator version 0.3.2 in Ubuntu 16.04 LTS, these bugs are no longer a problem, so you can install any version of the Ubuntu flavours from 16.04 LTS and newer versions.
UNetbootin
Download UNetbootin
mkusb — dd image of iso file to USB device safely
If you want to clone from a general image file to a drive, you can use mkusb. It lets you clone to any drive that is not busy, also an internal drive, and there are very obvious warnings to prevent mistakes.
- run in Debian and many linux distros that are similar to Ubuntu and Debian,
- clone from iso files of most Linux distros to create USB boot drives,
- create persistent live drives of the Ubuntu family and Debian, using all available drive space for persistence and/or data storage,
- restore a USB boot drive to a standard storage device.
There is a detailed description at /fromUbuntu including the Startup Disk Creator, UNetbootin and mkusb.
Creating a bootable Ubuntu USB flash drive from Mac OSX
There is a good wiki page about booting with UEFI, and a good tutorial thread, UEFI Installing — Tips.
Test if running in UEFI mode
You may want to test if your Ubuntu flavour is running in [U]EFI mode. An installed system and a live system too is using the directory /sys/firmware/efi, so you can run the following command line,
The following command line is more robust and also easier to understand, so you may prefer it (if you copy & paste and are not bothered by typing a long command line),
Источник