我在一個很多電腦的環境中,這些電腦並沒有被正確清點。基本上,沒有人知道哪個IP與哪個 哪個IP地址以及哪個主機名。所以我寫了以下內容:Ruby中的反向DNS?
# This script goes down the entire IP range and attempts to
# retrieve the Hostname and mac address and outputs them
# into a file. Yay!
require "socket"
TwoOctets = "10.26"
def computer_exists?(computerip)
system("ping -c 1 -W 1 #{computerip}")
end
def append_to_file(line)
file = File.open("output.txt", "a")
file.puts(line)
file.close
end
def getInfo(current_ip)
begin
if computer_exists?(current_ip)
arp_output = `arp -v #{current_ip}`
mac_addr = arp_output.to_s.match(/..:..:..:..:..:../)
host_name = Socket.gethostbyname(current_ip)
append_to_file("#{host_name[0]} - #{current_ip} - #{mac_addr}\n")
end
rescue SocketError => mySocketError
append_to_file("unknown - #{current_ip} - #{mac_addr}")
end
end
(6..8).each do |i|
case i
when 6
for j in (1..190)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 7
for j in (1..255)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
when 8
for j in (1..52)
current_ip = "#{TwoOctets}.#{i}.#{j}"
getInfo(current_ip)
end
end
end
一切工作除了它沒有找到一個反向DNS。
說我越來越示例輸出是這樣的:
10.26.6.12 - 10.26.6.12 - 00:11:11:9B:13:9F
10.26.6.17 - 10.26.6.17 - 08:00:69:9A:97:C3
10.26.6.18 - 10.26.6.18 - 08:00:69:93:2C:E2
如果我做nslookup 10.26.6.12
然後我得到了正確的反向DNS這樣 那就說明我的機器是看到DNS服務器。
我試過Socket.gethostbyname
,gethostbyaddr
,但它不起作用。
任何指導將不勝感激。
實際上這不是做反向查找。你需要使第七個參數爲true:Socket.getaddrinfo(interesting_ip,0,Socket :: AF_UNSPEC,Socket :: SOCK_STREAM,nil,Socket :: AI_CANONNAME,true)` – akostadinov 2015-09-09 20:08:48