0

I'm working on a script that checks if a certain device is connected to the network. If it is connected the device should get a message via email. It works flawlessly on windows, however, when I run it on my raspberry pi it just doesn't work. Can someone tell my why it doesn't work and if it is possible to run this on Linux?

Here's the code:

import smtplib, subprocess, time

host = "192.168.2.10"
x = True

server = smtplib.SMTP( "smtp.gmail.com", 587 )
server.starttls()
server.login( '[email protected]', 'password' )

while True:
    try:
        response = subprocess.getoutput(['ping', host])
    except:
        print("An error occured")
    if('Destination host unreachable' in response or 'Request timed out' in response and x == True):
        print("Device isn't connected")
        x = False

    elif('Destination host unreachable' in response or 'Request timed out' in response and x == False):
        print("Device is still not connected")

    elif('Destination host unreachable' not in response and x == False):
        print("Device just connected")
        x = True
        try:
            server.sendmail( 'Raspberry Pi', '[email protected]', 'Hello! ')
        except:
            print("An error occured. Message wasn't send")
            x = False
    elif('Destination host unreachable' not in response and x == True):
        print("Device is still online")

    else:
        print('Something went wrong with the if statements.')
    time.sleep(1)

Edit: If I run it on my raspberry and print the response variable it shows just the 'ping' menu. When you write 'ping' inside a command line you'll get all the options you have with that command. I get the same result while running this script. It somehow doesn't get the second parameter of the subprocess.getoutput. Here's the screenshot from the command line

2
  • What's the failure? You can't execute this code on your Raspberry Pi, or it runs but just doesn't send the email? Commented Aug 7, 2021 at 11:23
  • The raspberry only reads the 'ping' command. If I print the response variable it shows you the same thing as when you write 'ping' in the command line of the rpi. I'll try to put that with this post! Commented Aug 7, 2021 at 11:27

1 Answer 1

1

Linux's ping runs endlessly, whereas on Windows ping sends 4 requests.
Adjust your subprocess call to stop after a specific count of pings, additionally getoutput() takes a string and not a list.

Example:

>>> host = 'google.com'
>>> "0% packet loss" in subprocess.getoutput(f"ping -c 4 {host}")
True

You should check if the error messages are identical on Windows/Linux.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.