Python Wake On Lan
Question: I'm trying to write a script that checks if a host on my intranet is up. if
so, wait 10 seconds and test again. if it is down, send a wake on lan packet
to the host, then test again in 10 seconds. The code compiles but doesn't seem
to be working. Any help is appreciated.

    
    
    import os
    import socket
    def main():
        hostname = "10.0.0.5" 
        response = os.system("ping -c 1 " + hostname)
        if response == 0:
            print ("Host " + hostname + "is up.")
            Time.Sleep(10)
            main()
        else:        
            print("Host " + hostname + "is down.")
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.sendto('\xff'*6 + '\x00\x21\x6A\xC7\x1A\x42'*16, ('10.0.0.5', 80))
            Time.Sleep(10)
            main()
    

**Update:** I changed the if conditional to != with the 10.0.0.5 host on to
test if it's sending the packet, and it's not (confirmed with wireshark). I
don't know if it's even running my code tbh.

New Code seems to be working, only issue is that it's ignoring time.sleep and
just repeating once the ping finishes

    
    
    import os
    import socket
    import subprocess
    import time
    from time import sleep
    x = 0
    while x < 1:
            hostname = "10.0.0.5"
            output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]
    if ('unreachable' in output):
            print hostname, 'is down.'
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.sendto('\xff'*6 + '\x00\x21\x6A\xC7\x1A\x42'*16, ('10.0.0.255', 80))
            time.sleep(10)
    else:
            print hostname, 'is up.'
            time.sleep(10)
    x = x + 0
    


Answer: The indentations are off in your updated code.also, looking for 'unreachable'
in the output wouldn't be the best thing to do.what if it timed out or showed
another error ? i would use the return code instead.

Here is an updated version.make sure to preserve the indentations.

    
    
    import os
    import time
    import socket
    import subprocess
    
    hostname = "10.0.0.5"
    
    while 1:
        sp = subprocess.Popen(["ping.exe", hostname], stdout = subprocess.PIPE)
    
        sp.wait() # Wait for ping.exe to terminate.
    
        return_code = sp.returncode # Get the return code
    
        if return_code != 0:
            print hostname, 'is down.'
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            #I'm not that familiar with this part.assuming yours is correct.
            s.sendto('\xff'*6 + '\x00\x21\x6A\xC7\x1A\x42'*16, ('10.0.0.255', 80))
        else:
            print hostname, 'is up.'
    
        time.sleep(10) # Sleep for 10 seconds
    

