代码如下:
# !/usr/bin/env python3
# coding:utf-8
import socket
import binascii
import re
\#定义一个函数,默认MAC地址为欲唤醒电脑的MAC地址(WIN系统可通过ipconfig获取)
def wakeup(mac='F4-4D-30-73-87-E7',ip='192.168.2.255'):
\#利用正则判断MAC地址是否合法
if re.match(r"([0-9a-fA-F]{2}(-|:){0,1}){5}([a-fA-F0-9]{2})",mac) and (len(mac) == 12 or len(mac) == 17):
\#去掉MAC地址里的:和-
mac = mac.replace('-','').replace(':','').upper()
\#IP地址可以是具体某个IP或者是一个广播地址,端口一般为9
IP,port=ip,9
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
\#转换编码,唤醒数据包为FFFFFFFFFFFF+MAC地址重复16次+密码
send_data=binascii.unhexlify('FF' * 6 + mac.upper() * 20)
s.sendto(send_data,(IP,port))
s.close()
print("向"+mac+"发送唤醒包成功!")
else:
print("MAC address ERROR")
wakeup()