Skip to content

Instantly share code, notes, and snippets.

@jpalermo
Last active March 16, 2020 21:38
Show Gist options
  • Save jpalermo/5232635197582ccb0a8235dde63cc3c6 to your computer and use it in GitHub Desktop.
Save jpalermo/5232635197582ccb0a8235dde63cc3c6 to your computer and use it in GitHub Desktop.
ruby script to search a CIDR for a computer you can log into
#!/usr/bin/env ruby
require 'netaddr'
require 'open3'
require 'parallel'
require 'io/console'
require 'net/ssh'
if ARGV.length != 1
puts 'Pass search CIDR as the only argument'
exit 1
end
cidr = ARGV.pop
print "Enter Username (#{ENV['USER']}): "
username = gets.strip
username = ENV['USER'] if username.length == 0
password = IO::console.getpass "Enter Password, leave blank for public key auth: "
addresses = NetAddr::IPv4Net.parse(cidr)
address_range = 0..(addresses.len - 1)
Parallel.each(address_range, in_threads: 20) do |address_index|
address = addresses.nth(address_index).to_s
options = {
timeout: 1,
verify_host_key: :never,
}
if password.length == 0
options[:auth_methods] = ['publickey']
else
options[:auth_methods] = ['password']
options[:password] = password
options[:number_of_password_prompts] = 0
end
begin
Net::SSH.start(address, username, options) do |ssh|
output = ssh.exec!("hostname")
puts "#{address}: #{output}"
end
rescue Net::SSH::ConnectionTimeout, Net::SSH::AuthenticationFailed, Errno::ECONNREFUSED, Errno::EACCES
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment