Точечный обход блокировок pkh на роутере с openwrt с помощью wireguard и dnscrypt

Содержание:

Notes

: Scripts used to mount and check block devices (file systems and swap), as well as hotplug scripts to automount and check block devices when hotplug event (e.g. from plugging in a device) occurs. Also includes preinit scripts for mounting a block device as the root filesystem. This allows one to have the root filesystem on devices other than the built in flash device.
As of trunk r26314 and have been merged with , they’re still separate in Backfire.
In the OpenWrt ‘Backfire’ 10.03 release there is a bug. Solution is: and put a in front of the line:

echo '# WARNING: this is an auto generated file, please use UCI to set defined filesystems' > /etc/fstab

This creates the file and thus prevents creating a symlink to . In order for UCI to work, there need to be symlink! In case the bug has already taken place, delete /etc/fstab and then type this code to busybox.

ln -s /tmp/fstab /etc/fstab

It will create a symlink to the /tmp/fstab file, fixing the bug completely.

In the OpenWrt ‘Backfire’ 14.07 release, the tmpfs resize option via fstab config does not work

Примеры

Выполняется установка поддержки USB хранилища, предполагается, что USB уже настроен, включим поддержку файловой системы ext4 и подключим подсоединённое устройство USB, с уже созданным разделом подкачки Linux и разделом ext4.

opkg update
opkg install kmod-usb-storage block-mount kmod-fs-ext4
mkswap /dev/sda1
swapon /dev/sda1
mkdir -p /mnt/share
mount -t ext4 /dev/sda2 /mnt/share -o rw,sync

Помните, что разделы часто определяются автоматически и следующая команда тоже должна работать с настройками по умолчанию:

  mount /dev/sda2 /mnt/share
opkg update
opkg install kmod-usb-storage block-mount block-hotplug kmod-fs-ext4 kmod-fs-vfat kmod-nls-cp437 kmod-nls-iso8859-1
mkdir -p /mnt/usb
mount -t vfat /dev/sda1 /mnt/usb

Дополнительная настройка после обновления OpenWRT

Проверка новой версии ОС

* В Luci, перейдите к положению> Обзор, чтобы подтвердить, что вы запускаете новый релиз OpenWRT
* В SSH баннер входа содержит сведения о выпуске

Проверьте наличие обновляемого пакетов

После первоначального обновления рекомендуется проверить наличие обновленных пакетов, выпущенных после создания базового образа микропрограммы ОС.

Перечислите любые доступные обновляемые пакеты:

opkg update
opkg list-upgradable
  • Обновите все перечисленные пакеты (если они были перечислены) — можно включить несколько пакетов
  • Примечание: на устройстве только с 4МБ NVRAM, эти обновления могут не соответствовать — проверить наличие свободного места на / first with “df -h /” и убедитесь, есть по крайней мере, 600KB или так свободно
  • Примечание: обновления ниже были доступны по состоянию на 12 сентября 2015 года обновления OpenWrt 15.05
opkg upgrade luci-lib-ip luci-theme-bootstrap luci-app-firewall luci-proto-ppp luci-mod-admin-full luci-base luci-proto-ipv6 luci-lib-nixio luci

* Убедитесь,что пакеты больше не могут быть обновлены; команда не должна отображать выходные данные

opkg list-upgradable

Переустановите пакеты, установленные пользователем

После успешного обновления необходимо переустановить все ранее установленные пакеты. Вы составили список этих выше. Файлы конфигурации пакетов должны быть сохранены из-за действий, описанных выше, но не из-за самих пакетов.

Например:

opkg update
opkg install snmpd-static

Настройка установленных пользователем пакетов

В новых установках пакета будут установлены новые версии файлов конфигурации пакета по умолчанию. Поскольку существующие конфигурационные файлы уже были созданы, opkg отображал бы предупреждение об этом и сохранял новые версии конфигурационных файлов в разделе …-opkg имена.

Новые файлы конфигурации пакета, предоставляемый должны быть сопоставлены с вашими старыми настраиваемыми файлами для слияния в любых новых функций или изменения синтаксиса в этих файлах.

Программа diffutils полезна для этого.

Например:

# Установить Diffutils
opkg install diffutils
 
# Найти все файлы -opkg
find etc -name *-opkg
 
# сравниваем старые настроенный файл /etc/config и/snmpd будет с новый общий файл /etc/config и/snmpd будет-opkg
diff etcconfigsnmpd etcconfigsnmpd-opkg 
 
# слияние всех необходимых изменений в активной версии файла конфигурации
vi etcconfigsnmpd
# и очистить путем удаления пакета менеджер-версию файла конфигурации
rm etcconfigsnmpd-opkg
 
# Или если новая версия предоставляется сопровождающим пакета следует просто заменить старый конфигурационный файл,то просто поменять его в
mv etcconfigsnmpd-opkg etcconfigsnmpd

Включить и запустить установленные пользователем пакеты

* Наконец, вновь установленные пакеты должны быть включены и запущены (если это необходимо; многие делают)

etcinit.dsnmpd enable
etcinit.dsnmpd start

Выполните пробную перезагрузку

Обновление полностью завершено. Хорошая идея сделать тестовую перезагрузку и убедиться, что все ожидаемые функциональные возможности работают, как и раньше.

reboot

Необходимые пакеты для USB Хранилища

Когда ваше USB устройство правильно распознано системой, используя правильный драйвер ядра из списка базовая поддержка USB, следующие пакеты позволят осуществить поддержку USB хранилища:

  • требуется … Поддержка ядром запоминающих устройств USB.

  • требуется … файловая система вашего устройства. Зачастую это kmod-fs-ext4, kmod-fs-hfs, kmod-fs-hfsplus, kmod-fs-msdos, kmod-fs-ntfs, kmod-fs-reiserfs и kmod-fs-xfs.

  • опционально … Поддержка ядром большего количества устройств, таких как SmartMedia считыватели кард.

  • рекомендуется & … Скрипты для подключения и проверки устройств (файловые системы и раздел подкачки), а также горячего подключения (распознование только что подключенных устройств).

  • Любое запоминающее устройство это обычное SCSI устройство.

До релиза , требовались дополнительные пакеты: для распознавания USB при подключении и для корневой файловой системы на внешнем носителе. В сборке r26314 они были объединены в единый .

Начальная конфигурация

Установка пакетов

Пакет требуется для работы fstab. Его функциональность теперь предоставляется . Он создан для поддержки стандарта конфигурации init.d:

  1. Установка

    opkg update
    opkg install block-mount 

Автоматическое создание fstab

После сборки r36988, когда устанавливается , вы может использовать новую утилиту . Вызовите для получения простой конфигурации uci в файл. Далее вы можете ее изменить на свое усмотрение.

Для быстрого создания fstab можно использовать:

block detect > /etc/config/fstab

Далее отредактируйте ваш fstab в редакторе vi. Для понимания как работает редактор смотрите vi:

vi /etc/config/fstab

Если точка монтирования “корень” то вы начнете использовать extroot в процессе загрузки. Так же смотрите Extroot. Запустите для получения актуальных uuid доступных файловых систем. Так же смотри : block_mount для технических подробностей о процессе монтирования и использованных скриптах и командах.

Enable fstab at Boot

  1. enable (make it start automatically on every boot up)

    /etc/init.d/fstab enable
  2. and start (right now)

    /etc/init.d/fstab start

Whenever you change your configuration, restart this to make it take effect:

/etc/init.d/fstab restart

As of, or before 2014-04-14, running:

/etc/init.d/fstab start|restart

results in the following error message:

this file has been obseleted. please call "/sbin/block mount" directly

. Need to document the new proper way of doing things for Barrier Breaker.

Background

There are many package managers used for Linux systems. You may already be familiar with the ones most popularly used in desktop and server distributions of Linux: (, , etc), , and . You may even be familiar with some of the less popular ones, such as (from gentoo’s ), the Mac OS X GNU tools package manager , and the BSD package manager, . The package manager used by EMAC OE is similar to these tools, but is the popular choice for embedded Linux: . If you’re already familiar with any of the desktop/server package managers listed here, should be very easy to learn since it is quite similar to all of those tools. If not, it should still be easy to learn because it has a well designed interface.

Known issues

  • Transition to ath79: several devices that are supported in are not yet supported in : this is a community effort. Helping to port devices to to make them available in future releases is very welcome.
  • Device support: images for some device became too big to support a persistent overlay, causing such devices to lose configuration after a reboot. If you experience this problem, please report the affected device in the forum and consider downgrading to OpenWrt 18.06 or using the Image Builder to pack a smaller custom image
  • Device support: unstable Ethernet link with atheros switch on some ath79 devices (such as TL-WR841N): FS#2216, FS#2730

  • LuCI web interface: some optional GUI packages crash with an error about missing “cbi.lua”, install the package to fix these
  • LuCI web interface: due to changes in menu rendering, a logout/login cycle or device reboot might be required to make additional menu items appears after package installation (GH#4077)

See also: active bug reports for openwrt-19.07

Informational Commands

List available packages

Package name - Version - Description

The Description can contain line breaks, so using merely grep is inapt since grep is line-based.

List installed packages
List installed and upgradable packages
List user modified configuration files
List files belonging to <pkg>. The package has to be already installed for this to work. Example:

opkg files asterisk18
Package asterisk18 (1.8.4.4-1) is installed on root and has the following files:
/usr/lib/asterisk/modules/res_rtp_multicast.so
/usr/lib/asterisk/modules/codec_ulaw.so
/etc/asterisk/features.conf
/usr/lib/asterisk/modules/format_wav_gsm.so
/usr/lib/asterisk/modules/app_macro.so
/usr/lib/asterisk/modules/chan_sip.so
/usr/lib/asterisk/modules/app_dial.so
/usr/lib/asterisk/modules/app_playback.so
/usr/lib/asterisk/modules/format_gsm.so
/usr/lib/asterisk/modules/func_callerid.so
/usr/lib/asterisk/modules/func_timeout.so
/etc/asterisk/asterisk.conf
/etc/asterisk/modules.conf
/usr/lib/asterisk/modules/format_wav.so
/etc/asterisk/extensions.conf
/etc/init.d/asterisk
/etc/asterisk/manager.conf
/usr/lib/asterisk/modules/res_rtp_asterisk.so
/etc/asterisk/logger.conf
/etc/asterisk/rtp.conf
/usr/lib/asterisk/modules/codec_gsm.so
/etc/asterisk/indications.conf
/usr/lib/asterisk/modules/func_strings.so
/usr/lib/asterisk/modules/app_echo.so
/usr/lib/asterisk/modules/format_pcm.so
/etc/asterisk/sip_notify.conf
/etc/asterisk/sip.conf
/etc/default/asterisk
/usr/sbin/asterisk
/usr/lib/asterisk/modules/pbx_config.so
/usr/lib/asterisk/modules/func_logic.so
List package providing <file>
Display all info for <pkg>

Package: horst
Version: 2.0-rc1-2
Depends: libncurses
Provides:
Status: install user installed
Section: net
Architecture: ar71xx
Maintainer: Bruno Randolf <br1@einfach.org>
MD5Sum: 378cea9894ec971c419876e822666a6a
Size: 19224
Filename: horst_2.0-rc1-2_ar71xx.ipk
Source: feeds/packages/net/horst
Description:  is a scanning and analysis tool for 802.11 wireless networks and
 especially IBSS (ad-hoc) mode and mesh networks (OLSR).

The size is the size of the gzip compressed tar archive. At installation package gets un-tared and decompressed, but then again JFFS2 uses compression itself. Since the compression of JFFS2 is transparent, commands like will always report the size of the uncompressed file.

Display all status for <pkg>
Download <pkg> to current directory
Compare versions and using the operators , , , , , or
List installable package architectures
This only works for installed packages. So if you would like to know, how much storage a package and all of it’s dependencies would need, at the moment, you will have to piece this information together with the -option.
This only works for installed packages. So if you would like to know, how much storage a package and all of it’s dependencies would need, at the moment, you will have to piece this information together with the -option.

Highlights in OpenWrt 19.07

With this release, the OpenWrt project brings all supported targets back to a
single common kernel version and further refines and broadens existing
device support. It also introduces a new target and brings support for WPA3.

Target transition from ar71xx to ath79

This release provides initial support for the new target, the future device tree based successor of the popular target. For 19.07, both targets are still built, but it is recommended to switch to the target whenever possible: future releases of OpenWrt will drop support for the target. See the ath79 technical reference for rationale about the transition.

To perform the upgrade, please follow the instructions from Upgrading from ar71xx to ath79. Functionality for a given device should be equivalent between the two targets: if this is not the case, please report the issue and revert back to ar71xx if needed.

WPA3 support

The 19.07 release brings initial support for WPA3. However, WPA3 is not enabled by default and requires installing specific packages: to run WPA3 as an access point, is needed. For use as a Wi-Fi station, you need either (station support only) or (AP + station). Due to their large size, these packages are not installed by default, and it is impossible to install them on devices with less than 8MB flash.

It should also be noted that many existing client devices will never support WPA3, and that there are client devices that support WPA2 but cannot connect to an AP configured with WPA2+WPA3 mixed mode. Please only file bugs if you are sure the problem is not client related.

To configure your device as a WPA3 access point, see

Client-side rendering of the LuCI web interface

The new version of LuCI, the integrated web interface for OpenWrt, implements client-side rendering of views. This improves performance by offloading some work that was done on the device (Lua code) to the client browser (Javascript code)

The LuCI ecosystem is large, and not all LuCI apps have been adapted to this change, which may result in crashes involving . In that case, install the package.

If LuCI is loading slowly, consider installing , close and reopen the browser tab to start a new LuCI session.

With this step, Lua usage in LuCI is reduced and LuCI effectively comes closer to the goals of the experimental LuCI2 without having to rewrite everything from scratch.

Examples

To install a package run the following commands. List of available packages is lost upon reboot, so make sure to update the list before trying to install a package

opkg update
opkg install <package>

To search

  • will display only

  • will display all available information.

You can make use of glob patterns directly and also write a little shell script to use Regular expressions and otherwise further process information. Use a pipe () and or or to filter that output:

  • doesn’t work either.

Mass upgrade of all “upgradable” packages is not a good idea, as opkg only indicates that there is a newer version of the package, but does not do any further evaluation. Exceeding the flash space or failing to download all needed upgrades might brick the router. However, if you want to try that, there is one-liner to do it:
command upgrades all installed packages that are currently “upgradable” Read the cautionary file system notes first before trying to upgrade all packages.

Альтернативные процедуры обновления ОС до Luci или sysupgrade

mtd

Netcat

Прямой метод

Netcat можно было бы использовать, если вы не можете свободно достаточно оперативной памяти. См netcat. Netcat должен быть установлен первым.

Этот метод НЕ рекомендуется!

Косвенный метод

Этот метод намного безопаснее, если у вас достаточно оперативной памяти.

Этот метод отлично подходит для самостоятельной сборки firmwares.

Вы должны проверить, сколько оперативной памяти у вас есть в настоящее время.(В случае, если у вас нет достаточно осталось, обратитесь бесплатно оперативную памятьFree up RAM.)

Передача файла изображения во временную папку

Напишите это для вспышки

ИЛИ

Я тестировал под Ubuntu 11.10.

Некоторые полезные ссылки для Netcat

scp

Убедитесь, что маршрутизатор имеет достаточно памяти.

Убедитесь, что вы установили пароль для маршрутизатора (для включения SSH необходимо установить пароль для маршрутизатора). См. First Login для получения более подробной информации.

Скопируйте прошивку на маршрутизаторе

На вашем компьютере Linux запустите:

Ввод «да» estabilish подлинность,а затем введите пароль вашего маршрутизатора. Подождите scp команда завершена.Теперь вы можете видеть прошивку в /tmp каталог.

Написать прошивку вашего маршрутизатора

Заметка

или вы можете проверить файл /etc/config/network file, 127.0.0.1 является петлевой IP адрес, другой является IP адрес вашего маршрутизатора.

Extras

Functions

Function Description
Initialize Opkg configuration from stdin or file
Import Opkg configuration from sysupgrade backup to UCI
Back up the list of installed packages to UCI
Install missing packages, optionally from a specific list, e.g. , ,
List packages by destination
Process packages one by one, the command is , , etc.
Upgrade all installed packages, optionally on or
Find new configurations
mkdir -p etcprofile.d
cat  << "EOF_cat" > etcprofile.dopkg.sh
# Initialize Opkg configuration
opkg_uci() {
    if ! uci -q show opkg > devnull
    then uci import opkg < devnull
    fi
    uci -q batch << EOF
delete opkg.overlay
delete opkg.rom
delete opkg.rwm
set opkg.overlay=overlay
set opkg.rom=rom
set opkg.rwm=rwm
set opkg.custom=custom
$(sed -r -e "s/^(.*)\s(.*)$/add_list opkg.\2.pkg=\1/")
commit opkg
EOF
}
 
# Import Opkg configuration from sysupgrade backup
opkg_import() {
    local OPKG_BACK="${1:-/etc/backup/installed_packages.txt}"
    sed -e "s/\sunknown$/\trwm/" "${OPKG_BACK}" | opkg_uci
}
 
# Back up the list of installed packages
opkg_backup() {
    opkg_list_dest | opkg_uci
}
 
# Install missing packages from the list
opkg_restore() {
    local OPKG_LIST="${1:-overlay}"
    local OPKG_PKGS="$(uci get opkg."${OPKG_LIST}".pkg)"
    local OPKG_INST="$(mktemp -t opkg.XXXXXX)"
    local OPKG_BACK="$(mktemp -t opkg.XXXXXX)"
    opkg list-installed | sed -e "s/\s.*$//" > "${OPKG_INST}"
    echo "${OPKG_PKGS}" | sed -e "s/\s/\n/g" > "${OPKG_BACK}"
    opkg_proc install $(grep -v -x -f "${OPKG_INST}" "${OPKG_BACK}")
    rm -f "${OPKG_INST}" "${OPKG_BACK}"
}
 
# List packages by destination
opkg_list_dest() {
    find usrlibopkginfo -name "*.control" "(" \
    "(" -exec test -f rom{} ";" -exec echo {} rom ";" ")" -o \
    "(" -exec test -f overlayupper{} ";" -exec echo {} overlay ";" ")" -o \
    "(" -exec echo {} rwm ";" ")" ")" | sed -e "s/.*\///;s/\.control\s/\t/"
}
 
# Process packages one by one
opkg_proc() {
    local OPKG_PKG=""
    local OPKG_CMD="${1:?}"
    if  -z "${2}" 
    then local OPKG_PKGS=""
    else local OPKG_PKGS="${@#* }"
    fi
    for OPKG_PKG in ${OPKG_PKGS}
    do opkg "${OPKG_CMD}" "${OPKG_PKG}"
    done
}
 
# Upgrade all installed packages
opkg_upgrade_all() {
    local OPKG_DEST="${1:-.*}"
    local OPKG_INST="$(mktemp -t opkg.XXXXXX)"
    local OPKG_UPGR="$(mktemp -t opkg.XXXXXX)"
    opkg_list_dest | sed -n -e "s/\s${OPKG_DEST}$//p" > "${OPKG_INST}"
    opkg list-upgradable | sed -e "s/\s.*$//" > "${OPKG_UPGR}"
    opkg_proc upgrade $(grep -x -f "${OPKG_INST}" "${OPKG_UPGR}")
    rm -f "${OPKG_INST}" "${OPKG_UPGR}"
}
 
# Find new configurations
opkg_newconf() {
    find etc -name "*-opkg"
}
EOF_cat
. etcprofile

Tips and Tricks

Write text file with list of installed packages

With following command it’s possible to create a list of installed packages, and write the list in a text file.

The list with the name e2plugins can be found in the directory . This file can be used to show the installed packages, and reinstall the plugins after a new image was flashed. Of course you have to copy the list from the HOST on your computer (e.g. using FTP).

opkg list-installed *extensions* | awk '{ print $1 }' > /home/root/e2plugins

Install the content of the list is possible with following command. Make sure the text file is in the directory . And of course the packages should be available on the feeds.

opkg update && opkg install $(cat /home/root/e2plugins)

An other method to install multiple packages is described in the chapter other interesting commands. But you need to know the names of the packages.

Установка LEDE поверх OpenWRT Chaos Calmer

Подробности
Категория: Настройка
Опубликовано: 17 января 2018
Просмотров: 8103

После объявления слияния проектов LEDE и OpenWRT под эгидой последнего, но по пути развития текущей версии первого — пришлось начать постепенный переход своих роутеров на новую ветку. Как было объявлено в скором времени OpenWRT прекратит всякую поддержку ветки Chaos Calmer, которая закроет страницу своей 10 летней истории и начнется эра нового проекта. Основан он будет на LEDE 17 версии, быть может даже название менять и не будут. Поэтому было решено познакомится с перспективой на ближайшее будущее поближе. 

На всех моих роутерах последнее время стабильно трудилась Chaos Calmer 15.05.1 с некоторыми ручными допиливаниями. На официальной странице LEDE было написано, что в виду огромной совместимости форка LEDE и собственной коренной OpenWRT пользователь может установить прошивку LEDE поверх прошивки OpenWRT, то есть просто обновиться методом sysupgrade. Варианта 2 — из командной строки, либо через веб-интерфейс LuCI. 

1. Обновление Chaos Calmer 15.05.1 до Lede 17.01.4 из веб-интерфейса LuCI

Для начала нужно скачать подходящую прошивку. Так как обновляться до LEDE я буду на своем мобильном роутере TP-LINK MR3040, который трудится у меня в авто не первый год. Железо у меня 2 ревизии, поэтому прошивка под мое устройство называется tl-mr3040-v2-squashfs-sysupgrade.bin. 

Если вы зальете в свой роутер прошивку не той версии железа из которой собран ваш роутер — то получите кирпич.

Если зальете прошивку не от своего устройства — то тоже получите кирпич.

Если зальете прошивку factory через OpenWRT — тоже вероятно получите кусок пластика вместо роутера.

Поэтому к выбору прошивки под свое устройство подходим очень серьезно. Стабильные прошивки найти можно тут https://downloads.lede-project.org/releases/

У меня сейчас стоит Chaos Calmer 15.05.1. Обновлять будем через LuCi. 

Для этого в меню System переходим по пункту Backup / Flash firmware. Для начала создадим бэкап настроен по кнопке Generate Archive. Вдруг придется откатываться. Далее выбираем файл нашей прошивки и ждем кнопку Upload archive. 

OpenWRT покажет инфу о прошиваемом файле. Размер, контрольную сумму. И указание в моем случае, что файлы настроек будут стерты из памяти устройства. Перед нажатием кнопки Proceed устройство должно быть подключено в розетку, дабы аккумулятор не сел в самый неподходящий момент. 

После чего обновится окно прошивки. В процентах тут ничего вам не покажет, просто тупо подождать пару минут и в новой вкладке попробовать зайти на ваш роутер по его ip. У меня это 192.168.1.1

И LEDE гостеприимно попросит вас начать настройку системы с нуля. Чего я собственно и хотел. Аналогичным способом можно откатиться к Chaos Calmer с LEDE, главное всегда шить sysupgrade версию прошивки. 

Если у вас не установлена web оболочка LuCI, то шить прошивку будем прямо из ssh. 

2. Обновление Chaos Calmer 15.05.1 до Lede 17.01.4 из командной строки

Авторизируемся по ssh на устройстве. Скачиваем файл прошивки в директорию /tmp.

wget -P /tmp http://downloads.lede-project.org/releases/17.01.4/targets/ar71xx/generic/lede-17.01.4-ar71xx-generic-tl-mr3040-v2-squashfs-sysupgrade.bin

После чего обновляемся 

sysupgrade -v /tmp/lede-17.01.4-ar71xx-generic-tl-mr3040-v2-squashfs-sysupgrade.bin

после обновления уходим в reboot и начинаем извращаться теперь уже в LEDE.  

  • Назад

  • Вперёд

Non-standard Installation Destinations

Due to its history (fork of ipkg), opkg can specify a destination different than root for package installation, but since most packages don’t support this natively, it’s more a curiosity than actually useful.

The recommended way to have more space to install your packages is Extroot

WARNING: this solution will NOT work out-of-the-box in most cases, OpenWrt packages are designed to be installed in root filesystem and may need additional symlinks or modifications to work at all under the changed path!

The default opkg.conf actually contains three destinations:

dest root /
dest ram /tmp
dest mnt /mnt

The format of destination lines is simply the keyword dest, followed by a name for this destination (this can be anything), followed by a filesystem location. Any destination that has been thus configured can then be specified on the opkg command line like this:

opkg -d destination_name install somepackage

The dest argument must refer to one of the defined destinations in , e.g. to install packages to .

If you want to install kernel modules on any other destination than root, you might want to read this first: https://dev.openwrt.org/ticket/10739

Troubleshooting

  • Add option force_space in to allow installation of packets bigger than your partitions free space:

    echo option force_space >> /etc/opkg.conf
  • On Barrier Breaker, will create a file on extroot filled with uuid of mtd partition . At boot time when trying to do extroot, would try to check the actual uuid with the content of . If they did not match, extroot would fail. So if you want to continue use extroot after flashing a new firmwre, 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 . 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.

General Information

The basic capabilities of are available in OE 4.0 and earlier, but no packages are available online for these older versions. EMAC OE 5.X adds an online package repository complete with important updates for packages during the support window for each release. EMAC creates and hosts packages for all of our standard offerings, and may add updated packages as needed. EMAC recommends checking for and installing any updates available for your OE 5.X system prior to creating the final image which will be used to deploy your systems to ensure your image contains the latest bug fixes and security patches. It is important to remember to retest your application after an update to ensure that everything still works as expected, just as you would have to do for a desktop application.

Should your application require the ability to be updated/upgraded remotely, EMAC is able to provide assistance and services for creating custom packages for your application and hosting these packages for a modest fee. We will also assist you with configuring the systems to check for and install these updates. Please contact EMAC support should you need more information about this extra level of support.

The tool is used to work with the OPKG package management system. This tool provides the user with many different capabilities. In this document, only the basic capabilities are described. More information can be found in the last section of this page.

Preservation

Next, you’ll need to determine what files will be preserved through the upgrade by using the command below.

opkg list-changed-conffiles

If a file or directory is not in this list, it will not be preserved through the upgrade.

OpenWrt will preserve any files or directories listed in /lib/upgrade/keep.d/ (e.g., /lib/upgrade/keep.d/keep.me) or /etc/sysupgrade.conf. The easiest thing to do is list your needed files or directories in /etc/sysupgrade.conf. My file is shown below.

## This file contains files and directories that should
## be preserved during an upgrade.

/etc/config/
/etc/crontabs/
/etc/uhttpd.crt
/etc/uhttpd.key
/etc/rc.local

You can see that I’m choosing to preserve the entire /etc/config directory, as well as all my crontabs, the certificate and key for LuCI, and my startup file.

Upgrade

I recommend using the sysupgrade utility, since it’s tailor-made for this process.

Start by downloading the new firmware. For upgrades, always use the firmware that ends in sysupgrade.bin, not the factory.bin firmware. In my case, I’m using a  going from 15.05 to 15.05.1, so I’ll be using this file. Keep in mind, you’ll need enough  to download the files.

cd /tmp
wget https://downloads.openwrt.org/chaos_calmer/15.05.1/ar71xx/generic/openwrt-15.05.1-ar71xx-generic-archer-c7-v2-squashfs-sysupgrade.bin

Next, I highly recommend checking the MD5 sum to make sure the file isn’t corrupt.

cd /tmp
wget https://downloads.openwrt.org/chaos_calmer/15.05.1/ar71xx/generic/md5sums
md5sum -c md5sums 2> /dev/null | grep OK

If the MD5 sum returns OK, you can proceed with the upgrade (the -v flag tells sysupgrade to be verbose.).

sysupgrade -v /tmp/openwrt-15.05.1-ar71xx-generic-archer-c7-v2-squashfs-sysupgrade.bin

Expect the upgrade to take a few minutes. The router should reboot when completed.

Verification

Verify you can SSH into your router (assuming you chose to preserve the correct configuration files), then view the /etc/openwrt_release file to check the new version you’re running.

DISTRIB_ID='OpenWrt'
DISTRIB_RELEASE='15.05.1'
DISTRIB_REVISION='r48532'
DISTRIB_CODENAME='chaos_calmer'
DISTRIB_TARGET='ar71xx/generic'
DISTRIB_DESCRIPTION='OpenWrt Chaos Calmer 15.05.1'
DISTRIB_TAINTS=''

Now, you’ll need to re-download all your previously installed packages (this is where that backup list comes in handy).

opkg update
opkg list-upgradable
opkg install package1 package2 package3

I had to re-enable LuCI, you probably will too.

/etc/init.d/uhttpd start
/etc/init.d/uhttpd enable

In addition, you’ll need to disable any unneeded services again.

/etc/init.d/telnet stop
/etc/init.d/telnet disable

Let me know how your upgrade went!

Logan

Troubleshooting

Sleep before startup

I installed the packages, enabled the fstab, and changed my fstab config file. When I restart, the drive does NOT show up. I can issue an and I get an error that it can’t find a file () but the drive mounts. I took the advice from this posting https://forum.openwrt.org/viewtopic.php?id=27210 and put “sleep 15” in the start function of the file. (I’m using a USB stick) That fixed the problem.

Fstab does not mount partition on boot

Symptoms: You can mount your partition with , but fstab won’t mount it automatically on reboot. You are using Backfire or older version.

Solution: Despite you have installed try to install separately:

opkg update
opkg install block-hotplug

Note: This may or may not apply also to . This problem should not occur in Attitude Adjustment.

Options

Option Long Description
Query all packages not just those installed
Set verbosity level to <level>. Available verbosity levels:
0 errors only
1 normal messages (default)
2 informative messages
3 debug
4 debug level 2
Use <conf_file> as the opkg configuration file. Default is
Use a package cache
Use <dest_name> as the the root directory for package installation, removal, upgrading. <dest_name> should be a defined dest name from the configuration file, (but can also be a directory name in a pinch).
Use <dir> as the root directory for offline installation of packages.
Register architecture with given priority
Register destination with given path
Force Options
Install/remove despite failed dependencies
Overwrite preexisting config files
Reinstall package(s)
Overwrite files from other package(s)
Allow opkg to downgrade packages
Disable free space checks
Ignore checksum mismatches
Run postinstall scripts even in offline mode
No action – test only
No action – download only
Do not follow dependencies
Remove package and all dependencies
Remove packages that were installed automatically to satisfy dependencies
Specify tmp-dir.

Troubleshooting

磁盘空间耗尽

若 opkg 耗尽了存储空间,它通常会报告个 错误,表示没有干净地恢复孤悬的文件锁。可以调用 命令来删除这个文件锁。

除此之外,opkg 可能不会删除之前安装的文件。

处理此事的一种办法是获取一个之前安装的文件的列表,然后删除它们。

URL 替换为相应的包:

(cd /; \
 wget -qO- http://downloads.openwrt.org/snapshots/trunk/ar7/packages/6in4_10-1_all.ipk | \
 tar -Oxz ./data.tar.gz | tar -tz | xargs rm)

然而,上述代码并没有可靠地删除那些伴随软件包安装进去的依赖软件包。它也遗留下了那些空目录。这个脚本尝试修正这些问题:

#!/bin/sh
#takes one argument/parameter: the name of the package which didn't install correctly and should be removed along with its dependencies
#do opkg update first
#example: ./opkgremovepartlyinstalledpackage.sh pulseaudio-daemon

#get list of all packages that would be installed along with package x
opkg update
PACKAGES=`opkg --force-space --noaction install $1 | grep "http:" | cut -f 2 -d ' ' | sed 's/.$//'`
for i in $PACKAGES
do
        LIST=`wget -qO- $i | tar -Oxz ./data.tar.gz | tar -tz | sort -r | sed 's/^./\/overlay/'`
        for f in $LIST
        do
                if 
                then
                        echo "Removing file $f"
                        rm -f $f
                fi
                if 
                then
                        echo "Try to remove directory $f (will only work on empty directories)"
                        rmdir $f
                fi
        done
done
echo "You may need to reboot for the free space to become visible"

将之保存在你的 OpenWrt 设备上,命名为 ,设置为可执行 ,然后你可以这样执行它 。

Сохранение списков программных пакетов при загрузке

Сохранение статуса установленных пакетов opkg в хранящемся в extroot, а не в RAM, экономит некоторую оперативную память и сохраняет списки пакетов доступными после перезагрузки.

Через Web интерфейс

1. LuCI → System → Software → Configuration

смените

lists_dir ext varopkg-lists

на

lists_dir ext usrlibopkglists

это должно выглядеть примерно так:

dest root 
dest ram tmp
lists_dir ext usrlibopkglists
option overlay_root overlay
option check_signature

2. LuCI → System → Software → Actions → Update lists производит первоначальное обновление списка пакетов на extroot

———–Перевод и обновление статьи продолжается! ————
далее идет старая версия!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *