Python唤醒Lan

时间:2014-10-26 06:32:21

标签: python

我试图编写一个脚本来检查我的Intranet上的主机是否已启动。如果是这样,等待10秒再测试一次。如果它已关闭,则将lan数据包发送到主机,然后在10秒内再次测试。代码编译但似乎没有工作。任何帮助表示赞赏。

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()

更新:我将if条件更改为!=并打开10.0.0.5主机以测试它是否正在发送数据包,但是它没有(通过wireshark确认) )。我不知道它是否甚至运行我的代码tbh。

新代码似乎正在运作,唯一的问题是它忽略了time.sleep并且只是在ping完成后重复

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

1 个答案:

答案 0 :(得分:0)

您的更新代码中的缩进处于关闭状态。此外,还要查找“无法访问”字样。在输出中不是最好的事情。如果它超时或显示另一个错误怎么办?我会改用返回代码。

这是一个更新版本。确保保留缩进。

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
相关问题