代码拉取完成,页面将自动刷新
# encoding = utf-8
# refer https://blog.csdn.net/hih30250/article/details/136342258
import json
import socket
import struct
import sys
import re
import os
from typing import Literal
class WOL_SEND:
def __init__(self, wake_ip, wake_mac):
self.wake_ip = wake_ip
self.wake_mac = wake_mac
pass
def create_wol_package(self):
wake_mac_list = self.wake_mac.split(":")
mac = struct.pack(
"BBBBBB",
int(wake_mac_list[0], 16),
int(wake_mac_list[1], 16),
int(wake_mac_list[2], 16),
int(wake_mac_list[3], 16),
int(wake_mac_list[4], 16),
int(wake_mac_list[5], 16),
) # 将mac地址转二进制
broadcast_mac = b"\xff" * 6 # 生成6字节的FF
wol = (
broadcast_mac + mac * 16
) # 将6字节FF与目标mac的16次进行合并得到wol幻数据包
return wol
def send_wol_package(self):
sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sockets.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) # 设置广播
sockets.sendto(self.create_wol_package(), (self.wake_ip, 9))
def is_mac(mac_address: str) -> bool:
mac1 = re.compile(r"^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$")
mac2 = re.compile(r"^([0-9a-fA-F]{2}-){5}[0-9a-fA-F]{2}$")
return bool(mac1.match(mac_address) or mac2.match(mac_address))
def is_ip4(ip_address: str) -> bool:
ip4 = re.compile(r"^([0-9]{1,3}.){3}[0-9]{1,3}$")
return ip4.match(ip_address) is not None
def json_operator(op: Literal["r", 'w'], data: dict = None) -> list[dict]:
filename, ext = os.path.splitext(sys.argv[0])
json_file = filename + '.json'
if not os.path.exists(json_file):
if op == 'r':
print("错误:记录文件不存在")
exit(-1)
else:
print("警告:记录文件不存在,将新建一个")
else:
obj: list[dict | None] = []
with open(json_file, 'r') as f:
try:
obj = json.load(f)
except json.decoder.JSONDecodeError:
print(f"错误:{json_file}JSON格式错误")
f.close()
if op == 'r':
return obj
else:
for i in obj:
if i['name'] == data['name']:
print("错误:JSON中存在相同的记录名,保存失败")
return obj
obj.append(data)
with open(json_file, 'w') as f:
json.dump(obj, f, indent=4, sort_keys=True, ensure_ascii=False)
f.close()
print("保存成功")
return obj
def main() -> None:
wake_ip = ""
wake_mac = ""
json_save_flag = -1
json_read_flag = -1
for index in range(1, len(sys.argv)):
a = sys.argv[index]
if is_mac(a):
wake_mac = a.replace("-", ":")
elif is_ip4(a):
wake_ip = a
###################################################
elif a.lower() in ["--help", "-h", "/help", "h"]:
help()
exit(-1)
elif 'read' in a.lower() or a.lower() in ['-r', '/r']:
if wake_mac and wake_ip:
print("警告:已填写ip和mac,跳过read参数")
break
if index + 1 <= len(sys.argv):
json_read_flag = index + 1
else:
print("错误:read后缺少值,读取失败")
exit(-1)
elif 'save' in a.lower() or a.lower() in ["-s", "/s"]:
if index + 1 <= len(sys.argv):
json_save_flag = index + 1
else:
print("错误:save后缺少值,保存失败")
exit(-1)
###################################################
if wake_mac != "" and wake_ip != "":
if json_save_flag > 0:
json_operator('w', {
'name': sys.argv[json_read_flag],
'ip': wake_ip,
'mac': wake_mac
})
else:
pass
elif wake_mac != "" and wake_ip == "":
wake_ip = "255.255.255.255"
print("未接收到IP地址,将向广播地址发送魔术封包(广播可能会被路由设备拦截)")
elif wake_mac == "" and wake_ip != "":
print("错误:未接收到MAC地址")
exit(-1)
else:
if json_read_flag > 0:
data = json_operator('r')
d: dict = [d for d in data if d['name'] == sys.argv[json_read_flag]][0]
wake_ip = d['ip']
wake_mac = d['mac']
print(f"读取成功{sys.argv[json_read_flag]}")
else:
wake_ip = input("请输入唤醒设备的局域网IP地址:")
wake_mac = input("请输入唤醒设备mac地址(支持:和-):").replace("-", ":")
if not is_mac(wake_mac):
print("错误:输入的MAC地址无效")
exit(-1)
if not is_ip4(wake_ip):
print("错误:输入的ip地址无效")
exit(-1)
try:
ws = WOL_SEND(wake_ip, wake_mac) # 创建对象,传入MAC地址与IP地址
ws.send_wol_package()
print(f"已向 {wake_ip}({wake_mac}) 发送魔术封包")
# print(ws.create_wol_package())
# print("程序已完成")
except any as e:
print(e)
def help() -> None:
print("使用方式:")
print("[1]python wol.py 然后回答问题")
print("[2]python wol.py %IP地址% %MAC地址%")
print("[3]python wol.py %IP地址% %MAC地址% [-s|--save|/s|/save] %记录名称%")
print("[4]python wol.py [-r|/r|--read|/read] %记录名称%")
if __name__ == "__main__":
# refer https://blog.csdn.net/hih30250/article/details/136342258
main()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。