Run script when ping to certain host is successful and failed

Thanks in advance for anyone who's willing to help!

I know there is watchcat that can execute script when ping is failed, but what about when connection is recovered? I don't seem to figure out a way to do it.

EDIT: to provide more clarification, I have a wireguard interface which is always up, I have 3 peers, 2 of them are always up and working, but connection to 1 of them is sometimes not working. I need to run my own script when that happens, and I also need to run another script when the peer is back.

You can use a hotplug script which runs if an interface comes up:
https://openwrt.org/docs/guide-user/base-system/hotplug

create your while loop and put your script in /etc/rc.local

dont forget the >/dev/null 2>&1 at the end

if you can, please elaborate what you want to achieve exactly the forum will surely be of great help as usual

also don not forget chatgpt:

question to gpt:
execute command when ping fail and another command when ping does not fail, bash?
answer:
In Bash scripting, you can use the ping command along with conditional logic (if statements) to execute different commands based on whether the ping succeeds or fails. Here's a basic structure to achieve this:

#!/bin/bash

Example target to ping

target="example.com"

Ping the target and check the exit status ($?) to determine success or failure

if ping -c 1 "$target" >/dev/null 2>&1; then
# Ping succeeded (exit status 0)
echo "Ping to $target succeeded."
# Execute command when ping succeeds
# Example command:
# command_when_ping_succeeds
else
# Ping failed (exit status non-zero)
echo "Ping to $target failed."
# Execute command when ping fails
# Example command:
# command_when_ping_fails
fi

Explanation:

  1. Ping Command: ping -c 1 "$target" is used to ping the target (example.com in this case) just once (-c 1). The output (stdout) of the ping command is redirected to /dev/null to suppress it, and 2>&1 redirects stderr to stdout so that any error messages from ping are also suppressed.
  2. Conditional Execution:
  • if ping -c 1 "$target" >/dev/null 2>&1; then: Checks if the ping command succeeds (returns exit status 0).
  • else: Executes if the ping command fails (returns a non-zero exit status).
  1. Commands to Execute:
  • Replace # command_when_ping_succeeds with the actual command you want to execute when the ping is successful.
  • Replace # command_when_ping_fails with the command to execute when the ping fails.

Example Scenario:

Let's say you want to execute echo "Network is reachable" when the ping succeeds and echo "Network is unreachable" when the ping fails, the script would look like this:

#!/bin/bash

target="example.com"

if ping -c 1 "$target" >/dev/null 2>&1; then
echo "Network is reachable."
# Command when ping succeeds
else
echo "Network is unreachable."
# Command when ping fails
fi

Replace echo "Network is reachable." and echo "Network is unreachable." with your actual commands that you want to execute based on the ping result.

This script structure allows you to dynamically respond to the success or failure of the ping command and execute different actions accordingly in a Bash script.

This seems like a bad idea for the expressed requirement, a hotplug script is the way to go.

4 Likes

further on the gpt:

can this be implement into a while loop?
Yes, you can implement the ping command within a while loop in Bash to continuously monitor the status of a network connection, and execute different commands based on whether the ping succeeds or fails. Here’s how you can structure it:

#!/bin/bash

target="example.com"

while true; do
if ping -c 1 "$target" >/dev/null 2>&1; then
echo "Network is reachable."
# Command when ping succeeds
else
echo "Network is unreachable."
# Command when ping fails
fi

# Optional: Add a sleep interval to control how often to ping (e.g., every 5 seconds)
sleep 5

done

or at specific interval via cron also might do the job, depend what you exactly want to do

Thanks for the suggestion. Unfortunately it is not about interface, the interface is always up but the connection is not necessarily up.

on openwrt using hotplug?

On OpenWRT, you can leverage the hotplug mechanism along with shell scripting to monitor network connectivity using ping and execute commands based on the results. Here’s how you can implement it:

  1. Create a Script: Create a shell script that will continuously monitor the network status using ping within a whileloop.
  2. Use Hotplug: OpenWRT uses hotplug to trigger events when certain hardware or network events occur. You can use hotplug to execute your monitoring script whenever a network interface changes state (up or down).

Here's an example script (monitor_network.sh) that you can place in your OpenWRT device:

#!/bin/sh

Define your target to ping (example.com or IP address)

target="example.com"

while true; do
if ping -c 1 "$target" >/dev/null 2>&1; then
echo "Network is reachable."
# Command when ping succeeds
# Example: Restart a service or take specific action
# /etc/init.d/service_name restart
else
echo "Network is unreachable."
# Command when ping fails
# Example: Log the event or restart a different service
# logger "Network is unreachable"
fi

sleep 5  # Adjust sleep interval as needed

done

  • Make the Script Executable: Ensure your script (monitor_network.sh) is executable. You can do this with the command chmod +x monitor_network.sh.
  • Integrate with Hotplug: OpenWRT’s hotplug system can trigger events when network interfaces change state. To execute your script (monitor_network.sh) on such events, you typically add it to the appropriate hotplug directory or script.
  • Create a file (e.g., /etc/hotplug.d/iface/99-monitor-network) and add the following content:

#!/bin/sh

case "$ACTION" in
ifup)
# Execute your monitoring script when a network interface goes up
/path/to/your/monitor_network.sh &
;;
ifdown)
# Optional: Handle actions when a network interface goes down
;;
esac

    • Replace /path/to/your/monitor_network.sh with the actual path where monitor_network.sh script is located.
  • Set Permissions: Make sure the hotplug script (99-monitor-network in this example) is executable: chmod +x /etc/hotplug.d/iface/99-monitor-network.
  • Restart Hotplug: After creating or modifying any hotplug scripts, you may need to restart the hotplug service to apply changes:

/etc/init.d/hotplug restart

Notes:

  • Security: Ensure that any commands executed from your script (monitor_network.sh) have appropriate permissions and do not pose security risks.
  • Logging: Consider using system logging (logger) to record events or errors for easier troubleshooting and monitoring.
  • Testing: Test your script and hotplug integration to ensure it behaves as expected in response to network connectivity changes.

By following these steps, you can effectively monitor network connectivity on your OpenWRT device using ping and respond to network status changes using shell scripting and the hotplug mechanism.

To provide more clarification, I have a wireguard interface which is always up, I have 3 peers, 2 of them are always up and working, but connection to 1 of them is sometimes not working. I need to run my own script when that happens, and I also need to run another script when the peer is back.

Is there a proper place for that in hotplug.d? I don't seem to find it.

I appreciate the help, but long chatgpt code block might irritate some other people...

I actually am working on a script similar to what you suggested, but I have a gut feeling that it is not the right way to do it.

sincerely sorry if it irritates, just helping.

a proper working solution can be by various different methods.
you have 2 options above from an AI which will work.

@ZOzo stop posting Chatgpt crap

2 Likes

Again thanks for the help, I really appreciate it.

There might be multiple ways to achieve what I want, but some of them feels like hack more than proper solution, that's what I am getting at here. I am not a coder, just a hobbyist, so I have no real idea what to look for and what to avoid when implementing a solution, which is why I am seeking some advice.

My suggestion would have been the hotplug upon your first post, but after the elaboration reply i would suggest you bash scripting and the rc.local way.

some more experienced users might suggest more adequate solution.

Lets see your config (will be tomorrow I will have a look), also state which peer is the problem.

Please connect to your OpenWRT device using ssh and copy the output of the following commands and post it here using the "Preformatted text </> " button:

Remember to redact keys, passwords, MAC addresses and any public IP addresses you may have:

ubus call system board
cat /etc/config/network
cat /etc/config/dhcp
cat /etc/config/firewall
ip route show
wg show

Some example scripts which can give you some inspiration:

{
        "kernel": "5.15.150",
        "hostname": "OpenWrt",
        "system": "12th Gen Intel(R) Core(TM) i3-12100",
        "model": "QEMU Standard PC (i440FX + PIIX, 1996)",
        "board_name": "qemu-standard-pc-i440fx-piix-1996",
        "rootfs_type": "ext4",
        "release": {
                "distribution": "OpenWrt",
                "version": "23.05.3",
                "revision": "r23809-234f1a2efa",
                "target": "x86/64",
                "description": "OpenWrt 23.05.3 r23809-234f1a2efa"
        }
}
config interface 'loopback'
        option device 'lo'
        option proto 'static'
        option ipaddr '127.0.0.1'
        option netmask '255.0.0.0'

config globals 'globals'
        option ula_prefix 'fd3c:******'

config device
        option name 'br-lan'
        option type 'bridge'
        list ports 'eth0'
        list ports 'eth4'
        list ports 'eth5'
        list ports 'eth6'

config interface 'lan'
        option device 'br-lan'
        option proto 'static'
        option ipaddr '192.168.17.1'
        option netmask '255.255.255.0'
        option ip6assign '64'
        option delegate '0'

config interface 'wan'
        option device 'eth3'
        option proto 'dhcp'
        option peerdns '0'
        list dns '127.0.0.1'

config interface 'wan6'
        option device 'eth3'
        option proto 'dhcpv6'
        option reqaddress 'try'
        option reqprefix 'auto'
        option peerdns '0'
        list dns '::1'

config interface 'wireguard'
        option proto 'wireguard'
        option private_key '*****'
        option listen_port '12346'
        list addresses '192.168.13.6'
        option delegate '0'

config wireguard_wireguard
        option description 'Kaide' (This one is sometimes not working for a reason I know)
        option public_key '****'
        list allowed_ips '0.0.0.0/0'

config wireguard_wireguard
        option description 'Cellphone'
        option public_key '***'
        option private_key '****'
        list allowed_ips '192.168.13.7'

config wireguard_wireguard
        option description 'PC'
        option public_key '****'
        option private_key '****'
        list allowed_ips '192.168.13.8'

config wireguard_wireguard
        option description 'MT1300'
        option public_key '******'
        option private_key '*****'
        list allowed_ips '192.168.13.9'
        list allowed_ips '192.168.25.0/24'

config device
        option type 'bridge'
        option name 'guest'
        list ports 'eth1'
        list ports 'eth5.1'

config interface 'guest'
        option proto 'static'
        option device 'guest'
        option ipaddr '192.168.18.1'
        option netmask '255.255.255.0'
        option delegate '0'
config dnsmasq
        option domainneeded '1'
        option localise_queries '1'
        option rebind_protection '1'
        option rebind_localhost '1'
        option local '/lan/'
        option domain 'lan'
        option expandhosts '1'
        option cachesize '1000'
        option authoritative '1'
        option readethers '1'
        option leasefile '/tmp/dhcp.leases'
        option resolvfile '/tmp/resolv.conf.d/resolv.conf.auto'
        option localservice '1'
        option ednspacket_max '1232'
        option dnsforwardmax '500'
        list server '127.0.0.1#12345'

config dhcp 'lan'
        option interface 'lan'
        option start '100'
        option limit '150'
        option leasetime '12h'
        option dhcpv4 'server'
        option ra 'server'
        option dhcpv6 'server'

config dhcp 'wan'
        option interface 'wan'
        option ignore '1'

config odhcpd 'odhcpd'
        option maindhcp '0'
        option leasefile '/tmp/hosts/odhcpd'
        option leasetrigger '/usr/sbin/odhcpd-update'
        option loglevel '4'

config dhcp 'guest'
        option interface 'guest'
        option start '100'
        option limit '150'
        option leasetime '12h'
config defaults
        option input 'REJECT'
        option output 'ACCEPT'
        option forward 'REJECT'
        option synflood_protect '1'

config zone
        option name 'lan'
        option input 'ACCEPT'
        option output 'ACCEPT'
        option forward 'ACCEPT'
        list network 'lan'
        list network 'wireguard'

config zone
        option name 'wan'
        option input 'REJECT'
        option output 'ACCEPT'
        option forward 'REJECT'
        option masq '1'
        option mtu_fix '1'
        list network 'wan'
        list network 'wan6'

config forwarding
        option src 'lan'
        option dest 'wan'

config rule
        option name 'Allow-DHCP-Renew'
        option src 'wan'
        option proto 'udp'
        option dest_port '68'
        option target 'ACCEPT'
        option family 'ipv4'

config rule
        option name 'Allow-Ping'
        option src 'wan'
        option proto 'icmp'
        option icmp_type 'echo-request'
        option family 'ipv4'
        option target 'ACCEPT'

config rule
        option name 'Allow-IGMP'
        option src 'wan'
        option proto 'igmp'
        option family 'ipv4'
        option target 'ACCEPT'

config rule
        option name 'Allow-DHCPv6'
        option src 'wan'
        option proto 'udp'
        option dest_port '546'
        option family 'ipv6'
        option target 'ACCEPT'

config rule
        option name 'Allow-MLD'
        option src 'wan'
        option proto 'icmp'
        option src_ip 'fe80::/10'
        list icmp_type '130/0'
        list icmp_type '131/0'
        list icmp_type '132/0'
        list icmp_type '143/0'
        option family 'ipv6'
        option target 'ACCEPT'

config rule
        option name 'Allow-ICMPv6-Input'
        option src 'wan'
        option proto 'icmp'
        list icmp_type 'echo-request'
        list icmp_type 'echo-reply'
        list icmp_type 'destination-unreachable'
        list icmp_type 'packet-too-big'
        list icmp_type 'time-exceeded'
        list icmp_type 'bad-header'
        list icmp_type 'unknown-header-type'
        list icmp_type 'router-solicitation'
        list icmp_type 'neighbour-solicitation'
        list icmp_type 'router-advertisement'
        list icmp_type 'neighbour-advertisement'
        option limit '1000/sec'
        option family 'ipv6'
        option target 'ACCEPT'

config rule
        option name 'Allow-ICMPv6-Forward'
        option src 'wan'
        option dest '*'
        option proto 'icmp'
        list icmp_type 'echo-request'
        list icmp_type 'echo-reply'
        list icmp_type 'destination-unreachable'
        list icmp_type 'packet-too-big'
        list icmp_type 'time-exceeded'
        list icmp_type 'bad-header'
        list icmp_type 'unknown-header-type'
        option limit '1000/sec'
        option family 'ipv6'
        option target 'ACCEPT'

config rule
        option name 'Allow-IPSec-ESP'
        option src 'wan'
        option dest 'lan'
        option proto 'esp'
        option target 'ACCEPT'

config rule
        option name 'Allow-ISAKMP'
        option src 'wan'
        option dest 'lan'
        option dest_port '500'
        option proto 'udp'
        option target 'ACCEPT'

config rule
        option name 'Allow Guest DNS'
        option src 'guest'
        option dest_port '53'
        option target 'ACCEPT'

config rule
        option name 'Allow Guest DHCP'
        list proto 'udp'
        option src 'guest'
        option dest_port '67-68'
        option target 'ACCEPT'

config redirect
        option dest 'lan'
        option target 'DNAT'
        option name 'Force DNS'
        option src 'lan'
        option src_dport '53'
        option dest_port '53'
        option family 'any'

config redirect
        option dest 'guest'
        option target 'DNAT'
        option name 'Force Guest DNS'
        option src 'guest'
        option src_dport '53'
        option dest_port '53'
        option family 'any'

config rule
        option name 'wireguard'
        list proto 'udp'
        option src 'wan'
        option dest_port '12346'
        option target 'ACCEPT'

config include 'pbr'
        option fw4_compatible '1'
        option type 'script'
        option path '/usr/share/pbr/firewall.include'

config zone
        option name 'guest'
        option input 'REJECT'
        option output 'ACCEPT'
        option forward 'REJECT'
        list network 'guest'

config forwarding
        option src 'guest'
        option dest 'wan'

config forwarding
        option src 'lan'
        option dest 'guest'
default via [my ipv4 gateway] dev eth3 proto static src [my ipv4 address]
[my ipv4 gateway] dev eth3 proto kernel scope link src [my ipv4 address]
192.168.17.0/24 dev br-lan proto kernel scope link src 192.168.17.1
192.168.18.0/24 dev guest proto kernel scope link src 192.168.18.1
interface: wireguard
  public key: ******
  private key: (hidden)
  listening port: 12346

peer: [This one is sometimes not working because of a reason I know]
  endpoint: *****
  allowed ips: 0.0.0.0/0
  latest handshake: 1 minute, 32 seconds ago
  transfer: 531.66 MiB received, 60.34 MiB sent

peer: *****
  allowed ips: 192.168.13.7/32

peer: *****
  allowed ips: 192.168.13.8/32

peer: *****
  allowed ips: 192.168.13.9/32, 192.168.25.0/24

Did not know this was a WG IF, IIRC no event here, but presumably:
/usr/bin/wireguard-watchdog
is what to use?

Edit: might be of use

1 Like

I am already using that, IIRC, that one will restart wireguard interface (or re resolve endpoint IP?) when peer DDNS ip changes. I need to double check if it does anything else.

can you provide a schematics of the whole setup with all the devices, if behind NAT, types of nat, cg-nat, cellular connection, etc.

what resources you have access to, approx loads of data going between the various connection points, VPS avail, domain avail and service provider.

Describe exact issue as clearly as possible.

your solution might already be there scattered within the forum