Skip to content

Instantly share code, notes, and snippets.

@Mic92
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mic92/78ec3aceeb173e88a02c to your computer and use it in GitHub Desktop.
Save Mic92/78ec3aceeb173e88a02c to your computer and use it in GitHub Desktop.
Generate bgp filter for dn42
#!/usr/bin/env ruby
# Author: Mic92 <joerg@higgsboson.tk>
# License: WTFPL (C) 2015
#
# TODO
# - support openbgp
require "optparse"
if (RUBY_VERSION.split(/\./) <=> ["1","9","0"]) == -1
abort "This script needs at least ruby 1.9"
end
def blank?(s)
s.nil? || s =~ /^\s*$/
end
options = { }
parser = OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options]"
opts.on("--format [FORMAT]", [:bird, :quagga], "syntax format (bird, quagga)") do |format|
options[:format] = format
end
end
parser.parse!
if ARGV.size == 0
source = $stdin
else
begin
source = File.open(ARGV[0])
rescue SystemCallError => e
abort e.to_s
end
end
peers = []
source.map do |line|
# Line-Format: Nr Action Prefix MinLen MaxLen
next unless line =~ %r!(\d+)\s+(\w+)\s+([a-fA-F0-9.:]+)/(\d+)\s+(\d+)\s+(\d+)!
peer = [$1, $2, $3, $4, $5, $6]
line =~ /#(.*)$/
peer << $1
peers << peer
end
case options[:format]
when :bird
puts "function is_valid_network() {"
puts " return net ~ ["
permitted_peers = peers.find_all {|peer| peer[1] == "permit" }
permitted_peers.each_with_index do |peer, i|
_, _, prefix, prefixlen, minlen, maxlen, comment = peer
print " #{prefix}/#{prefixlen}{#{minlen},#{maxlen}}"
print "," unless (permitted_peers.size - 1) == i
if blank?(comment)
puts
else
puts " ##{comment}"
end
end
puts " ];\n}"
else # :quagga
peers.each do |peer|
number, action, prefix, prefixlen, minlen, maxlen, comment = peer
print "ip prefix-list dn42-in seq #{number} #{action} #{prefix}/#{prefixlen}"
if prefixlen != maxlen
print " ge #{maxlen}"
end
if prefixlen != minlen
print " le #{minlen}"
end
if blank?(comment)
puts
else
puts " ##{comment}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment