Skip to content

Instantly share code, notes, and snippets.

@geoffgarside
Created May 25, 2011 12:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoffgarside/990866 to your computer and use it in GitHub Desktop.
Save geoffgarside/990866 to your computer and use it in GitHub Desktop.
Quick slapped together ruby class for parsing cisco router configuration files, only a start
class CiscoConfigParser
def initialize(io)
@io = io
end
def parse
@io.each do |line|
if line =~ /^\!$/ # terminate current block
end_config
next
elsif line =~ /^\!/ # Comment
next
end
parse_config(line)
end
end
private
def state
@state ||= []
end
def end_config
meth = ['e_config', state].flatten.join('_')
send(meth) if respond_to?(meth)
state.pop
end
def parse_config(line)
cmd, opts = line.strip.split(' ', 2)
meth, opts = meth_and_opts(cmd, opts)
send(meth, opts) if respond_to?(meth)
end
def meth_and_opts(cmd, opts)
return negated_meth_and_opts(opts) if cmd =~ /no/
[['p_config', state, cmd.gsub('-', '_')].flatten.join('_'), opts]
end
def negated_meth_and_opts(line)
cmd, opts = line.split(' ', 2)
[['n_config', state, cmd.gsub('-', '_')].flatten.join('_'), opts]
end
protected
def p_config_vlan(ids)
@current_vlan = {:ids => ids}
end
def e_config_vlan
@vlans ||= {}
@vlans[@current_vlan.delete(:ids)] = @current_vlan
end
def p_config_interface(name)
state.push(:interface)
@current_interface = {:id => name}
end
def e_config_interface
@interfaces ||= {}
@interfaces[@current_interface.delete(:id)] = @current_interface
end
def p_config_interface_description(str)
@current_interface[:description] = str
end
end
@lozzd
Copy link

lozzd commented Jan 24, 2013

This is insane. But also awesome. Thanks!
Did you ever do any more? I'm expanding it now so I can compare the allowed vlans on two sets of core routers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment