Openwrt установка на hdd
This is a very brief tutorial on getting OpenWRT installed on a regular computer, it assumes you know your way around Linux. If you find this and need additional details, please like, subscribe, and comm. oh wait this isn't youtube, just comment.
This is how I got OpenWRT going on a Mini ITX Intel DH67CF with an Intel G870 CPU with 4GB of RAM.
What You'll Need
- 2 USB Sticks
- Linux Live ISO
- Latest OpenWRT combined-ext4 Image
- As of this writing this version is 18.6.2
Use dd and create your live Linux ISO.
Format the second USB stick ext4, then gunzip the combined-ext4 image, then copy it to the USB stick.
Boot off your live Linux USB.
Insert your second USB once linux fully loads.
Use dd to write your combined-ext4 image to your hard drive.
Once dd completes, open gparted and resize the second partition to around 4GB.
Reboot removing the USB sticks.
Grub should automatically boot to OpenWRT.
You may have to hit enter a couple of times if the boot seems to hang, it'll drop you to the command prompt and complain that there's no password.
Edit your /etc/config/network file with vi .
You'll want to modify your lan interface giving it a static IP within your network.
Here's mine for example:
Then do service network reload and you should be able to ping your gateway and outside the network.
You should now be able to get into the gui from any computer in the same subnet.
opkg install vim-full nano usbutils pciutils
opkg install bash
Edit /etc/passwd and change your shell to /bin/bash .
I like to have a larger /root partition and a swap .
opkg install fdisk kmod-fs-ext4 e2fsprogs swap-utils block-mount
Use fdisk -l to list your partitions.
Should show something like this:
From here use fdisk /dev/sda . Create a new primary partition about the size of your RAM for your swap. Then create a secondary primary partition for your /root partition. Write the changes and do fdisk -l again. Should display something like this:
Format your sda4 as ext4 with mkfs.ext4 /dev/sda4 , then make your sda3 swap space with mkswap /dev/sda3 then swapon /dev/sda3 .
View your memory and swap space with free -k .
Mount your sda4 to /root , mount /dev/sda4 /root .
Enable fstab with:
Create your fstab with
Edit your fstab with vi , make it look like this your UUIDs will not be all zeros.
Now reboot and your mount and swap should be good to go.
opkg install adblock luci-app-adblock
Reload luci and you should find Adblock under Services.
Generate your ssh keys.
Add your ssh key to github.
Git will not work correctly with ssh from the server, this is the workaround.
Edit your .profile and add:
Then source your .profile .
Now you should be able to connect to github.
Дополнительные сведения
Через Web интерфейс
1. LuCI → System → Software → Configuration
это должно выглядеть примерно так:
2. LuCI → System → Software → Actions → Update lists производит первоначальное обновление списка пакетов на extroot
———–Перевод и обновление статьи продолжается! ———— далее идет старая версия!
Automount the partition
Automount ensures that the external disk partition is automatically made available for usage when booting the OpenWrt device
to see something like this
Note the “target” entry. This is the file path, where your attached USB storage drive can be accessed from now on. E.g. you can now list files from your external disk:
The result will be:
Troubleshooting
Add option force_space in /etc/opkg.conf to allow installation of packets bigger than your /rom partitions free space:
Do not use vfat (FAT/FAT32); it does not work. If you have a FAT preformatted USB drive, you cannot use it for extroot without reformatting. Use e.g. ext4 (install e2fsprogs, then format your FAT formatted USB drive using mkfs.ext4 /dev/sda1 as per the example, also see storage).
On Barrier Breaker, block-mount will create a file /etc/.extroot-uuid on extroot filled with uuid of mtd partition rootfs . At boot time when trying to do extroot, block-mount would try to check the actual uuid with the content of .extroot-uuid . If they did not match, extroot would fail. So if you want to continue use extroot after flashing a new firmwre, /etc/.extroot-uuid needs to be deleted first.
If the partition containing your extroot isn't mounted during boot, but you can mount it without problems from a shell, you should try to increase config 'global' / option delay_root . On my system I had to set it to 15 to get extroot working. Another hint to this being the culprit is having a working swap or other partitions mounted after booting, but not your extroot.
PavelSosin-320 commented Mar 11, 2020
What about MS WSL 2.0 ?
PavelSosin-320 commented Mar 13, 2020
Thanks, but I'm searching for a solution for the current situation rather than hypothetic.
I have Windows 10 with WSL 2.0, i.e. able to install and run any ISO packed Linux distro built according to Microsoft guidelines. I don't have and don't use any unmanaged storage device, only my laptop disk, and my phone storage.
I have a single WiFi network based on Technicolor router with a capacity between 50 to 400 Mghrz depends on device type and distance from the router. My router provides both DLNA and SMB if I look at its configuration Web GUI. My phones have both Android standard DLNA players and Android standard SMB (X-File) clients. Both clients discover, connect and communicate with services on my router. My Samsung Smart TV running Samsung Tizen (unknown to me Unix distro ) discovers DLNA on my router and communicates with it.
The goal: add NAS storage to my WiFi LAN with cost less than 40$ per Tb using external disk attached to my router and its SMB service.
The test: ask my ISP which supplied to me Technicolor router with proprietary software based on OpenWRT and install it as WSL distro. Install the recent OpenWRT stable distro as WSL distro. Test all my clients with DLNA and SMB servers without adding any redundant hardware.
I hope, it will be a good argument to ask from my ISP to upgrade the firmware on my router urgently as equipment repair instead of waiting several months until the next proprietary version possibly sold/rent as a new model.3. Настройка extroot
Посмотрите, какие есть у вас разделы:
Здесь мы видим mtdblock устройства (разделы во внутренней флеш памяти), и раздел /dev/sda1 это ваш USB флеш диск.
Отформатируйте раздел /dev/sda1 в ext4 если это необходимо:
Сейчас мы от конфигурируем /dev/sda1 как новый overlay через подсистему fstab uci:
Если у вас есть раздел подкачки, он также будет распознан и добавлен автоматически.
Installing OpenWrt in an internal drive
If you want to write OpenWrt in Sata or IDE drives or CF Cards or SD cards, you can just remove them from the device and flash the image raw from your PC. Also sometimes eMMC is removable or can be put in “usb write mode” in some devices.
But if you cannot remove the storage from the device (or do not have an adapter to connect them to the PC), you can write OpenWrt on a USB drive (or another removable storage device), then you can then insert it in a USB port or slot. When booting select the drive where you installed OpenWrt.
Then you need to identify how is the internal storage device called with lsblk or dmesg:
Be aware that you will also see the USB drive or the storage device you have temporarily installed OpenWrt on.
This for example is the output of a 4GB USB drive with 2 partitions on it that was assigned the name /dev/sda:
After you have identified the onboard storage you want to install OpenWrt in, you can follow the Linux install instructions above. Then power off the system, unplug the removable storage device you used to install OpenWrt, and power on again. Now it should boot from the internal storage.
Create a partition on the USB disk
if the previous chapter did not list any existing partitions (like “/dev/sda1”, “/dev/sda2”, “/dev/sdb1”…), you have to create a partition first for further storage usage.
This triggers an interactive dialogue: Use the suggested defaults for the partition creation (number, starting sector, size, Hex code)
and then confirm your choice with
Refer to the gdisk help text (write “?”) in case you need additional help. Stick to a single partition, to stay aligned to the following HowTo.
Сохранение списков программных пакетов при загрузке
Сохранение статуса установленных пакетов opkg в /usr/lib/opkg/lists хранящемся в extroot, а не в RAM, экономит некоторую оперативную память и сохраняет списки пакетов доступными после перезагрузки.
Install and verify USB drivers
This step ensures that required USB storage drivers are properly installed.
The typical OpenWrt package already has core USB device drivers installed (if your device has USB ports at all), but might not yet have an USB storage device driver installed. Install this storage driver first (if it is already installed, the following command will just say “is already installed”:
“Bus…”-Lines represent the host chip. Here, the “Driver” will be xhci for USB3.0, ehci for USB2.0 and uhci or ohci for USB1.1.
Lines with “Class=Mass Storage” represent connected USB devices. Here the “Driver” is either usb-storage for storage of type Bulk only Transport or usb-storage-uas for storage of type USB_Attached_SCSI
In step 5, verify that the output prints no error and has at least one output line for root_hub and Mass Storage and that each Driver= lists a driver name. If not, then refer to the Installing USB Drivers for more suggestions on drivers.
Через Web интерфейс
LuCI → System → Mount Points должен быть показан раздел на внешнем USB устройстве подмонтированный как overlay .
Verify that the OS recognizes the attached disk and partitions
This optional verification step can be used, to check that the OS can properly detect a connected external drive.
This should print at least a connected disk like “/dev/sda” or “/dev/sdb”. If no disk at all is listed, recheck USB driver installation and reboot your OpenWrt device once.
for exFAT you also need libblkid
and you should see output like this, if your disk already has partitions:
If a disk already has existing partitions, they get listed as /dev/sda1, /dev/sda2 ,/dev/sda3 and so on.
If we had connected more than one storage device we would have also a /dev/sdb1 (first partition of second device), /dev/sdc1 (first partition of third device) and so on.Resizing partitions
Be sure to resize the image before resizing partitions when installing in a VM.
Use fdisk to create a new partition 2, choose/type the starting sector address you wrote down earlier (as by default it will try to place it somewhere else), and leave the default end sector address (this will mean the partition will now use all available space).
Write the partition table changes to disk. It may complain about partition signatures already present, write n to NOT remove the partition signature to proceed.
An example fdisk operation on a 8GB flash drive:
Be sure to update the GPT partition UUID in the GRUB configuration when using efi.img.gz:
Building your own image with larger partition size
Anyone can compile OpenWrt from source, but it's a complex procedure with many options which require some experience, specially for using it on a production router.
Different from compiling, we can build our own custom image using the Image Builder. This doesn't compile the whole software, instead it downloads required packages from the same repository used by OpenWrt to install them. Image Builder builds the same image files used for installing and upgrading OpenWrt.
Due to that it's much simpler than compiling and offers great advantages, like adding directly to the image all packages we need, removing those we don't need, and also adding to it our config files. Having packages on the image, we don't need to reinstall all of them after an upgrade. And having our config files directly on the image, we don't need to reconfigure everything or copy all files from backup, which is specially difficult when default network configs don't work with our router's interfaces or it doesn't start with correct IP address. In many cases, OpenWrt will be back fully working on first boot after upgrading.
Another advantage for building a custom image is when the default rootfs partition size is too small to store all packages and we need to resize it. Note that, when following above procedures of installing then resizing partition and upgrading by writing partition image or extracting rootfs.tar.gz, we don't need to build the image with the final size of the partition. Doing so would result in the too large image file and would require enough RAM to store the whole file during building. It's recommended to use on the image just enough size to store all packages plus a small amount of free space.
Follow the Image Builder tutorial to setup the building environment using the x86/64 target. Once the building environment is setup, we use the make image command to build an image, which results on a set of files with the types of images described on this page. They are saved on bin/targets/x86/64 inside the building folder.
Because x86 hardware doesn't have profiles, we don't need to use the PROFILE parameter. With PACKAGES parameter we set all packages we want to add to or remove from default list. The command make info lists default packages list. FILES parameter is used to add custom config and script files to be added to the image, it points to a folder which represents root folder when OpenWrt is running.
For changing default partition sizes use parameters CONFIG_TARGET_KERNEL_PARTSIZE and CONFIG_TARGET_ROOTFS_PARTSIZE . We can either edit .config file on building folder or pass them directly to make image . Example CONFIG_TARGET_KERNEL_PARTSIZE=128 CONFIG_TARGET_ROOTFS_PARTSIZE=512 .
Для полного понимания процедур крайне желательно ознакомится с темами приведенными ниже:
This article relies on the following:
Так же необходимо отметить что механизм конфигурирования extroot существенно зависит от версии OpwnWrt и в меньшей степени зависит от типа вашего устройства. Данная русскоязычная версия документации будет отталкиваться от версии OpwnWrt 18.06. В качестве аппаратной платформы будет использоваться роутер TP-LINK TL-WDR4300/3600.
У многих роутеров существенно ограничено размер дискового пространства для хранения файлов и данных (встроенная flash-память). Но, в тоже время, роутеры могут быть оборудованы портами USB или SATA, что позволяет подключить к ним внешние устройства хранения, такие, как диски USB-flash и USB-HDD. В более экзотических случаях могут быть подключены даже mini PCI-E или сетевые диски. Подключение подобных устройств позволяет расширить “дисковую” память роутера, в том числе и его корневую файловую систему, rootfs для хранения как дополнительного программного обеспечения, так и дополнительных настроек. В большинстве поддерживаемых устройств OpenWrt разбивает внутреннее хранилище на разделы rootfs и rootfs_data , которые объединяются в одну перезаписываемую файловую систему наложения overlay .
Partition(раздел) Mount point(точка монтирования) Compression(сжатие) Writable(записываемый) rootfs /rom Yes(Да) No(Нет) rootfs_data /overlay No(Нет) Yes(Да) overlay / Unmodified files(Не модифицированные файлы) Yes(Да) Таким образом, OpenWrt помещается даже в крошечные объемы внутренней памяти (всего 4 МБ), но все же позволяет записывать настройки и устанавливать некоторые пакеты в доступный для записи раздел без изменения всех используемых программ Linux.
Extroot работает, устанавливая другой overlay раздел на внешнем устройстве хранения, и во время загрузки этот новый overlay раздел будет смонтирован поверх overlay раздела внутреннего хранилища. Этот подход позволяет легко откатиться в случае удаления внешнего устройства хранения, поскольку ваше устройство по-прежнему будет иметь свой собственный overlay раздел и, следовательно, будет загружать всю конфигурацию оттуда.
Это означает, что он будет вести себя точно так же, как и перед настройкой extroot.Через командную строку
Раздел на внешнем USB устройстве должен быть подмонтирован как overlay Свободное пространство в корневом разделе / должно быть равно пространству на /overlay .
PavelSosin-320 commented Mar 11, 2020
What about MS WSL 2.0 ?
Download disk images
Go here, choose the release version, then click on target and then on x86. You will see different targets.
64 is for modern PC hardware (anything from around 2007 onward), it is built for 64-bit capable computers and has support for modern CPU features. Choose this unless you have good reasons not to.
Generic is for 32-bit-only hardware (either old hardware or some Atom processors), should be i686 Linux architecture, will work on Pentium 4 and later. Use this only if your hardware can't run the 64-bit version.
Legacy is for very old PC hardware, Pentium MMX, what is called i586 in Linux architecture support. It will miss a lot of features you want/need on modern hardware like multi-core support and support for more than 4GB of RAM, but will actually run on ancient hardware while other versions will not.
Geode is a custom Legacy target customized for Geode SoCs, which are still in use in many (aging) networking devices, like the older Alix boards from PCEngines.
Now you will see different files offered, the following two are disk images you can download and use:
squashfs-combined.img.gz This disk image uses the traditional OpenWrt layout, a squashfs read-only root filesystem and a read-write partition where settings and packages you install are stored. Due to how this image is assembled, you will have only 230-ish MB of space to store additional packages and configuration, and extroot does not work.
ext4-combined.img.gz This disk image uses a single read-write ext4 partition with no read-only squashfs root filesystem, which allows to enlarge the partition. Features like Failsafe Mode or Factory Reset won't be available as they need a read-only squashfs partition to function. It has both boot and root partitions and MBR area with updated GRUB2.
ext4-rootfs.img.gz This is the equivalent partition image without boot partition, to be installed without overriding MBR.
rootfs.tar.gz This contains all files from root partition. it can be extracted on root partition without the need of rewriting the partition. It's highly recommended to remove all script and compiled files before extracting, to avoid conflicts.
Adding extra partitions
When OpenWrt is installed on a x86 machine using generic-ext4-combined.img.gz, the drive's partition table is overwritten, which means that any existing partition is deleted. Any remaining space will be unallocated and the drive will have a normal MBR partition table.
Any partition management tool that supports MBR and ext4 can be used to create extra partitions on the drive, in example fdisk, GParted.
But attention must be taken for future upgrades. If extra partitions are added, you cannot use -combined.img.gz images anymore, because writing this type of image will override the drive's partition table and delete any existing extra partition, and also revert boot and rootfs partitions back to default size.
pjobson commented Mar 12, 2020
@PavelSosin-320 I stopped using Windows before that was a thing, I was still using CYGWIN back then. If WSL has dd then you can probably write the OpenWRT image to the hard drive. It kind of seems like a long way around to setup Windows on a USB stick, boot off of that and do the work in WSL. I use a Linux boot stick, because it is quick and easy.
I write up little directions like these for myself so I don't have to figure them out again in the future. There are probably many ways of doing this install, this is just one of them.
Just be careful with dd , you can really screw up your operating system and lose data if you are not careful.
Upgrading
On most embedded devices, upgrading OpenWrt is much simpler than the first installation and consists of simply executing sysupgrade. On x86 machines, on the other hand, upgrading is more complex than the first installation.
One of the advantages of x86 is the easiness to backup and restore drives, using any normal backup tool that supports MBR and ext4. Always make a proper backup of the whole drive and test its restore before any upgrade procedure. It's also recommended to restore the backup on a virtual machine and execute the upgrade on it prior to upgrading the real router, to learn and experiment the procedures without risking the real thing.
On all procedures on this section, we must either connect the drive on a secondary PC running Linux, or boot the router with a Linux Live CD/USB.
If you had used a ext4-combined.img.gz type of image to install, there are 4 options for upgrading:
Write a new ext4-combined.img.gz image: this is the simplest option and is identical to first installation: all data, configs, packages and extra partitions will be wiped and you'll have a brand new OpenWrt system with default packages and configs. Then you can reinstall all packages and copy config files back and create extra partitions.
Use sysupgrade: this is default upgrading procedure, but the least recommended option for x86 machines. Proceed to Sysupgrade for details.
Extracting boot partition image from ext4-combined.img.gz and writing it and ext4-rootfs.img.gz, leaving MBR partition table intact.
Extracting boot partition image from ext4-combined.img.gz and writing it, then uncompressing rootfs.tar.gz to existing rootfs partition.
The 2 last options require more steps to execute, but have the advantage of leaving MBR partition intact, therefore keeping boot and rootfs partitions sizes (in case of having resized them) and any extra partitions. At this time they are the most recommended methods of upgrading. The only exception is when new OpenWrt image brings a newer version of GRUB2. Part of GRUB2 is stored close to MBR and outside of partitions area, so we need to write a full ext4-combined.img.gz to update it.
2. Настройка rootfs_data
Подключитесь через ssh к устройству.
Сконфигурируйте /etc/config/fstab для монтирования rootfs_data в другой каталог на тот случай, если вам понадобится получить доступ к исходному оверлею root для изменения настроек extroot:
Или вы можете определить раздел rootfs_data вручную:
Каталог /rwm будет содержать исходный корневой overlay, который используется в качестве основного корневого overlay до тех пор, пока extroot не будет поднят и запущен. Позже вы можете отредактировать /rwm/upper/etc/config/fstab , чтобы изменить вашу конфигурацию extroot (или временно отключить ее), если вам это когда-либо понадобится.
Linux
Extract the image file from the archive. Most sane distros will let you do so by right click and then select “extract”, or you will have to open up your graphical archive manager and do it from there. Then write the image file you extracted to the drive you want to install OpenWrt in. Many distros include a disk image writer application such as GNOME Disks. Identify the disk you want to write the image on, e.g. sda, sdb, sdc, etc., and write the image with dd tool where using the previously identified drive name. Note you have to gain administrative privileges with sudo and write to the drive (sda, sdb), not to a partition (sda1, sdb3).
Installation
The installation consists of writing a raw disk image on the drive which will boot OpenWrt system. It may be a USB flash drive, USB SDcard reader with SDcard or in a SATA hard drive or SSD (recommended). You can do it either on a secondary PC, or booting the router machine with a Live CD/USB.
WARNING: writing raw image files DELETES the content of the drive you write them on, be sure that you are not deleting anything important, and that you have selected the right drive.
pjobson commented Mar 13, 2020
I don't think you can do OpenWRT as a WSL distro, that being said, my knowledge of WSL is infinitesimal.
Per the ISP thing, I honestly don't think you'll have much luck fighting with them on it, they have their own firmware, so they can manage everything on the router themselves. There is a possibility that they let you run your own router, it really depends on the ISP.
I use Plex for all of my media storage and streaming, that's what the gist above is geared towards, but it may give you some ideas as to how to structure your network to meet your needs.
Once I used VirtualBox but the company which I left recently prohibited to use it due to good security reasons. Integration VirtualBox with Windows network was horrible! Today Microsoft and Linux are close friends and Microsoft geared to incorporate Linux into Microsoft products everywhere. The reason is Microsoft's income from its cloud - Azure. Docker and Cloud world mainly runs on Unix/Linux. WSL is well supported by Microsoft community, based on the proven hardware architecture, used in some Cloud-related products like DockerDesktop for Windows (works fine for me!), i.e. it is a mature platform. - If you want you can Google "WSL 2.0" and find many projects based on WSL 2.0 platform, even Linux Desktops on WSL. wsl-2-where-is-it-and-where-is-it-going *No NAT configuration is needed* in the recent releases because MS reuses container networking ideas. *WSL does support SMB.* Microsoft is with SMB forever - this is one of cloud storage protocols used in Kubernetes running in Azure. *The big question is the dialect*. Unfortunately, they switch and retire versions in the galop. Some projects are developing under the assumption that MS will enable WSL in all Windows distro including Home edition and finally remove "Hyper-V hardware barrier" Regarding my fight with ISP - I hope for good. There are several ISP and all in a very tough situation. I'm satisfied with my Technicolor router because I have very fast WiFi (last measurement up to 600 Mhz wifi speed, ready to connect to FTTH fiber infra, etc. On the other hand, 600 Mhz *speed means that wireless connected NAS can work almost like a local external drive*!
OpenWrt can run in normal PC, VM, or server hardware, and take advantage of the much more powerful hardware the x86 (Intel/AMD) architecture can offer.
Partition layout
The x86 image is using the following partition layout (as seen from inside of the device):
/dev/sda2 is a 256MB partition containing the squashfs root filesystem and a read-write f2fs filesystem OR the ext4 root filesystem (depending on what image you have chosen).
Any additional space in the device is unallocated.
4. Перенос данных
Теперь мы перенесем содержимое текущего оверлея на наш новый оверлей на внешнем диске:
Install file system drivers and create a file system in the partition
To use a partition for data storage, it needs to be formatted with a file system.
The following is the most simplest (and recommended) default configuration for OpenWrt file system usage.
For advanced users, there are further optional file system options available.WARNING: This step deletes existing data in that partition. Ensure you have a backup of important files before starting!
For USB hard disks, install EXT4 file system and use EXT4 to format the partition (in this example '/dev/sda1'):
For SSD drives and thumb drives, install F2FS file system and use F2FS to format the partition (in this example '/dev/sda1'):
Upgrading rootfs partition
As said above, there are 2 options for upgrading rootfs partition, when we are using the ext4 file system and not squashfs: writing ext4-rootfs.img.gz image or uncompressing rootfs.tar.gz into existing partition.
Writing ext4-rootfs.img.gz will delete any file on the partition. When using dd , it will preserve partition's actual size, it won't revert its size to image's.
For uncompressing rootfs.tar.gz, we must mount rootfs partition, delete all files from it, then uncompress updated files.
It may be tempting to not delete config files, but the risk isn't worth it, because some file may conflict and not be properly upgraded. It's safer to backup config files (as we should also backup whole drive before upgrading) and copy them back after upgrading. I suggest going further and having a Subversion repository on another computer where all config files are saved and their changes are tracked, and use rsync to sync between the repository working copy and production files on the router.
Extracting boot partition image
The boot partition contains part of GRUB2 software, Linux kernel and grub.cfg with boot options. rootfs partition contains OpenWrt files, packages and configs.
At the moment, it's not built a separated image file with boot partition, as it's available for rootfs. To be able to upgrade boot partition without overriding the whole drive, we must extract it from ext4-combined.img.gz, this requires a spare empty drive or a virtual machine.
Инструкции
1.2. Устройства более чем с 8 МБ флеш памяти
На этих устройствах должно быть достаточно места для установки необходимых нам пакетов. Удалите все пакеты, которые вы установили, чтобы добавить функциональность, так как они теперь только используют место во встроенной флеш памяти. После того, как вы сделаете extroot, у вас будет все необходимое пространство.
Из интерфейса командной строки напишите (в одну строку):
Это установит пакеты, необходимые для раздела с файловой системой ext4.
Пользователи, подверженные риску, могут захотеть создать собственный образ (как описано в предыдущем разделе), содержащий эти инструменты и особенно модули ядра, которые соответствуют ядру прошивки, чтобы они были доступны в отказоустойчивом режиме(failsafe mode).
Проверка
Extroot на карту памяти в слоте USB-модема
В статье Использование 3g/UMTS USB модема для WAN соединений рекомендуют добавить в образ прошивки утилиту usb-modeswitch .
Использование данной утилиты имеет особенности: если /overlay расположить на карте памяти, находящейся в слоте USB-модема, то даже при совершенно правильных настройках внешнего overlay , работоспособных при любом другом размещении оверлея, в данном случае будут наблюдаться неполадки файловой системы, возникающие на завершающей стадии загрузки ОС. Неполадки вызваны тем, что утилита usb-modeswitch , отключая CDROM и подключая модем, попутно на некоторое время отключает и считыватель карт памяти, нарушая работу файловой системы.
Избежать этого можно заранее настроив USB-модем так, чтобы usb-modeswitch не потребовался вообще: устройство должно сразу представляться ОС как модем или сетевой адаптер со считывателем карт памяти включенными по-умолчанию.Подключите USB-модем к компьютеру и с помощью терминала отправьте на модем соответствующие AT-команды.
Проверяем исходную конфигурацию USB-модема:Расшифровать данный ответ модема можно с помощью следующей команды:
В данном примере у нас USB-модем, в котором в первой конфигурации (слева от символа ; ) включены CDROM и считыватель карт, во второй конфигурации (справа от символа ; ) включен модем, управляющий и диагностический интерфейсы, и считыватель карт памяти. Именно между двумя этими конфигурациями утилита usb-modeswitch переключает USB-модем на роутере.
Ваша цель - оставить только одну конфигурацию, в которой по-умолчанию включен модем (см. 1 выше) или сетевой адаптер (см. 16 выше), присутствует считыватель карт памяти (см. A2 выше), но при этом выключен CDROM.
ВНИМАНИЕ: Нельзя отключать интерфейс PCUI (см. 2 выше) - вы потеряете возможность управлять USB-модемом!Некоторые USB-модемы принимают параметр 'выключить всё' (см. FF ниже).
Перечислите все необходимые вам по-умолчанию функции модема в списке справа от символа ; по их кодам из ответа модема вверху:Данная последовательность команд выключила CDROM и оставила единственную конфигурацию, в которой по-умолчанию присутствуют модем, интерфейсы и считыватель карт памяти - без необходимости пользоваться утилитой usb-modeswitch на роутере. Обратите внимание на символ ; - слева от него пусто.
Tip: The Quick Start for installing a USB drive solves the very common case of installing a single USB drive onto your OpenWrt device. People do this to use Samba or other programs that need to store data on an external drive. The remainder of this page provides much more information about USB devices and drivers.
Many supported devices have ports to connect storage devices, most common are USB, or Sata.
This article will describe how to configure your device to use such storage devices for storage or for sharing. If you want to expand your firmware's space (to install more packages) please read the article about Extroot configuration.To configure external disk space, follow the procedures of this page:
Hardware support
All images support basic video output (screen text terminal), so you can connect a screen to the device's video ports and see it boot up.
Some images support keyboard input which can be used to configure OpenWrt.
To communicate through a PC serial port you will need a “null-modem” aka “crossed” serial cable to connect the device's serial port to your PC's serial port.
To be able to connect to your device, the image must support the Ethernet hardware.
The Geode images support Geode hardware so as long as you have a Geode-based board you should be fine.
NVMe SSD support is available since OpenWrt 21.02.
Resizing F2FS overlay
Resize F2FS overlay for squashfs-combined.img.gz:
Windows / macOS
If you are using a Windows / macOS, you will need a program to extract the raw disk image from the compressed archive you downloaded. Then you will need to open the raw image file with a program that can write it on the drive you want to install OpenWrt on.
A good free and opensource archiver program you can use is 7zip, or Keka.
A good free and opensource raw disk image writer program you can use is Win32 Disk Imager, or Etcher.
Optional: Idle spindown timeout on disks for NAS usage
Optional step for hard disks.
If you want to use OpenWrt as a permanent NAS, you might want to spin down the harddisk motor during times of inactivity. Either because you want to have it quiet in your room during nighttime or to increase lifetime of the harddisk (e.g. when using a home-edition harddisk (instead of a 24×7-datacenter edition).
There are different options, to automatically spin down the motor of the attached harddisk after a certain time of inactivity. Both require installing optional packages on OpenWrt.
1. Option: hdparm
This tool permanently saves a spindown timer on the harddisk itself, using standardized SATA disk commands (the harddisk will then remember that spindown-timer value, even if turned off, even after a restart and even if attached to a different device). Its actually just a command line interface for a built-in harddisk function. So no OpenWrt service has to be run in the background for this and 'hdparm' could even be uninstalled after setting this parameter. Unfortunately many older USB2.0-PATA/SATA-adapters do not support the required SATA command, although even decade-old harddisks do support it. But fortunately most USB3.0-SATA-cases seem to support the required SATA command. To install the packageE.g. to set a reasonable idle timeout of 20 minutes on the harddisk, use:
if the command failed with an error message, your USB-SATA-casing sadly does not support it and you won't be able to use 'hdparm' for disk spindown as long as you use this USB-casing.
Of course you can always change the timeout or disable auto-spindown again later on. Depending on your harddisk, the value may be active until the next reset or permanently stored on the harddisk. The harddisk firmware itself manages the spindown timeout, not a OpenWrt service. For persistent changes use /etc/rc.local file, like:
2. Option: hd-idle (With LuCi integration)
This is a service than runs in the background of the OpenWrt device and maintains its own idletimeout counter. Once the defined timeout counter reaches 0, it will send a “live” spindow SATA command to the disk. Unlike the permanent spindown command from hdparm, a lot more USB2.0-SATA cases seem to support this “spindown-now” SATA command.To install the package that even has LuCi frontend integration:
To configure it, use the “Services” menu of the LuCi web GUI of your device.
To install the CLI package (without LuCi):To configure it, you can edit the /etc/config/hd-idle file and then autostart and run the hd-idle service service hd-idle enable && service hd-idle start .
Name Type Default Description disk string sda Replace sda with your device's identifier enabled boolean 0 Enable hd-idle operation idle_time_unit string minutes The unit of time used in the idle_time_interval option idle_time_interval integer 10 How much idle time before spindown Notice that you have to enable it since it isn't by default.
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 InternationalРано или поздно, приходишь к мысли, что внутренней памяти TL-MR3020 недостаточно для экспериментов в области домашней автоматизации, и естественно — возникает желание ее расширить. К счастью, MR3020 обладает USB-портом, и работает под OpenWRT. А это, хоть и урезанный, но все-таки — Linux!
Разобьем сменный накопитель на нужное количество разделов. Я взял миниатюрную флешку Cruzer Fit на 32 Gb, которую предварительно отформатировал следующим образом:
Теперь маленькое пояснение касательно разделов. Если с разделом подкачки и разделом для файлов, в принципе — все понятно, то о системном (/overlay) нужно сказать несколько слов.
Overlay — внутренняя область памяти, которую OpenWRT использует для изменяемых данных (таких как конфигурационные файлы или пакеты программ). Остальные файлы в самой прошивке находятся в read-only файловой системе. Поэтому, для расширения памяти, необходимо переместить Overlay с памяти роутера на внешний носитель.
Обновим список пакетов и произведем установку нужных модулей для поддержки USB-накопителей и файловой системы ext4:
Подключаем USB-накопитель и смотрим как на это отреагировала система (она должна его обнаружить). В моем случае, команда dmesg показала следующее:
Если система увидела накопитель и все его разделы — отредактируем файл /etc/config/fstab с указанием точек монтирования.
Вместо имен разделов «sdxx» в файле fstab — используйте идентификаторы «uuid», так как они уникальны. Если вы подключите еще один (а то и несколько носителей), нет гарантии, что роутер назначит системному USB-накопителю нужное имя. Поэтому, вместо имени раздела «device» указывайте уникальный идентификатор раздела «uuid».
Узнать идентификаторы разделов можно, выполнив команду block detect, после чего, внести соответствующие изменения в fstab. Если система устанавливается с нуля, лучше сформировать fstab автоматически:
Проверяем, что получилось:
Вносим изменения в файл /etc/config/fstab. Параметры раздела sda3, который был создан для NAS, пока закомментируем или удалим (настройкой NAS займемся позже):
Если параметры точек монтирования очевидны, то на параметрах секции global хотелось бы остановиться подробней:
Создаем временную директорию /mnt/sda2 (для переноса системы, которая расположена во внутренней памяти роутера), и монтируем в нее раздел USB-накопителя.
Копируем раздел /overlay с внутренней памяти роутера на раздел, который расположен на USB-накопителе. Операция копирования производится с сохранением всех прав.
Теперь можно отмонтировать раздел и удалить временную директорию:
Если все сделано правильно, роутер должен загрузиться с USB-накопителя. Если роутер не загружается: отключите USB-накопитель, загрузитесь с внутренним /overlay, подключите USB-накопитель, смонтируйте разделы и проверьте fstab (иногда, даже — несколько раз … это помогает :)) Проверено на себе!
После загрузки роутера, смотрим на доступную память (системный раздел и раздел подкачки):
Как видим, после внесенных изменений, раздел подкачки стал 249 Мб, а системный раздел 285 Мб.
Отлично! Теперь у нас полноценная платформа для экспериментов в области домашней автоматизации.
Resizing Ext4 rootfs
Resize Ext4 rootfs for ext4-combined.img.gz:
Resizing filesystem
Be sure to resize partitions before resizing filesystem. Note that online resizing should work for both F2FS and Ext4 on OpenWrt 19.07, although F2FS requires rebooting to apply changes.
1.1. Для устройств менее чем с 4 МБ флеш памяти
В образах прошивки OpenWrt по умолчанию нет инструментов для создание extroot, так как система сборки в настоящее время создает только barebone-образы.
Единственный способ использовать эти устройства - перестроить образ прошивки с нужными пакетами с помощью Image Builder.
Image Builder может работать только в 64-битной операционной системе Linux, поэтому, если у вас нет системы Linux, посмотрите инструкции по установке Ubuntu 64bit в VirtualBox.
Затем перейдите на ту же страницу загрузки, где вы можете загрузить прошивку для своего устройства, и прокручивать вниз, пока не найдете файл, начинающийся с “ OpenWrt-imagebuilder ”.
Загрузите его и распакуйте в папку в системе Linux.Откройте терминал в этой папке и напишите:
Это выведет на экран все возможные имена профилей для устройств, поддерживаемых этим Image Builder, чтобы мы могли создать образ для нужного устройства. Каждая запись будет выглядеть так:
Первая строка - это имя профиля, вторая строка - полное имя вашего устройства, третья строка - список пакетов по умолчанию для этого устройства, и в нем должны быть перечислены некоторые пакеты с USB или Sata или любым другим устройством хранения.
В нашем случаи это TP-LINK TL-WR1043N/ND v1, поэтому имя профиля этого устройства tl-wr1043nd-v1 Теперь нам нужно написать команду, чтобы начать сборку образа (обратите внимание, что имя после PROFILE= является именем профиля данного устройства, обязательно используйте имя профиля для своего устройства):
Это создаст образ прошивки, который может прочитать раздел, отформатированный в файловой системе ext4 на внешних устройствах хранения подключенных через USB.
К сожалению, пакет e2fsprogs с инструментами для файловой системы ext4 слишком велик, чтобы поместиться в 4 МБ. Если кто-то может отделить mke2fs и инструменты проверки файловой системы от него, то можно сделать отделенные инструкции по использованию файловой системы ext4.
После этого откройте папку bin внутри папки Image Builder, затем откройте папку target, затем папку, в которой вы ее найдете (она имеет имя, зависящее от типа устройства), а затем внутри папки. называется generic , и вы должны добраться образа для прошивки. Выберите правильный образ (factory или sysupgrade) и установите его.
Затем вам нужно будет отформатировать USB-накопитель в файловую систему ext4, и для этого вам потребуется использовать Linux LiveCD или gparted диск.
К сожалению, это неудобно, но, как сказано выше, мы не можем разместить инструменты форматирования на устройствах с 4 МБ флэш-памяти.Читайте также: