Ubuntu: Wait for Network Link Up and Execute a Bash Command
Ubuntu: wait for network link up and execute a bash command
The event listener I suggested:
When you plug or unplug network cable, it will trigger echo ‘Change detected’, of course it could trigger just about anything.
And this will run as one off, but I take you know how to make a daemon out of it, if not it will be a good exercise to learn 🙂
Waiting for network link to be up before continuing in bash
You can check if the network interfaces’ names appear after running ifconfig -s .
Check this link for more details.
To make this test ongoing, you can do something like what @jm666 said:
Wait for Network Interface Before Executing Command
This command should wait until it can contact google or it has tried 50 times:
The for i in <1..50>loops 50 times or until a break is executed. The ping -c1 www.google.com sends 1 ping packet to google, and &> /dev/null redirects all the output to null, so nothing is outputed. && break executes break only if the previous command finished successfully, so the loop will end when ping is successful.
Linux: execute a command when network connection is restored
You can start a script after the linux box gets connected using up
(requires ifplugd to be installed )
However, there keep in mind that if you disconnect the cable (and plug in in after a while), the script also starts even though the router might not have been restarted.
alternatively , place your script in
/etc/network/if-up.d/
(make sure it is executable and restart networking after changes.)
Bash script to bring up and down an interface on loop
if ping succeeds then bring $iface up
if ping fails then bring $iface down
Hourly network device restart using Bash in Ubuntu
If you want to write a shell script to this that is up to you, but I am a big fan of reusing something that already exists.
Use cron to run your script every hour. Set it up for the root account and have it mess with the interface.
How to create a loop in bash that is waiting for a webserver to respond?
Combining the question with chepner’s answer, this worked for me:
How to wait for an open port with netcat?
You can’t set netcat to wait until some port is open, so you have to add part for waiting before next check is made. Try this:
How to wait in bash for several subprocesses to finish, and return exit code !=0 when any subprocess ends with code !=0?
wait also (optionally) takes the PID of the process to wait for, and with $! you get the PID of the last command launched in the background.
Modify the loop to store the PID of each spawned sub-process into an array, and then loop again waiting on each PID .
Waiting for network link to be up before continuing in bash [duplicate]
Is there a way to check for successful network interface link for multiple interfaces in a bash script before continuing?
1 Answer 1
You can check if the network interfaces’ names appear after running ifconfig -s .
Check this link for more details.
To make this test ongoing, you can do something like what @jm666 said:
![]()
-
The Overflow Blog
Linked
Related
Hot Network Questions
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.8.2.43556
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Настройка сетевого адаптера
![]()
Интернет — это лучшее изобретение человечества, он объединяет более 35% населения Земли, а также открывает неограниченные возможности для обучения, работы, отдыха и общения. В вашем компьютере он появляется при помощи сетевого адаптера, имеющего беспроводной(Wi-Fi) или проводной интерфейс. В этой статье я расскажу о настройке адаптера для подключения к сети.
Есть несколько типов подключения интернета:
- Телефонная линия
- DSL, кабельная сеть или электропроводка
- Мобильная связь (2G,3G,4G — LTE)
- Оптоволокно
- Спутниковый интернет
Каждый из них имеет свои специфические особенности, однако компьютер чаще всего подключается при помощи обычной витой пары — кабеля RJ-45, либо при помощи Wi-Fi соединения с роутером(который, в свою очередь, тоже работает через витую пару или USB-модем).
Настройка. Так как большинство пользователей использует Windows 7, то рассказывать я буду на ее примере.
Для этого мы переходим в Панель управления -> Сеть и Интернет -> Центр управления сетями и общим доступом, затем слева в меню выбираем Изменение параметров адаптера.
![]()
Здесь Вы можете увидеть список всех адаптеров компьютера и их статус подключения, включая Bluetooth-адаптеры, а также виртуальные адаптеры типа Hamachi.
Обычное подключение через витую пару(без роутеров, модемов)
![]()
Кабель «Витая пара» — RJ-45 — 8P8C
Тут также есть 2 варианта: Вам необходимо настроить соединение и каждый раз выполнять подключение либо Ваш провайдер поддерживает технологию DHCP и Вам просто необходимо воткнуть кабель в разьем.
В зависимости от Вашего варианта нужно правильно настроить адаптер.
Вариант 1
Заходим в список адаптеров. Выбираем нужный(Подключение по локальной сети . ) и нажимаем на нем правую клавишу мыши(ПКМ), здесь выбираем Свойства. В открывшемся списке выбираем компомнент Протокол Интернета версии 4 и нажимаем кнопку Свойства. Сюда необходимо вписать настройки, выданные Вашим оператором.
Вариант 2
Операция аналогичная Варианту 1, только в свойствах протокола необходимо установить флажки Получить IP-адрес автоматически, Получить адрес DNS-сервера автоматически.
![]()
![]()
Подключение при помощи роутера
Обычно роутер имеет 5 разьемов(4 LAN и 1 WAN). Кабель от интернета вы подключаете в WAN порт(он отделен от остальных), а затем при помощи второго кабеля/Wi-Fi адаптера соединяете роутер и компьютер. После этого (Смотрите Вариант 2 в подключении через витую пару), в адаптере Wi-Fi эти настройки стоят по-умолчанию.
Для последующей настройки интернета Вы заходите по локальному адресу роутера(192.168.0.1 или 192.168.1.1 — по-умолчанию) и выполняете необходимые действия.
Как настроить роутер Asus Вы можете прочитать в этой статье — https://idej.net/peripheral/44-kak-nastroit-router-asus.html
Остальные типы я расписывать не буду, все вопросы можете задать в комментариях.
Теперь детальнее о настройках адаптера
Чтобы увидеть эти настройки надо зайти в список адаптеров, нажать ПКМ на нужном адаптере, выбрать Свойства, затем под строкой с полным именем адаптера нажать кнопку Настроить. Здесь перейти на вкладку Дополнительно.
В основном, свойства одинаковы у всех адаптеров, однако все же есть небольшая разница.
Wait for link что это
This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.
What can I do to resolve this?
You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.
Cloudflare Ray ID: 7d7e561f5ec32494 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare
Photon Network Manager Command-line Interface (netmgr)
For locally logged-on users, Photon OS provides a command line interface to manage network configuration of the system.
Setup Steps
The netmgr tool is included with your Photon OS distribution. To make sure that you have the latest version, you can run:
Syntax
The CLI is built on set, get, add, delete command model and uses the option-name — option-value model of specifying command parameters.
Passed-in parameter values can be enclosed in single (') or double-quotes (") as long as you use matching characters to denote the beginning and end of the value. Unless a parameter value contains special characters or spaces, you can also omit quotes altogether.
network object
<network object> is one of the following values:
- link_info
- ip4_address
- ip6_address
- ip_route
- dns_servers
- dns_domains
- dhcp_duid
- if_iaid
- ntp_servers
- hostname
- wait_for_link
- wait_for_ip
- error_info
- net_info
Network Manager CLI
link_info
Get the mac address, MTU, link state, and link mode for the (optionally) specified interface.
Set the MAC address, link state (up or down), link mode (manual or auto), or MTU for the specified interface.
ip4_address
Get the IPv4 address for the specified interface.
Set the IPv4 address (dot-decimal/prefix notation), mode (dhcp, static, or none), and (optionally) the default gateway for the specified interface.
ip6_address
Get IPv6 addresses for the specified interface.
Add one or more IPv6 addresses (comma-separated list in colon-separated/prefix notation) to the specified interface.
Delete one or more IPv6 addresses (comma-separated list in colon-separated/prefix notation) from the specified interface.
Set the IPv6 DHCP mode (1=enable, 0=disable) and IPv6 auto-configuration settings (1=enable, 0=disable) for the specified interface.
ip_route
Get the static IP route for the specified interface.
Add the static IP route (gateway IP, destination network, and metric) to the specified interface.
Delete the specified static IP route from the specified interface.
dns_servers
Get the list of DNS servers.
Set the DNS mode (DHCP or static) for one or more DNS servers (comma-separated list).
Add a DNS server to the list of DNS servers.
Remove the specified DNS server from the list of DNS servers.
dns_domains
Get the list of DNS domains.
Set the list of DNS domains (one or more DNS domains in a comma-separated list).
Add a DNS domain to the list of DNS domains.
Delete a DNS domain from the list of DNS domains.
dhcp_duid
Get the DHCP DUID (optionally interface-specific DUID) for the system.
Set the DHCP DUID for the system, optionally per-interface if the interface is specified.
if_iaid
Get the IAID for the specified interface.
Set the IAID for the specified interface.
ntp_servers
Get the NTP servers list.
Set the NTP servers list.
Add the specified server to the NTP servers list.
Delete the specified server from the NTP servers list.
hostname
Get the system hostname.
Set the system hostname.
wait_for_link
Wait for the specified network interface to be up and usable (it can send and receive packets).
The timeout (in seconds) specifies the maximum time to wait. Specify 0 for no timeout (wait indefinitely).
Note: You might need to use wait_for_ip to wait until you can send and receive IP packets.
wait_for_ip
Wait for the specified interface to acquire a valid IP address for the specified address type.
The timeout (in seconds) specifies the maximum time to wait. Specify 0 for no timeout (wait indefinitely).
error_info
Get error information about the specified error code.
Here is a list of error codes:
- 4097 — invalid parameter
- 4098 — not supported
- 4099 — out of memory
- 4100 — value not found
- 4101 — value exists
- 4102 — invalid interface
- 4103 — invalid mode
- 4104 — bad configuration file
- 4105 — write failed
- 4106 — timeout
- 4107 — DCHP timeout
net_info
Get the specified network configuration parameter for the specified object.
Note: The object can be an interface name (for example, "eth0") or a file name (for example, /etc/systemd/resolved.conf).
Set the value of the specified network configuration parameter for the specified object (interface or file).
Note : You can add (+) or remove (-) a parameter by prepending the parameter name with + or -.
For example, in order to add static IPv4 address "10.10.10.1/24" to eth0 interface, the following command adds this Address to the Network section of the eth0 network configuration file.
Wait for link-up
Wait for link-up on a network interface. iPXE will open the first specified network interface and wait for a link to be detected. If a usable link is detected, the command will terminate and the network interface will be left open. If no link is detected, the network interface will be closed and iPXE will proceed to the next network interface in the list.
If no network interfaces are explicitly specified, iPXE will try all available network interfaces.
A configuration timeout can be specified (in milliseconds) using the –timeout option. If no timeout is specified, iPXE will wait indefinitely for a link to be detected.
Command status
| Success | A link was detected |
|---|---|
| Failure | No link was detected |
See also
Notes
You do not normally need to use this command. iPXE will automatically wait for the link to be detected when configuring the interface using the ifconf or dhcp or autoboot commands.
If no timeout has been specified then iPXE will wait indefinitely for a link to be detected, or until the command is cancelled using Ctrl-C .
If the command succeeds then you can use the ifname setting to retrieve the name of the successful interface. For example:
Link Type: Wait For
Note:
A Link Type specifies the condition that makes the RMC jump to and execute the next step in a User Program.
The Wait For Link Type waits for the Link Condition to become true before jumping to the next step in the User Program. If you want the User Program to wait a certain period of time, use the Delay link type instead.
The Wait For Link Type has the following boxes:
The Link Condition specifies the condition that must become true before jumping to the next step in the User Program. This condition must be a logical expression that evaluates to True or False.
To select the Wait For Link Type:
Open or create a User Program.
Go to the step where you want the Wait For Link Type.
Double-click the Link Type box.
Beginning with the loop time after the step containing the Wait For link type is executed, the RMC will monitor the Wait For link condition. In the same loop time that the condition becomes true, the program will jump to the next step and execute it. Therefore, the specified step can be executed no sooner than the next loop time after the first step was executed, and the state of the condition in the same loop time that the step is executed is not considered.
Consider a program where Step 0 issues a Move Absolute command and has a Wait For link type with a link condition that waits for a discrete input to be on. In the loop time that step 0 is executed (the Move Absolute command is issued), the link condition is not evaluated. The next loop time, the program will evaluate the link condition. If the condition is true (the discrete input is on), the program will jump to the specified step and execute it in that same loop time. If the condition is false, (the discrete input is off), the program will wait. This will repeat until the condition is true, at which point, the program will jump to the specified step and execute it in the same loop time in which the condition became true.