import socket
import time
import struct
# wake on lan
def wake_up(mac, broadcast="255.255.255.255", port=9):
print("=> 开始唤醒", mac, broadcast, port)
if len(mac) != 17:
raise ValueError("网卡格式有误,请使用格式:'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)
for i in range(10): # 为避免失败,间隔广播多次
print("-> 尝试唤醒", i+1)
sock.sendto(send_data, (broadcast, port))
time.sleep(1)
print("=> 唤醒结束", mac, broadcast, port)
sock.close()
except Exception as e:
print(e)
# start
if __name__ == '__main__':
wake_up(mac='F4-8E-38-A1-46-46', broadcast='172.33.30.1', port=9)