Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use a boolean in a For Loop

I have a Script that sends a Notification to my Phone using ntfy.

It pings a Device and if the Ping responds with an Error, it sends a Notification to my Phone.

for ip in ap_ips:
    try:
        ping3.ping(ip)
        requests.post(ntfy_adress,
                      data=("Das Gerät mit der IP-Adresse " + ip + " ist online.").encode(
                          encoding='utf-8'),
                      headers={
                          "Title": ("Unifi AP ist Online!"),
                      })
    except:
        requests.post(ntfy_adress,
                      data=("Das Gerät mit der IP-Adresse " + ip + " ist nicht mehr erreichbar.").encode(encoding='utf-8'),
                      headers={
                          "Title": ("Unifi AP ist Offline!"),
                          "Tags": "warning"
                      })

The Script is supposed to be running in a infinite Loop.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How do i get the Script to only send a Notification if the Ping Result is diffrent than before?

>Solution :

You have to store between two executions the status. Before your while loop do something like:

status = {}

And then, check that the previous status is not the current one

for ip in ap_ips:
    try:
        ping3.ping(ip)

        if status.get(ip) != "OK":
            requests.post(
                ntfy_adress,
                data=("Das Gerät mit der IP-Adresse " + ip + " ist online.").encode(
                    encoding="utf-8"
                ),
                headers={
                    "Title": ("Unifi AP ist Online!"),
                },
            )
        status[ip] = "OK"

    except:  # You should set explicitly which error type you expect here if ping fails.
        if status.get(ip) != "KO":
            requests.post(
                ntfy_adress,
                data=(
                    "Das Gerät mit der IP-Adresse " + ip + " ist nicht mehr erreichbar."
                ).encode(encoding="utf-8"),
                headers={"Title": ("Unifi AP ist Offline!"), "Tags": "warning"},
            )
        status[ip] = "KO"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading