Last active
February 1, 2018 15:38
-
-
Save mraaroncruz/f103b8af4d81f59a54a5f2af6dc238b6 to your computer and use it in GitHub Desktop.
Read MAC addresses from your dhcp.leases file and send them Magic Packets to Wake On LAN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// Core code borrowed from the cmd/ files in http://github.com/sabhiram/go-wol | |
import ( | |
"bufio" | |
"errors" | |
"flag" | |
"fmt" | |
"os" | |
"regexp" | |
"time" | |
wol "github.com/sabhiram/go-wol" | |
) | |
const defaultInterval time.Duration = 10 * time.Millisecond | |
var ( | |
dhcpPath = flag.String("leases-path", "/var/db/isc/dhcpd/dhcpd.leases", "Path to dhcp leases file") | |
broadcastInterface = flag.String("interface", "", "Broadcast interface") | |
broadcastIP = flag.String("bcast", "255.255.255.255", "Broadcast IP") | |
udpPort = flag.String("port", "9", "UDP Port") | |
delay = flag.Duration("interval", defaultInterval, "Time to wait between waking") | |
) | |
func main() { | |
flag.Parse() | |
exitCode := run() | |
os.Exit(exitCode) | |
} | |
func parseMACAddresses(path string) ([]string, error) { | |
f, err := os.Open(path) | |
defer f.Close() | |
if err != nil { | |
return nil, err | |
} | |
var macAdresses []string | |
re := regexp.MustCompile(`hardware ethernet ([0-9A-Fa-f:]+);`) | |
buf := bufio.NewScanner(f) | |
for { | |
if buf.Scan() { | |
matches := re.FindStringSubmatch(buf.Text()) | |
if len(matches) > 1 { | |
macAdresses = append(macAdresses, matches[1]) | |
} | |
} else { | |
break | |
} | |
} | |
return macAdresses, nil | |
} | |
func run() int { | |
exitCode := 0 | |
macAddresses, err := parseMACAddresses(*dhcpPath) | |
if err != nil { | |
fmt.Printf("%s\n", err.Error()) | |
exitCode = 1 | |
} | |
for _, address := range macAddresses { | |
_ = runWakeCommand(address) | |
time.Sleep(*delay) | |
} | |
return exitCode | |
} | |
func runWakeCommand(macAddr string) error { | |
var err error | |
// bcastInterface can be "eth0", "eth1", etc.. An empty string implies | |
// that we use the default interface when sending the UDP packet (nil) | |
bcastInterface := "" | |
// Always use the interface specified in the command line, if it exists | |
if *broadcastInterface != "" { | |
bcastInterface = *broadcastInterface | |
} | |
err = wol.SendMagicPacket(macAddr, *broadcastIP+":"+*udpPort, bcastInterface) | |
if err != nil { | |
fmt.Printf("ERROR: %s\n", err.Error()) | |
return errors.New("Unable to send magic packet") | |
} | |
fmt.Printf("Magic packet sent successfully to %s\n", macAddr) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment