Posted on Friday, 27th January 2012 by Michael
Ruby: Script to check if an IP is up and get its Hostname
This script will go line by through a text file checking to see which IP is up. If the host is not up it will log to the results.csv file as “IP,DOWN,NoName”. If the host is up it will log to the results.csv file as “IP,UP,hostname”. Please note that if the authority DNS server does not have an answer for that IP it will log no name and instead will put the IP address again. This script is very handy on our firewall audits and cleans ups to see what hosts are still needed and which are no longer even turned on any longer.
You will need to have the IP addresses you want to check in a file called IP.txt, unless you edit the script. Make sure you put the file in the same path as the script.
#!/usr/bin/ruby
require "socket"
require 'resolv'def computer_exists?(fwip)
system("ping -c1 -w1 #{fwip}")
enddef append_to_file(line)
file = File.open("results.csv", "a")
file.puts(line)
file.close
enddef getInfo(current_ip)
begin
if computer_exists?(current_ip)
host_name = Socket.getaddrinfo(current_ip,nil)
append_to_file("#{current_ip},UP,#{host_name[0][2]}\n")
else
append_to_file("#{current_ip},DOWN,NoNAME\n")
end
rescue SocketError => mySocketError
append_to_file("#{current_ip},UP,ERROR")
end
end#Myfavorite method, read and process file
ipLST='IP.txt'
File.readlines(ipLST).each do |line|
current_ip = "#{line}"
getInfo(current_ip)
end
Posted in Code | Comments (0)