需求
- 家中nas需要定时唤醒
- 远程在外唤醒家中的电脑
直接上代码
# coding:utf-8
import socket
import struct
import time
def wake_up(MAC =''):
BROADCAST = "192.168.0.255"
# BROADCAST = "www.baidu.cn" # 如果是外网访问,可以用域名,记得讲本地7、9端口映射出去
# BROADCAST = "27.38.173.130" # 外网ip也可以,推荐用域名
if len(MAC) != 17:
raise ValueError("mac address should be as 'XX-XX-XX-XX-XX-XX'")
mac_address = MAC.replace("-", '')
data = ''.join(['FFFFFFFFFFFF', mac_address * 20])
send_data = b''
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)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
posts = [9]
for port in posts:
sock.sendto(send_data, (BROADCAST, port))
print("Ok")
except Exception as e:
print(e)
wake_up(mac="xx-xx-xx-xx-xx-xx")
说明
- mac地址可以在自己的路由器中获取
- 网络唤醒,需要被唤醒的机器主板支持网络唤醒,记得在bios设置
- 通过外网唤醒,需要ddns,将本地7,9号端口映射出去
原创文章,作者:站长,如若转载,请注明出处:https://wsppx.cn/136/%e7%bd%91%e7%bb%9c%e5%bc%80%e5%8f%91/%e5%90%8e%e7%ab%af/python/