Last active
December 11, 2015 00:09
-
-
Save kou1okada/4514982 to your computer and use it in GitHub Desktop.
Ruby script to send WOL magic packet.
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
#!/usr/bin/env ruby | |
# Copyright (c) 2013 Koichi OKADA. All rights reserved. | |
# This script is distributed under the MIT license. | |
# http://www.opensource.org/licenses/mit-license.php | |
require 'socket' | |
require 'optparse' | |
def wol mac, ip = "255.255.255.255", port = 9, verbose = true | |
magic = ["ff" * 6 + mac.gsub(/[:-]/,"") * 16].pack("H*") | |
sock = UDPSocket.new | |
sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_BROADCAST, 1) | |
sock.send(magic, 0, ip, port) | |
sock.close | |
puts "Sending magic packet to #{ip}:#{port} with #{mac}" if verbose | |
end | |
if File.expand_path($0) == File.expand_path(__FILE__) | |
Pat_MAC = Regexp.new("^#{(["[0-9a-fA-F]{1,2}"]*6).join("[:-]")}$") | |
Pat_IPv4 = Regexp.new("^#{(["[0-9]{1,3}"]*4).join('\.')}$") | |
$conf = { | |
:p => "9", | |
:i => "255.255.255.255", | |
:q => false, | |
} | |
opts = OptionParser.new | |
opts.banner = "Ruby script to send WOL magic packet.\n" | |
opts.banner += "Usage: #{File.basename $0} [options] MAC_ADDRESS ...\n" | |
opts.banner += "options:" | |
opts.on("-p PORT" ) {|v| $conf[:p] = v} | |
opts.on("-i IP_ADDRESS", Pat_IPv4 ) {|v| $conf[:i] = v} | |
opts.on("-q" , "quiet") {|v| $conf[:q] = v} | |
opts.parse! ARGV | |
error = [] | |
ARGV.each_with_index {|v,i| error << "Error: in ARGV[#{i}]: #{v} is not valid MAC address." unless v =~ Pat_MAC} | |
error << "Error: too few arguments." unless 0 < ARGV.length | |
if 0 < error.length | |
puts error.join("\n"), "\n" | |
puts opts.help | |
exit 1 | |
end | |
ARGV.each {|mac| wol mac, $conf[:i], $conf[:p], !$conf[:q]} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment