Wirenboard6:InstallingOnTheRemoteSite/en: различия между версиями

Нет описания правки
(Новая страница: «To ensure that the controller does not stop trying to communicate when the connection is lost, the options in the provider settings file <code>/etc/ppp/peers/</co…»)
 
(не показана 51 промежуточная версия этого же участника)
Строка 151: Строка 151:




== PPP — основной и резервный выход в интернет ==
== PPP is for a primary and backup Internet access ==


Проще всего обеспечить выход в интернет, если ppp0 — единственный WAN-интерфейс. Интерфейс ppp0 настраивается, как это написано выше, и затем, командой <code>ifup ppp0</code>, устанавливается подключение к интернету через сеть сотового оператора.  
The easiest way to provide access to the Internet, if ppp0 — the only WAN-interface. The ppp0 interface is configured as described above, and then, with the <code>ifup ppp0</code> command, an Internet connection is established through the network of the cellular operator.  


Сложности начинаются, когда контроллер подключен к Ethernet и имеет шлюз по умолчанию в одной сети, а также подключается к сети сотовой передачи данных.  
Difficulties begin when the controller is connected to Ethernet and has a default gateway in one network, and also connects to a cellular data network.  


В такой конфигурации мы сталкиваемся со следующей особенностью: протокол PPP обеспечивает соединение точка-точка и не предполагает шлюза по умолчанию.  
In this configuration, we are faced with the following feature: the PPP Protocol provides a point-to-point connection and does not assume a default gateway.  


В случае подключения по PPP, когда ни одного шлюза по умолчанию нет (например, мы не подключили Ethernet-кабель), pppd в качестве шлюза по умолчанию добавит в таблицу маршрутизации в системе IP-адрес ppp-партнера. Если шлюз по умолчанию уже задан, то в таблицу маршрутизации новый шлюз по умолчанию не добавляется. И тогда при падении основного Ethernet-канала выход в интернет теряется, несмотря на активное соединение. В этом случае необходимо добавить второй шлюз по умолчанию через интерфейс ppp0. Метрика любого нового шлюза должна отличаться от метрик имеющихся, поэтому мы явно указываем метрику при создании нового шлюза по умолчанию.  
In the case of a PPP connection where there is no default gateway (for example, we have not connected an Ethernet cable), pppd will add the IP address of the ppp partner as the default gateway to the routing table in the system. If a default gateway is already specified, a new default gateway is not added to the routing table. And then when the main Ethernet channel falls, the Internet connection is lost, despite the active connection. In this case, you must add a second default gateway through the ppp0 interface. The metric of any new gateway must be different from the metrics available, so we explicitly specify the metric when creating a new default gateway.  


Для обеспечения отказоустойчивого соединения мы должны предусмотреть любой порядок поднятия и падения интерфейсов. Задача — обеспечить связь независимо от порядка поднятия интерфейсов и переключение при падении одного из них.  
To ensure failover of connections we need to provide for any procedure for raising and fall of the interfaces. The task is to provide communication regardless of the order of raising the interfaces and switching when one of them crushes.  


Для интерфейса eth0, который мы будем считать основным для выхода в интернет, создается шлюз по умолчанию с метрикой 0 в таблице маршрутизации. Зададим для шлюза по умолчанию через интерфейс ppp0 метрику 100 (или любой, отличной от 0).
The default gateway with metric 0 in the routing table is created for the eth0 interface, which we will consider to be the primary interface for Internet access. Set the default gateway via the ppp0 interface to 100 metric (or any metric other than 0).
Для выполнения команд после инициализации любого ppp-интерфейса pppd демон использует директорию <code>/etc/ppp/ip-up.d</code>. В качестве параметров командной строки скрипту передается и имя ppp-интерфейса (в нашем случае такой интерфейс один это ppp0).
The daemon uses the <code>/etc/ppp/ip-up directory to execute commands after any ppp interface is initialized.d</code>. The name of the ppp interface is also passed to the script as command-line parameters (in our case, there is only one such interface — ppp0).


Создадим скрипт add_routes в директории <code>/etc/ppp/ip-up.d</code> и сделаем его исполняемым (<code>chmod +x /etc/ppp/ip-up.d/add_routes</code>):
Create the add_routes script in the <code>/etc/ppp/ip-up directory.d</code> and make it executable (<code>chmod +x /etc/ppp/ip-up.d/add_routes</code>):
<pre>
<pre>
#!/bin/sh
#!/bin/sh
Строка 173: Строка 173:
route add default dev ppp0 metric 100 2>/dev/null
route add default dev ppp0 metric 100 2>/dev/null
</pre>
</pre>
Первая команда удаляет шлюз по умолчанию, на случай, если он был создан с метрикой 0. Вторая — добавляет шлюз по умолчанию с метрикой 100 для интерфейса ppp0.
The first command removes the default gateway, in case it was created with metric 0. The second adds a default gateway with a metric of 100 for the ppp0 interface.
Таким образом мы имеем два шлюза по умолчанию с разными метриками:
Therefore, we have two default gateways with different metrics:


[[Special:MyLanguage/Файл:Two_def_gateways.png|||| ]]
[[Special:MyLanguage/Файл:Two_def_gateways.png|||| ]]


При падении одного из их трафик будет передаваться через другой и наоборот.
If one of them falls, the traffic will be transmitted through the other and Vice versa.
Запустим ping 8.8.8.8, а затем  вынем и вставим вилку RJ-45:  
Start ping 8.8.8.8 and then remove and insert the RJ-45 plug:  


[[Special:MyLanguage/Файл:Channel_switch.png|||| ]]
[[Special:MyLanguage/Файл:Channel_switch.png|||| ]]


Как показал опыт, иногда возникает проблема с доступностью DNS-серверов провайдера. Для всех соединений прописываем общедоступные сервера Google и OpenDNS.
Sometimes there is a problem with the availability of provider DNS servers. For all connections prescribe public servers from Google and OpenDNS.


'''eth0:''' Из файла <code>/etc/dhcp/dhclient.conf</code> из параметра request удаляем параметр <code>domain-name-servers</code>, а после параметра request указываем открытые DNS-сервера Google и OpenDNS:  
"'eth0:"' From <code>/etc/dhcp/dhclient.conf</code> remove the <code>domain-name-servers</code> parameter from the request parameter, and after the request parameter specify the open DNS servers Google and OpenDNS:  
<pre>prepend domain-name-servers 8.8.4.4, 8.8.8.8, 208.67.222.222, 208.67.220.220;</pre>
<pre>prepend domain-name-servers 8.8.4.4, 8.8.8.8, 208.67.222.222, 208.67.220.220;</pre>


'''ppp0:''' В директории <code>/etc/ppp/ip-up.d</code> создаем скрипт (и даем ему права на выполнение), который добавит DNS-сервера Google и OpenDNS в файл <code>resolv.conf</code> при поднятии интерфейса.
"'ppp0:"' In the <code>/etc/ppp/ip-up directory.d</code> create a script (and give it execute permissions) that will add Google DNS servers and OpenDNS to the <code>resolv file.conf</code> when the interface is up.


<pre>
<pre>
Строка 207: Строка 207:
== VPN ==
== VPN ==


Для удаленного доступа к контроллеру будем использовать OpenVPN. Предполагается, что сервер уже есть и настроен, необходимо установить и настроить клиент на контроллере.  
For remote access to the controller we will use OpenVPN. It is assumed that the server is already present and configured, you must install and configure the client on the controller.  


Чтобы обеспечить большую надежность, на сервере с 2 IP-адресами запускается два серверных процесса, один из которых слушает на порту 1194 TCP на IP1, а второй  — на порту 1194 UDP на IP2. (Это не обязательно, вы можете использовать один серверный процесс).
To ensure greater reliability, two server processes are started on a server with 2 IP addresses, one of which listens on port 1194 TCP on IP1 and the other - on port 1194 UDP on IP2. (This is optional, you can use a single server process).


На контроллере мы поднимаем 2 OpenVPN-клиента и явно задаем маршрут для IP2 через интерфейс <code>ppp0</code> для одного из них.  
On the controller, we enable 2 OpenVPN clients and explicitly set the route for IP2 via the <code>ppp0</code> interface for one of them.  


Установка OpenVPN — стандартная, с использованием <code>open-rsa</code>.
OpenVPN installation is standard, using <code>open-rsa</code>.


Для этого на контроллере устанавливаем <code>openvpn</code> и <code>easy-rsa</code>:
To do this, install <code>openvpn</code> and <code>easy-rsa</code>on the controller:


<pre>apt-get install openvpn easy-rsa</pre>
<pre>apt-get install openvpn easy-rsa</pre>


Копируем
Copy
<pre>cp -R /usr/share/easy-rsa /etc/openvpn/</pre>
<pre>cp -R /usr/share/easy-rsa /etc/openvpn/</pre>


Копируем сертификат удостоверяющего центра <code>ca.crt</code> на контроллер в директорию <code>/etc/openvpn/easy-rsa/keys</code>
Copy the CA certificate <code>ca.crt</code> to the controller in <code>/etc/openvpn/easy-rsa/keys</code> folder


В директории
In the folder
<code>/etc/openvpn/easy-rsa</code>
<code>/etc/openvpn/easy-rsa</code>
создаем поддиректорию <code>keys</code>:
create a subfolder <code>keys</code>:
   
   
<pre>mkdir keys && chmod 600 keys && cd keys</pre>
<pre>mkdir keys && chmod 600 keys && cd keys</pre>


Создаем запрос на подписывание сертификата (с именем, соответствующим серийному номеру контроллера, в данном случае A7ZO7UCC):
Create a certificate signing request (with the name corresponding to the serial number of the controller, in this case that's A7ZO7UCC):
<pre>
<pre>
cd /etc/openvpn/easy-rsa/
cd /etc/openvpn/easy-rsa/
Строка 237: Строка 237:
./build-req A7ZO7UCC
./build-req A7ZO7UCC
</pre>
</pre>
Копируем полученный запрос <code>A7ZO7UCC.csr</code> на сервер в произвольную директорию и подписываем его.   
Copy the received request <code>A7ZO7UCC.csr</code> to the server in an arbitrary directory and sign it.   
<pre>
<pre>
cd /etc/openvpn/easy-rsa
cd /etc/openvpn/easy-rsa
Строка 243: Строка 243:
./sign-req /root/certs/A7ZO7UCC
./sign-req /root/certs/A7ZO7UCC
</pre>
</pre>
Подписанный сертификат <code>A7ZO7UCC.crt</code> копируем на контроллер в директорию <code>/etc/openvpn/easy-rsa/keys</code>.
Signed <code>A7ZO7UCC certificate.crt</code> copy to the controller in the directory <code>/etc/openvpn/easy-rsa/keys</code>.


На сервере в конфигурационном файле (<code>/etc/vpn/server.conf</code>) смотрим, какой файл соответствия клиент-адрес указан в параметре <code>ifconfig-pool-persists</code> и в этот файл добавляем адрес для клиента-контроллера из диапазона сетевых адресов, описанного в параметре <code>server</code> конфигурационного файла.
On the server in the configuration file (<code>/etc/vpn/server.conf</code>) see which client-address match file is specified in the <code>ifconfig-pool-persist < /code> parameter and add the address for the client-controller from the network address range described in the <code>server</code> parameter of the configuration file to this file.


Например,  
For example,  
<pre>
<pre>
service openvpn stop
service openvpn stop
mcedit /etc/openvpn/ipp.txt
mcedit /etc/openvpn/ipp.txt
</pre>
</pre>
Добавляем строку <code>A7ZO7UCC,10.8.0.48</code>
Add the line <code>A7ZO7UCC,10.8.0.48</code>
<pre>service openvpn start</pre>
<pre>service openvpn start</pre>




Для второго экземпляра сервера такую же операцию выполняем с его конфигурационными файлами, IP-адреса должны различаться, например, добавляем запись
For the second server instance, we perform the same operation with its configuration files, the IP addresses should be different, for example, add an entry
<code>A7ZO7UCC,10.9.0.48</code>
<code>A7ZO7UCC,10.9.0.48</code>




Конфигурационные файлы для клиента на контроллере для двух соединений будем хранить в файлах <code>/etc/openvpn/client.conf</code> и <code>/etc/openvpn/client1.conf</code>.
The configuration files for the client on the controller for the two connections will be stored in the <code>/etc/openvpn/client files.conf</code> and <code>/etc/openvpn/client1.conf</code>.


Содержимое файла настройки клиента:
Contents of the client configuration file:
<pre>
<pre>
client
client
Строка 279: Строка 279:
link-mtu 1542
link-mtu 1542
keysize 128
keysize 128
#keysize 128 -- для совместимости с имеющимися клиентами
#keysize 128 - for compatibility with existing clients
</pre>
</pre>


В файле конфигурации второго vpn-подключения <code>сlient1.conf</code> замените <code>proto udp</code> на <code>proto tcp</code> и укажите второй IP-адрес сервера в параметре <code>remote</code>.  
In the configuration file of the second vpn connection, <code>CLIENT1.conf</code> replace <code>proto udp</code> with <code>proto tcp</code> and specify the second IP address of the server in the <code>remote</code>parameter.  


Автозагрузка сервиса OpenVPN на контроллере включается командой:
Startup of the OpenVPN service on the controller is enabled by the command:
<pre>update-rc.d openvpn defaults</pre>
<pre>update-rc.d openvpn defaults</pre>
   
   
Проверяем доступность сервера
Check server availability
<code>ping 10.8.0.1</code>
<code>ping 10.8.0.1</code>


Строка 293: Строка 293:
== AutoSSH ==
== AutoSSH ==


Еще одно резервное подключение к контроллеру сделаем на основе <code>AutoSSH</code>. Механизм работы таков: с контроллера устанавливается ssh-соединение к серверу, при этом ssh-порт контроллера пробрасывается на один из свободных портов на localhost сервера. Сервис аutossh следит за тем, что ssh-соединение не разорвано, и в случае разрыва восстанавливает его. Восстановление происходит не мгновенно какое-то время порт, используемый на <code>localhost</code> сервера удерживается демоном <code>sshd</code>.  
Another fallback controller connection will be based on the <code>AutoSSH</code>. The mechanism of work is as follows: SSH-connection from the controller to the server is established, and the ssh-port of the controller is forwarded to one of the free ports on the localhost server. Service аutossh ensures that the ssh connection is not broken, and in case of the gap restores it. Recovery is not instantaneous for a while, the port used on the server's <code>localhost</code> is held by the <code>sshd</code>daemon.  


Устанавливаем на контроллере <code>apt-get install autossh</code>. Генерируем пару ключей для пользователя <code>root</code>:
Install on the controller <code>apt-get install autossh</code>. Generate a key pair for the user <code>root</code>:
<pre>ssh-keygen </pre>
<pre>ssh-keygen </pre>
Пароль — пустой.
Password is empty.


Для обслуживания удаленных подключений создаем пользователя <code>remote</code> на сервере с оболочкой <code>/bin/false</code>:  
To maintain remote connections, create a user <code>remote</code> on the server with the shell <code>/bin/false</code>:  


<pre>adduser --home /home/remote --shell /bin/false remote </pre>
<заранее>команду adduser --Home /для дома/дистанционный --оболочку /bin/false в удаленных и </pre>


В файл <code>/home/remote/.ssh/authorized_keys</code> на сервере добавляем созданный на контроллере ключ <code>/root/.ssh/id_rsa.pub</code> с преамбулой
Here, in file <code>/home/remote/.ssh/authorized_keys</code> on the server, we add key created on the controller <code>/root/.ssh/id_rsa.pub</code> with the preamble


<code>no-agent-forwarding,no-X11-forwarding,permitopen="localhost:62001" </code>
<code>no-agent-forwarding,no-X11-forwarding,permitopen="localhost:62001" </code>


что обеспечит дополнительную безопасность сервера при подключении контроллера. Порт 62001 — порт localhost-сервера, на который будет перенаправлен ssh-порт данного контроллера.  
this will provide additional security for the server when the controller is connected. Port 62001 is the port of the localhost server to which the ssh port of this controller will be redirected.  


Первый раз подключаемся с контроллера на сервер вручную:
The first time we connect from the controller to the server manually:
<pre>ssh remote@vpn.mydomain.com </pre>
<pre>ssh remote@vpn.mydomain.com </pre>


На контроллере создаем файл <code>\etc\systemd\system\autossh.service</code> для запуска <code>autossh</code> в качестве сервиса:
On the controller, create a file <code>\etc\systemd\system\autossh.service</code> to run it <code>autossh</code> as a service:




Строка 335: Строка 335:
WantedBy=multi-user.target
WantedBy=multi-user.target
</pre>
</pre>
Включаем сервис а автозагрузку на контроллере:
Add service to autorun on the controller
<pre>systemctl enable autossh.service</pre>
<pre>systemctl enable autossh.service</pre>


После запуска сервиса мы можем подключиться к контроллеру на сервере с помощью команды
After starting the service, we can connect to the controller on the server using the command
<pre>ssh 127.0.0.1 -p 62001</pre>
<pre>ssh 127.0.0.1 -p 62001</pre>




== Передача данных  с контроллера в облако ==
== Data transfer from controller to the cloud ==


Для передачи MQTT-сообщений с контроллера в облачный сервис используется MQTT-бридж, конфигурация которого настраивается на контроллере в файле <code>\mnt\data\etc\mosquitto\conf.d\bridge.conf</code>
To send MQTT messages from the controller to the cloud service, the MQTT bridge is used, the configuration of which is configured on the controller in the file <code>\mnt\data\etc\mosquito\conf.d\bridge.conf</code>
<pre>
<pre>
connection wb_devices_cloud.wb_A7ZO7UCC
connection wb_devices_cloud.wb_A7ZO7UCC
Строка 359: Строка 359:
</pre>
</pre>


Затем выполните команду
Then run the command


<pre>
<pre>
Строка 366: Строка 366:




Если вы хотите передавать данные на несколько серверов одновременно, создайте несколько разделов <code>connection</code>.
If you want to transfer data to multiple servers at the same time, create multiple <code>connection</code>partitions.




== Возможные неполадки GPRS-соединения ==
== Possible GPRS connection problems ==


Возможных причин отсутствия GPRS-подключения может быть несколько.  
There can be several possible reasons for the lack of GPRS connection.  
* Закончился оплаченный лимит трафика.  
* The paid traffic limit has ended.  
* Низкий уровень сигнала, плохой контакт антенны.  
* Low voltage, poor contact to the antenna.  
* СИМ-карты некоторых операторов рассчитаны только на 4G-сети, 3G-подключение установить с ними не получится.  
* SIM cards of some operators are designed only for 4G-network, 3G-connection to install them will not work.  
* Проверьте, правильно ли вставлена СИМ-карта в слот.  
* Check if the SIM card is inserted correctly into the slot.  
* Возможно, СИМ-карта нерабочая.  
* The SIM card may not be working.  
* Ваш тарифный план не предусматривает пакетную передачу данных.  
* Your data plan does not include packet data.  


Прежде чем идти в личный кабинет и звонить провайдеру, можно выполнить ряд простых проверок.
Before you go to your personal account and call the provider, you can perform a number of simple checks.




Запустите команду
Run the command


<pre>gammu networkinfo</pre>
<pre>gammu networkinfo</pre>
Строка 396: Строка 396:
</pre>
</pre>


Важно, что контроллер подключен к пакетной сети передачи данных <pre>(GPRS                 : attached)</pre> и GPRS-соединение установлено.  
It is important that the controller is connected to the packet data network <pre>(GPRS : attached)</pre> and GPRS connection is established.  


После этого оцените уровень сигнала в minicom командой <code>AT+CSQ</code>
Then evaluate the signal strength in minicom with <code>AT+CSQ</code>
Вы получите результат в виде <code>13,99</code>
You will get the result as <code>13.99</code>


Первая цифра показывает мощность сигнала: > 9 — удовлетворительный, > 14 — хороший, > 19 — отличный. Низкие и нестабильные значения CSQ означают, что антенна плохо расположена, неаккуратно подключена, радиообстановка неблагоприятная.
The first digit shows the signal strength: > 9 — satisfactory, > 14 — good, > 19 — excellent. Low and unstable CSQ values mean that the antenna is poorly positioned, carelessly connected, radio placement is unfavorable.


Если обе проверки пройдены, но связи нет, обратитесь к провайдеру (загляните в личный кабинет), можете проверить СИМ-карту в смартфоне.
If both checks are passed, but there is no connection, contact your provider (check in your personal account), you can check the SIM card in your smartphone.
12 063

правки