Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wake-On-Lan Magic Packet using netcat in bash
#!/usr/bin/env bash
mac_address=$1
# Strip colons from the MAC address
mac_address=$(echo $mac_address | sed 's/://g')
broadcast=$2
port=4343
# Magic packets consist of 12*`f` followed by 16 repetitions of the MAC address
magic_packet=$(
printf 'f%.0s' {1..12}
printf "$mac_address%.0s" {1..16}
)
# ... and they need to be hex-escaped
magic_packet=$(
echo $magic_packet | sed -e 's/../\\x&/g'
)
# echo $magic_packet
echo -e $magic_packet | nc -w1 -u $broadcast $port
@iameli

This comment has been minimized.

Copy link

@iameli iameli commented May 15, 2018

thing I did: add -b and broadcast to 255.255.255.255 to wake the device anywhere on the LAN

@Dareeo

This comment has been minimized.

Copy link

@Dareeo Dareeo commented Dec 7, 2018

what if my router can't accept any parameters in nc (-u)?

@allanlinuxmg

This comment has been minimized.

Copy link

@allanlinuxmg allanlinuxmg commented Aug 23, 2019

Hello.

I have a improvement for your script.
Change var: mac_address
From:
mac_address=$(echo $mac_address | sed 's/://g')
To:
mac_address=$(echo $mac_address | sed 's/[ :-]//g')

Then it will work with four mac formats.
Ex:
74:e6:e2:aa:aa:aa #Linux
74-e6-e2-aa-aa-aa #Windows
"74 e6 e2 aa aa aa" #Space
74e6e2aaaaaa #All close

@yoshihikoueno

This comment has been minimized.

Copy link

@yoshihikoueno yoshihikoueno commented Apr 15, 2020

oh yeah, sed has slight different syntaxes depending on the OS. Maybe it'll be better to use perl instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment