Created
May 22, 2012 03:55
-
-
Save kachick/2766460 to your computer and use it in GitHub Desktop.
昔でっちあげたもの - 同セグメントに居るホストのMACアドレスを集める
This file contains hidden or 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
| require 'ipaddr' | |
| class IPAddr | |
| #==なら要件を満たせるので、オーバーライドしてしまおう。 | |
| alias_method :'eql?', :'==' | |
| #hashの判定は、ライブラリの==メソッドから適当に判断した。 | |
| def hash | |
| [@family, @addr].hash | |
| end | |
| end |
This file contains hidden or 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
| #! ruby -w -Ks | |
| # -*- coding: Shift_JIS -*- | |
| # | |
| # Description: | |
| # 同セグに居るホストのMACアドレスを集める | |
| # Env: | |
| # Ruby 1.8.7 & Windows XP | |
| # Usage: | |
| # 起動すると、標準出力へ調査結果をCSVで吐く | |
| # Example: | |
| # script.rb > macaddrs.csv | |
| # Updates | |
| # 0.1.0 2011/02/22 | |
| # 0.1.1 2011/06/02 | |
| require 'ipaddr_ext' | |
| module MACCollector | |
| NetworkInfo = Struct.new :ip, :mac, :mac_type do | |
| def <=>(other) | |
| ip <=> other.ip | |
| end | |
| end | |
| module_function | |
| def collect(segment, interval=0.2) | |
| [].tap do |results| | |
| [].tap {|threads| | |
| segment.to_range.each do |ip| | |
| threads << Thread.start(ip) do | |
| `ping #{ip} -n 1 -w 1` | |
| if /^\s+((?:\d{1,3}\.){3}\d{1,3})\s+(\S+)\s+(\S+)/ =~ `arp -a #{ip}` | |
| results << NetworkInfo.new(IPAddr.new($1), $2, $3) | |
| end | |
| end | |
| sleep interval | |
| end | |
| }.each(&:join) | |
| results.sort! | |
| end | |
| end | |
| end | |
| include MACCollector | |
| IPCONFIG = `ipconfig` | |
| SEGMENT = IPAddr.new( | |
| "#{IPCONFIG.slice(/\bIP Address\b.+: (\S+)/, 1)}/#{IPCONFIG.slice(/\bSubnet Mask\b.+: (\S+)/, 1)}" | |
| ) | |
| puts NetworkInfo.members.map(&:upcase).join(',') | |
| collect(SEGMENT).each do |info| | |
| puts info.values.join(',') unless info.mac_type == 'invalid' | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment