如何将CIDR格式转换为所有可能的IP地址列表?[BATCH]

时间:2015-02-15 16:38:31

标签: python ruby batch-file ip cidr

我想知道如何将CIDR IP转换为所有可能IP地址的列表。我知道这个话题已经存在,但没有一个真正给了我所需要的东西。

所以问题很简单。如果有人可以创建一个程序[无论使用什么语言(ruby,python等等)],那么会创建.txt文件 - 来自.txt文件的IP地址列表,其中包含CIDR IP。

包含CIDR IP的文本 - >程序处理 - >新文件" CHOSEN文件中所有可能的IP列表"

我希望我足够清楚,你确实了解我,我也希望有人能帮助我。非常感谢你提前!

如果CIDR足够复杂,您可以尝试制作使用 IP范围的程序

除了一件事,我还发现geoipgen非常好。它不会保存任何东西,它只是输出。有没有办法实现" save"将输出保存到文件的选项。

这是我在评论中所说的Ruby代码(仅限IP范围):

    #!/usr/bin/env ruby
#
# Turn IP Ranges into CSV output
# By: HR
#
# Now handles single input or loading via file:
#     ipranges2csv.rb -f ranges.txt
#     ipranges2csv.rb -s 192.168.2-3.1-25
#

# Output file, edit as needed
CSV_OUTPUT='ip_ranges.csv'

require 'optparse'
require 'colorize' # to install: sudo gem install colorize

# Trap Interupts, close cleanly
trap("SIGINT") {
  puts "\n\nWARNING".light_red + "!".white + " CTRL".light_red + "+".white + "C Detected, Shutting things down".light_red + ".....\n\n".white
  exit 666;
}

def banner
  puts "IP Range to CSV Convertor".light_green
  puts "By".light_green + ": HR".white
end

def cls
  if RUBY_PLATFORM =~ /win32|win64|windows|WoW64|\.NET/i
    system('cls')
  else
    system('clear')
  end
end

# Breaks up IP range into array of all the unique single IP values
# Returns updated array that is primed for CSV writing
def range_convertor(iprange)
  iprange.sub!(/\/\d+$/, '')      # No CIDR Support here, sorry
  blocks = iprange.split('.')[0..3]   # Break our IP into array of smaller chunks for handling

  # Setup our iteration sets for each block
  d_range = []
  if blocks[3] =~ /-/
    (blocks[3].split('-')[0] .. blocks[3].split('-')[-1]).each {|i| d_range << i }
  else
    d_range << blocks[3]
  end

  c_range = []
  if blocks[2] =~ /-/
    (blocks[2].split('-')[0] .. blocks[2].split('-')[-1]).each {|i| c_range << i }
  else
    c_range << blocks[2]
  end

  b_range = []
  if blocks[1] =~ /-/
    (blocks[1].split('-')[0] .. blocks[1].split('-')[-1]).each {|i| b_range << i }
  else
    b_range << blocks[1]
  end

  a_range = []
  if blocks[0] =~ /-/
    (blocks[0].split('-')[0] .. blocks[0].split('-')[-1]).each {|i| a_range << i }
  else
    a_range << blocks[0]
  end

  # Now try to piece it all together
  the_real_ranges = []
  a_range.each {|z| b_range.each {|y| c_range.each {|x| d_range.each {|w| the_real_ranges << "#{z}.#{y}.#{x}.#{w}" } } } }

  return the_real_ranges.uniq
end

# Main>
options = {}
optparse = OptionParser.new do |opts|
  opts.banner = "Usage: #{$0} ".white + "[".light_green + "OPTIONS".white + "]".light_green
  opts.separator ""
  opts.separator "EX".light_green + ": #{$0} -f ip_ranges.txt".white
  opts.separator "EX".light_green + ": #{$0} --file /tmp/ips.txt".white
  opts.separator "EX".light_green + ": #{$0} -s '192.168.3-5.1-254'".white
  opts.separator "EX".light_green + ": #{$0} --single '192.168.3-5.1-254'".white
  opts.separator ""
  opts.separator "Options".light_green + ": ".white
  opts.on('-f', '--file FILE', "\n\tFile to load for CSV conversions (one IP/Range per line)".white) do |target|
    if File.exists?(target.strip.chomp)
      options[:method] = 2
      options[:rangefile] = target.strip.chomp
    else
      puts "\nProblem finding IP Range file".light_red + "!".white
      puts "Please check path or permissions and try again".light_red + ".....\n\n".white
      exit 666;
    end
  end
  opts.on('-s', '--single IP', "\n\tSingle IP Range to Convert to CSV".white) do |single|
    options[:method] = 1
    options[:single] = single.strip.chomp
  end
  opts.on('-h', '--help', "\n\tHelp Menu".white) do
    cls
    banner
    puts
    puts opts
    puts
    exit 69;
  end
end
begin
  foo = ARGV[0] || ARGV[0] = "-h" # if nothing passed, send to help menu
  optparse.parse!
  mandatory = [ :method ]
  missing = mandatory.select{ |param| options[param].nil? } #freakout if they dont give us what we need!
  if not missing.empty?
    puts "Missing option(s)".light_red + ": #{missing.join(', ')}".white
    puts
    banner
    puts optparse
    puts
    puts
    exit
  end
rescue OptionParser::InvalidOption, OptionParser::MissingArgument, OptionParser::AmbiguousOption
  cls
  puts $!.to_s.light_red
  puts
  banner
  puts optparse
  puts
  puts
  exit 666;
end

cls
banner
csv_ips=[]
if options[:method].to_i == 1
  # Single IP Range
  puts "\n\nConverting Single IP Range".light_green + ": #{options[:single]}".white
  csv_ips = range_convertor(options[:single])
else
  # Load IP Ranges from File
  puts "\n\nConverting IP Ranges from File".light_green + ": #{options[:rangefile]}".white
  fh=File.open(options[:rangefile])
  fh.each do |line|
    res = range_convertor(line.strip.chomp)
    res.each {|ip| csv_ips << ip unless csv_ips.include?(ip)}
  end
  fh.close
end

# Write the converts to file
puts "Writing results to new CSV file".light_green + "....".white
fh=File.open(CSV_OUTPUT, 'w+')
fh.puts csv_ips.join(',')
fh.close
puts "Conversion complete, results can be found in".light_green + ": #{CSV_OUTPUT}\n\n".white
#EOF

0 个答案:

没有答案