Openwrt установка на компьютер
Installation Checklist
This checklist cannot and does not completely cover all the ways you can install OpenWrt.
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.
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.
VM Setup in VirtualBox
Resizing F2FS overlay
Resize F2FS overlay for squashfs-combined.img.gz:
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:
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).
Run with VirtualBox automatically on Start of Windows OS
“VB-MYDEVICE”=“\”C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe\“ startvm \”NAMEOFVBINSTANCE\“ –type headless”
Веб-интерфейс
В большинство версий OpenWrt изначально входит веб оболочка LuCI. LuCI расшифровывается как Lua Configuration Interface. Перейдите в браузере по сетевому адресу вашего «роутера», ведите заданный вначале пароль и сможете поэксперементировать с LuCI.
Доступен русский перевод. Для установки перейдите раздел System — Software, введите в поле Filter слово «russian» и на вкладке Available packages (russian) установите пакет luci-i18n-russian. Либо установите его при помощи opkg, как описано выше, а затем выберите язык в разделе System — System — Language and Style — Language.
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.
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 document describes how to run the x86-64 OpenWrt images in VM VirtualBox, or VBox for short.
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.
Базовая конфигурация
Установив OpenWrt на ваше устройство, продолжите с базовыми настройками.
Troubleshooting
Promiscuous Mode of the corresponding Bridged Network Adapter to “Allow All” or else your local network won't be bridged properly to your vpn bridged network
You can also have 2 physical network interfaces on your main operating system that is hosting the virtual machine. In this case
VM setup
This article may contain network configuration that is version dependent post 2021-06
while legacy ifname syntax may work on 21.02 or recent master it is recommended that you migrate to device usage
More Information
This part of the configuration will deal with setting up networking manually.
The configuration you will set up by following this tutorial is:
eth0 of the VM on mng (management) interface, fixed address 192.168.56.2, set in VirtualBox as Host-only Adapter on adapter vboxnet0. This interface will be always available to the host even if host or VM are disconnected from any network.
eth1 of the VM on wan interface, dynamic address, set in VirtualBox as NAT . This interface will be used to access the Internet through whatever setup the host also uses.
(optional) eth2 of the VM on lan interface, configured depending on your local network, set in VirtualBox as Bridged Adapter. This interface allows other devices (host included) to connect to the VM as if it was a physical device in the local network. Will only work if there is already a local network of some kind.
For a setup with 2 bridged physical network cards WAN /LAN Setup see troubleshooting. The rest of this guide applies to a setup with 2 physical cards as well.
Virtualbox settings
Host-only network adapter
we first need to make sure there is a Host-only network adapter and that it has the right settings
Note: this is found in VBox 6.0 (at least for Windows) under Tools, and is pre-configured.
Click on File → Preferences → Network
On macOS, this setting may be found through File > Host Network Manager…
Click on Host-only Networks tab and then if you don't see a vboxnet0 entry click on the + icon on the right of the window to add a new one.
Now select the vboxnet0 entry, and click on the screwdriver icon on the right to open its settings.
(optional) you can also set the DHCP server as shown in the screenshot if you want to have dynamic addresses to the VM, but for this tutorial it is not required as we set a static address in the VM itself
Press OK to save and close until you are back to VirtualBox Manager interface again.
Network Settings
Open the VM's settings
Go in the Network tab
configure Adapter 1:
in the Name field select the name of the network card (ethernet or wifi) of your PC that connected to a local network. On Windows it has a full device name, on Linux it will have codenames like eth0, eth1 for ethernet or wlp2s0 for wifi.
Virtual Machine Settings
Due to limitations, the keyboard in the virtual machine's terminal is set to US, so some (or most) of your keys may not print the symbols as indicated by the keycaps.
Also, due to the fact that what you see there is a bare machine terminal and not a smart thing like a SSH program (Putty/Kitty/whatever) or a terminal emulator program, you cannot copy-paste text into it.
Don't worry, most of the setup will be done after you are connected with SSH (remote terminal) that does not have any of these issues.
Look at this US keyboard layout to find what button you need to press on your keyboard to generate the right symbol.
Press Enter to activate the console when the boot messages have finished scrolling by. It may take two or three minutes for “entropy” to be generated ( random: crng init done with OpenWrt 17.01.4). Until there is sufficient entropy, SSH and other cryptographic functions may fail.
After you have logged in successfully, we can actually do the true configuration, please copy-paste the following block of code and press enter:
now write uci changes to check if the setting configuration was loaded correctly. If you see the following (the network.mng entries MUST be the same as the ones shown here, the network.wan might be slightly different), everything went well
if all is well, save config with uci commit && reboot, if all is NOT well, write reboot to erase the temporary changes and find a way to set the above configuration manually.
now you should have both internet access (try a opkg update) AND a management interface with a static address you can connect your SSH client program to even if your PC is disconnected from a local network.
the optional Bridged Adapter on Adapter 3 isn't crucial for basic functionality and is also specific for your own local network parameters. In my own network (and in most home networks) it will work fine if you write
If you have more complex requirements you will have to set that up on your own by reading the documentation, or through luci.
you can now install packages to this images as normal, you will probably want to install luci, write opkg update && opkg install luci, then you can connect to the VM's luci by typing 192.168.56.2 in your browser address bar or click on this link to get there.
Выбор прошивки
Если интересующая вас прошивка доступна только как raw образ (img.gz, image.gz, bin) будет необходимо воспользоваться входящим в комплект VirtualBox конвертером. Под Windows для этого сохраните в папке VirtualBox (могут понадобиться права администратора) следующий текстовой файл и задайте ему расширение .bat или .cmd:
После чего распакуйте скачанный образ прошивки и перетащите его на данный скрипт. Полученный .vdi образ можно подключать к виртуальной машине.
2. Через автозагрузчик и Ethernet порт
Чтобы провернуть такой вариант, а именно принудительно залить прошивку, можно воспользоваться тем, что большинство автозагрузчиков содержат встроенный функционал для таких целей. Некоторые содержат TFTP-client, другие - TFTP -server, третьи FTP-client, а некоторые даже FTP -server. Вам необходимо выяснить:
какой порт используется для подключения к автозагрузчику по умолчанию (Если не можете ответить на этот вопрос, попробуйте порт по умолчанию);
важно также узнать время после включения, в течение которого ваше устройство принимает входящие подключения к автозагрузчику. Это может быть, например, время в 2 секунды, начиная с 3-ой секунды после включения устройства в сеть.
Как только вы получили ответы на все эти вопросы, вы можете продолжать:
установите, по необходимости, недостающие программы на ваш PC для доступа к роутеру (так, если автозагрузчик содержит FTP -server, вам нужен FTP -client);
прочитайте инструкции по использованию этих программ! например man tftp , man tftpd , man ftp , man ncftp , man ftpd , man pure-ftpd или другую документацию;
Замечание: Иногда даже автозагрузчик не позволяет записать файл прошивки на flash память устройства, например, в Inventel DV4210 (AKA Livebox).
Методы установки
Resizing Ext4 rootfs
Resize Ext4 rootfs for ext4-combined.img.gz:
Доступ к файловой системе
Запустите WinSCP (или аналог) и подключитесь к виртуальной машине.
Вы увидите стандартный двухпанельный файловый менеджер. Теперь вы можете редактировать конфигурационные файлы в удобном графическом режиме. Так же возможно копировать файлы в «роутер» и обратно. Попробуйте перейти в правой части в корень (/), а затем в /etc/config/ и запустить network.
При желании внесите изменения и сохраните результат.
Convert openwrt.img to VBox drive
Open a terminal and go in the folder where you have downloaded the file (sorry, the tool has only a command line interface)
Convert it to native VBox format by writing this in command line (the same for Windows, macOS and Linux. Sadly this tool does not have graphical user interface): VBoxManage convertfromraw --format VDI openwrt-*x86-64-combined*.img openwrt.vdi . This will create the openwrt.vdi file which a virtual drive for VBox virtual machine.
Error
If you receive an error similar to
you may need to pad the image with dd if=openwrt-x86-64-combined-ext4.img of=openwrt.img bs=128000 conv=sync and use the padded image as input to VBoxManage convertfromraw.
Безопасный режим
→ failsafe_and_factory_reset (используйте, только если персональная wiki страница не описывает процесс возврата на оригиналную прошивку)
Установка программ
В первую очередь, установите эмулятор VirtualBox, если его у вас нет. Чтобы иметь возможность выполнять команды вне консоли окна эмулятора, понадобится SSH клиент. Например, Putty. При этом вам станет доступен буфер обмена домашней системы. Для удобного доступа к файловой системе «роутера» нужен графический SCP клиент. Например, WinSCP для Windows. Для Linux будет достаточно встроенного файлового менеджера. Например, Krusader, Dolphin, Nautilus.
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.
Системный апгрейд
→ generic.sysupgrade (используйте, только если персональная wiki страница не описывает процесс возврата на оригиналную прошивку)
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.
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.
Method 4: via JTAG
Prerequisites
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.
Настройка сети
В первую очередь задайте пароль администратора, введя passwd и новый пароль в ответ на приглашение.
По умолчанию OpenWrt создаёт собственную подсеть, игнорируя существующие и получает в ней адрес 192.168.1.1. Вы можете попробовать подключиться к виртульной машине по этому адресу, задав своему компьютеру (сетевой карте либо виртуальному адаптеру хоста, в зависимости от сделанных настроек VirtualBox) статичный адрес в подсети 192.168.1.*. Но удобнее вариант, при котором эмулируемый «роутер» соединяется с существующей сетью, получая доступ в интернет и к устройствам в вашей сети. При помощи встроенного текстового редактора vi можно редактировать конфигурационные файлы. Наберите vi /etc/config/network для изменения настроек сети. Управление курсором в vi осуществляется стрелками, для удаления строки можно нажать dd, переход в режим редактирования происходит нажатием кнопки i, возврат в режим команд по Esc. Приведите данный файл к следующему виду (поменять option proto со static на dhcp):
После чего перейдя по Esc в коммандный режим наберите :wq и Enter для сохранения и выхода из редактора. Чтобы выйти без сохранения, наберите команду :q!. Эти настройки означают, что эмулируемый «роутер» попробует получить доступный ip адрес. Если у вас нет настоящего роутера и возможности получить более одного адреса — выберите в настройках сети VirtualBox режим «Виртуальный адаптер хоста».
Для применения новых настроек перезагрузите виртуальную машину или введите /etc/init.d/network restart.
После загрузки посмотрите адрес виртуальной машины, набрав ifconfig, в поле inet addr у eth0:
Поздравляю, OpenWrt запущена и доступна по сети. Имейте ввиду: данный адрес (192.168.1.23 в моём случае) — временный и может меняться после перезапуска эмулятора или спустя какое-то время (несколько часов). Запустите Putty и попробуйте подключиться к виртуальной машине по данному адресу. Логин для подключения – root, пароль вы задали при первой загрузке.
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.
Install a ramdisk-image into main memory
This step shows you howto upload a new ramdisk image to the device. The existing firmware on the flash remains unchanged! You require a working serial cable to do the ramdisk upload.
specifically select the RAMDISK option to make OpenWrt Buildroot create a ramdisk-image for you to upload
connect your serial cable to the header on the WNDR3700 and set your local terminal program (eg. minicom) to
power up the board. When it gets to the message asking you to press any key to interrupt the normal bootup sequence, press a key on the serial console (or just hold down the enter key from first bootup until you get to a prompt):
(if you forget the bootargs piece below, the board will boot and look normal, but it won't be able to bring up any of the network interfaces!)
Don't forget to consult the other Generic Basic Howtos for OpenWrt
Method 3: via Bootloader and Serial port
Настройка VirtualBox
Создайте новую виртуальную машину. Тип – Linux, версия – Linux 2.6. Откажитесь на данном этапе от подключения диска — это будет сделано позже.
Откройте свойства новой виртуальной машины (кнопка «Настроить») и перейдите в раздел Сеть. Вместо режима NAT выберите Сетевой мост (Bridged) – это позволит получить доступ к виртуальной машине с других устройств в сети. Если же у вас нет домашней сети (хотя бы роутера) оставьте NAT и добавьте второй адаптер «Виртуальный адаптер хоста».
Затем в разделе COM-порты обязательно поставьте галочку, чтобы активировать эмуляцию порта. В противном случае OpenWrt не сможет загрузиться.
Наконец, в разделе Носители добавьте к контролёру IDE образ прошивки OpenWrt, как жёсткий диск. Если к контроллёру SATA подключены устройства – удалите их.
Нажмите OK, сохранив настройки.
Four Installation Methods
There are four ways to install OpenWrt on a device:
Select an OpenWrt image
You need a x86 64 bit version of OpenWrt. There is two versions of them:
combined-squashfs.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.
combined-ext4.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.
In the guide we'll use openwrt-x86-64-combined-ext4.img.gz because it has less limits.
Download a stable release of the openwrt-x86-64-combined-ext4.img.gz image from targets/x86/64/ folder e.g. 19.07.2. Or you can try the fresher but unstable snapshot image
Uncompress the gziped img file. On Linux use the command gzip -d openwrt-*x86-64-combined*.img.gz . As a result you should get the raw openwrt-x86-64-combined-ext4.img image file.
Custom Images
You can compile your own image (Target System → x86-64 and Target Images → Build VirtualBox image files). ext4 needs to be enabled first.
4. через JTAG
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.
VM creation
Tutorial and screenshots from VirtualBox 5.1.8 on Linux host, on Windows or macOS hosts there will be some cosmetic differences (a different top bar) but the VirtualBox panels and buttons will be exactly the same
Start VirtualBox and click New to add a virtual machine (VM)
Choose a Name for your virtual machine, choose Linux for Type, and Linux 2.6 / 3.x / 4.x (64-bit) for Version, then click Next.
OpenWrt will work fine with much less RAM than the recommended amount, 128 MiB will be enough.
Choose Use an existing hard disk file, click the file icon to open Virtual Media Manager, click Add and choose your openwrt.vdi file using the file chooser window. Click Create to end this guided procedure.
It's recommended to place the disk image in a permanent place before linking it with VBox. If you move it afterwards, VBox will not find it anymore and will complain about this issue on next start (or when you try to start the VM). It will offer a guided procedure to link the disk image again, so don't worry.
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.
Перезаливка с OpenWrt
Однажды установив и запустив OpenWrt, у вас появится множество удобных инструментов для перезаливки прошивки через интерфейс командной строки командой mtd . Указывайте интересующий вас раздел (пожалуйста, просмотрите flash_layout или flash_layout или flash_layout для обозначений.
И, конечно, самый простой вариант апгреда через Web-интерфейс так же возможен.
Чтобы перезаписать существующую флэш память рядом с разделом, где установлен автозагрузчик, а так же ту часть, которая содержит ART, в случае устройства WR1043ND и схожих с ним можно использовать:
Вы можете, хотя это не рекомендовано, установить прямой туннель для установки прошивки без копирования ее на временный раздел tmpfs flash-памяти роутера. В таком случае, вот ваши действия:
на обслуживающей машине: включите сервис netcat с прослушиванием на 5050 порту, отправьте прошивку в тот момент, когда будет установлено соединение:
Последняя описанная процедура не рекомендована, но она может быть использована в случае, если у вас обнаружится дефицит памяти на устройстве.
→ generic.uninstall (используйте, только если персональная wiki страница не описывает процесс возврата на оригинальную прошивку)
3. через автозагрузчик и Serial порт
Method 2: via Bootloader and an Ethernet port
Most, if not all bootloaders provide built-in functionality for this purpose. Some use a TFTP-client, others a TFTP -server, others a FTP-client, some an FTP -server, some a web server and some use the XMODEM-protocol.
Before proceeding you need to determine the following:
Once you know all of the above parameters, you may proceed.
Install the appropriate software on your PC (i.e. if the bootloader uses an FTP -server, you need a FTP -client).
NOTES: Sometimes even the bootloader prevents you from flashing a non-OEM firmware. If you have a short time window, the connection between your computer and device needs to be established quickly. To make this as quick possible, you can disable auto-negotiation on your NIC and/or disable media sensing.
Specific Howtos
Пояснения
Четыре пути
Существует четыре способа установки OpenWrt на ваше устройство:
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.
Что такое Image File?
Image file (файл образа) - это побайтовая копия всех данных, используемых в файловой системе. Если вы установите GNU/Linux простым способом на один или несколько разделов вашего жесткого диска, а потом скопируете все содержимое байт за байтом с вашего жесткого диска в один файл:
то полученный файл /media/sdb3/backup-sda.dd и будет являться файлом образа (Вашего дискового тома /dev/sda).
Разница с OpenWRT лишь в том, что рабочие OpenWrt-Image-File так не создаются Они создаются специальной программой Image Generator (ранее называвшейся Image Builder). Вы можете прочитать больше:
imagebuilder Если вы хотите узнать больше об Image Generator, вернитесь в раздел downloads и выберите второй путь.
- Last modified: 2020/12/14 09:04
- by tmomas
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
The installation of OpenWrt is device specific. These device specific procedures should be found in the wiki. See Table of Hardware for available procedures. If your device is not listed, information in this Howto may be helpful.
Warning!
This section describes actions that might damage your device or firmware. Proceed with care!
If your attempt to install OpenWrt fails, please view generic.debrick for fixes.
This HOWTO is VERY generic. You cannot use it in most situations, as you have to adapt values and other parts for specific hardware. Please look at the supported hardware page for device-specific documentation.
In most circumstances; you have three options:
See also
- Last modified: 2021/07/23 10:43
- by someothertime
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
OpenWrt не может быть установлена настолько просто и безопасно, как любой другой дистрибутив GNU/Linux. Установка на Flash-чип, впаянный в PCB карту, к сожалению, несколько более затруднительна, чем установка с диска DVD на жесткий диск. После того, как вы выбрали ваш метод получения прошивки (по-английски firmware image) уникальной для вашего устройства и иногда даже модели и версии, вам придется перезаписать оригинальную прошивку на чипе flash-памяти. На этой странице вы найдете описание того, как сделать это.
По сравнению со сборкой дистрибутива, установка файла с прошивкой OpenWrt иногда может быть самым непростым во всей процедуре, а иногда занимает пару минут. В зависимости от конкретной модели вашего устройства, вы можете ограничиться простой заливкой вашей новой прошивки через web-интерфейс; можете вручную заливать необходимую прошивку через tftp; или, если ваши дела совсем плохи, то вплоть до изменения структуры вашего устройства и подключения через JTAG доступ. Но в целом, основным вариантом установки является установка через вшитый загрузчик (Redboot, Uboot и проч.) или простое копирование на CompactFlash-карточку: все зависит от конкретной модели вашего устройства.
Warning!
This section describes actions that might damage your device or firmware. Proceed with care!
Заливка неверной версии файла прошивки не обязательно должна сломать ваше устройство, но вам придется пройти через некоторые трудоемкие процедуры, чтобы оживить его. Иногда, вам придется использовать модифицированный Serial кабель, и роутер может не заработать с первого раза.
Это HowTo ОЧЕНЬ общее. Вам не следует сразу приступать к работе, изучив только эту страницу, не адаптировав процедуру по установке OpenWrt для вашего конкретного устройства. Честно говоря, у нас просто нет столько людей, чтобы писать подобные объяснения для всех сотен поддерживаемых устройств. Поищите описание по установке для вашего устройства на странице поддерживаемых устройств. Если такого описания нет, продолжайте чтение.
В целом, у вас есть две опции: Залить OpenWrt в постоянную память, или запускать OpenWrt через сеть. Netbooting поддерживается не всеми вариантами загрузчиков, вшитых в устройства. Пожалуйста, ознакомьтесь с конкретной страницей wiki посвященой модели вашего роутера. Если ваши попытки установить OpenWrt провалились, статья о том, как оживить роутер поможет вам. Обязательный раздел к прочтению →flash.layout.
Установка пакетов
Имейте ввиду, архитектура вашей прошивки и устанавливаемого пакета должна совпадать.
1. Из-под оригинальной прошивки
Откройте в вашем браузере Web-интерфейс оригинальной прошивки и установите файл OpenWrt через опцию “Firmware Upgrade”. Готово. Как правило, нужный файл прошивки OpenWRT содержит в названии подстроку “-factory”, например, openwrt-ar71xx-generic-wndr3800-squashfs-factory.img
Замечание: Иногда оригинальная прошивка проверяет, какой файл ей предлагают для “обновления”. В случае, если заводская прошивка решит, что предлагаемый ей файл не является приемлемым, вам не удастся установить OpenWrt одним кликом. Не отчаивайтесь, попробуйте один из оставшихся трех путей.
Method 1: via OEM firmware
Open the WebUI of the OEM firmware with your web browser and install the OpenWrt factory firmware image file using the “Firmware Upgrade” option. Your device should reboot with OpenWrt installed.
NOTE: Sometimes the OEM firmware will only allow you to flash your device with a specific firmware file. If that is the case, you will not be able to install OpenWrt using this method. However, for some devices the build bots prepare tagged builds such that they are compliant with the firmwares from the manufacturer. This should be documented on the device specific page for your model.
Читайте также: