按照WOL协议规定,在电脑处于关机而网卡供电状态下,从网络上接收到WOL魔法包后会自动加电开机。这种方式能够很方便的使用在需要进行远程管理的环境中。此程序实现了网络唤醒的魔法数据包发送功能,可以实现远程开机。
假设需要被唤醒PC网卡MAC地址为:01:02:03:04:05:06 则WOL魔法包结构如下:
FF FF FF FF FF FF | 01 02 03 04 05 06 ...重复16次... 01 02 03 04 05 06 | 00 00 00 00 00 00
前段的6字节0xff 和尾部的 6字节0x00 无需变化照抄即可,数据包总长度:108 字节
通过把以上数据包发送到本地子网的广播地址(代码中为:192.168.1.255)的UDP端口9即可唤醒该PC
注意:此代码需要python解释器运行,Windows/Linux/Mac OS 通用
使用方法:
1. 保存以下代码到 wol.py
#!/usr/bin/env python #coding=utf-8 import socket, sys import struct def to_hex_int(s): return int(s.upper(), 16) dest = (‘192.168.1.255‘, 9) if len(sys.argv) < 2: print("usage: %s <MAC Address to wakeup>" % sys.argv[0]) sys.exit() mac = sys.argv[1] spliter = "" if mac.count(":") == 5: spliter = ":" if mac.count("-") == 5: spliter = "-" if spliter == "": print("MAC address should be like XX:XX:XX:XX:XX:XX / XX-XX-XX-XX-XX-XX") sys.exit() parts = mac.split(spliter) a1 = to_hex_int(parts[0]) a2 = to_hex_int(parts[1]) a3 = to_hex_int(parts[2]) a4 = to_hex_int(parts[3]) a5 = to_hex_int(parts[4]) a6 = to_hex_int(parts[5]) addr = [a1, a2, a3, a4, a5, a6] packet = chr(255) + chr(255) + chr(255) + chr(255) + chr(255) + chr(255) for n in range(0,16): for a in addr: packet = packet + chr(a) packet = packet + chr(0) + chr(0) + chr(0) + chr(0) + chr(0) + chr(0) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1) s.sendto(packet,dest) print("WOL packet %d bytes sent !" % len(packet))
2. 使用方法为命令行下执行(linux/Mac可以不需要写命令最开始的python):
python ./wol.py 01:02:03:04:05:06
本文出自 “iPlay IT” 博客,转载请与作者联系!
Python WOL/WakeOnLan/网络唤醒数据包发送工具
原文:http://iplayit.blog.51cto.com/7753603/1576048