Wake-on-LAN Feature Testing Python Script for LattePanda in Local Network

userHead LattePanda 2024-07-09 01:38:10 361 Views1 Replies

The Python script referenced here was showcased in our  Wake-on-LAN (WOL) video tutorial

 

It includes a function named `wake_up`, whose purpose is to construct and dispatch a WOL magic packet to a designated MAC address on a local network. This function is a key component of the script, enabling users to remotely power on machines that support the Wake-on-LAN protocol, simply by providing the correct MAC address.

 

import socket
import time
import struct
def wake_up(mac='xx-xx-xx-xx-xx-xx'):
   """
   Sends a Wake-on-LAN (WOL) magic packet to a specified MAC address within the local network.
   
   :param mac: The MAC address of the device to be woken up, formatted as 'XX-XX-XX-XX-XX-XX'.
   """
   BROADCAST_ADDRESS = "255.255.255.255"
   WOL_PORT = 7
   if len(mac) != 17:
       raise ValueError("MAC address must be in the form 'XX-XX-XX-XX-XX-XX' with 17 characters.")
   
   # Remove hyphens from MAC address and create the magic packet payload
   mac_address = mac.replace("-", '')
   data = 'FFFFFFFFFFFF' + mac_address * 16
   send_data = b''
   # Convert the payload into a byte array
   for i in range(0, len(data), 2):
       send_data += struct.pack('B', int(data[i: i + 2], 16))
   # Send the magic packet to the broadcast address via UDP
   try:
       with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
           sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
           for _ in range(3):  # Send the packet three times
               sock.sendto(send_data, (BROADCAST_ADDRESS, WOL_PORT))
               time.sleep(1)
       print(f"WOL magic packet sent to {mac}.")
   except Exception as e:
       print(f"Failed to send WOL packet: {e}")
# Example usage
wake_up()