Skip to content

Instantly share code, notes, and snippets.

@0xpizza
Last active July 22, 2023 00:10
Show Gist options
  • Save 0xpizza/ca5eab01021133cd46440ac415960dae to your computer and use it in GitHub Desktop.
Save 0xpizza/ca5eab01021133cd46440ac415960dae to your computer and use it in GitHub Desktop.
import argparse
import os
import re
import socket
import sys
import logging
logging.basicConfig(
format='[%(levelname)s] %(asctime)s - %(message)s',
stream=sys.stdout,
level=logging.INFO,
)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('MAC', type=str)
parser.add_argument('--debug', action='store_true')
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
regex = r'^([\da-f]{2}[-:]?){5}[\da-f]{2}$'
logging.debug('Verifying MAC: %s', regex)
mac = re.match(regex, args.MAC.strip(), re.IGNORECASE)
if mac is None:
logging.error('Invalid MAC address (example: 11-22-33-44-55-66)')
raise SystemExit
mac = bytes.fromhex(re.sub('[:-]', '', mac.group()))
my_ip = socket.gethostbyname(socket.gethostname())
logging.info(f'Attempting to wake up {mac.hex().upper()} on interface {my_ip}')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
with s:
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((my_ip,0))
payload = b'\xff' * 6 + mac * 16
broadcast = ('255.255.255.255', 0)
logging.debug('Payload: %s', payload.hex())
for _ in range(10):
s.sendto(payload, broadcast)
logging.debug('Sent 1 packet to %s:%s', broadcast[0], broadcast[1])
logging.info('Sent 10 magic packets!')
if __name__ == '__main__':
try:
main()
except Exception as e:
logging.critical('Unexpected exception: %s', str(e))
raise RuntimeError from e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment