WOL之python实现


#!/usr/bin/env python
# Wake on Lan

import socket
import struct

def wake_on_lan(mac):
""" Switches on remote computers using WOL. """
# Check mac format and try to compensate.
if len(mac) == 12:
pass
elif len(mac) == 12 + 5:
sep = mac[2]
mac = mac.replace(sep, '')
else:
raise ValueError('Incorrect MAC address format')

# Pad the synchronization stream.
data = ''.join(['FFFFFFFFFFFF', mac * 16])
send_data = ''
print data

# Split up the hex values and pack.
for i in range(0, len(data), 2):
send_data = ''.join([send_data, struct.pack('B', int(data[i: i + 2], 16))])

# Broadcast it to the LAN.
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 今天发现在某些机器上脚本能正常使用,有些机器却不行,经查发现有问题的机器都配有多个IP,那么在这种情况下,可以bind到特定网段上发包。
sock.bind(('192.168.102.250', 20000))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(send_data, ('', 7))

if __name__ == '__main__':
# Use maces with any seperators.
wake_on_lan('00:1F:16:15:53:84')
wake_on_lan('00-1F-16-15-4D-CD')
wake_on_lan('00:22:68:1B:7A:82')
wake_on_lan('00:1B:38:02:D9:F4')

你可能感兴趣的:(Python)