Python/Python 黑魔法/Python 远程开机.py

28 lines
1.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

def wake_up(request, mac='DC-4A-3E-78-3E-0A'):
MAC = mac
BROADCAST = "192.168.0.255"
if len(MAC) != 17:
raise ValueError("MAC address should be set as form 'XX-XX-XX-XX-XX-XX'")
mac_address = MAC.replace("-", '')
data = ''.join(['FFFFFFFFFFFF', mac_address * 20]) # 构造原始数据格式
send_data = b''
# 把原始数据转换为16进制字节数组
for i in range(0, len(data), 2):
send_data = b''.join([send_data, struct.pack('B', int(data[i: i + 2], 16))])
print(send_data)
# 通过socket广播出去为避免失败间隔广播三次
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.sendto(send_data, (BROADCAST, 7))
time.sleep(1)
sock.sendto(send_data, (BROADCAST, 7))
time.sleep(1)
sock.sendto(send_data, (BROADCAST, 7))
return HttpResponse()
print("Done")
except Exception as e:
return HttpResponse()
print(e)