# frozen_string_literal: true require_relative "../netdisco" require "slop" class Netdisco class CLI class MissingHost < NetdiscoError; end class NoConfig < NetdiscoError; end # 网络邻居发现入口函数 def run output = Netdisco.new.discover @host # 邻居关系发现后修正处理逻辑钩子函数 output.clean! if @opts[:purge] output.resolve! if @opts[:resolve] # 将计算结果转换格式打印 if @opts[:graphviz] output.to_dot elsif @opts[:list] output.to_a elsif @opts[:json] output.to_json elsif @opts[:yaml] output.to_yaml else output.to_hash end end # 类对象初始化入口函数 def initialize raise NoConfig, "edit ~/.config/netdisco/config" if CONFIG.create args, @opts = opt_parse @host = DNS.getip args.shift raise MissingHost, "no hostname given as argument" unless @host CFG.snmp.community = @opts[:community] if @opts[:community] CFG.debug = true if @opts[:debug] CFG.ipname = true if @opts[:ipname] end # CLI 命令行交互解析 def opt_parse opts = Slop.parse do |o| o.on "-h", "--help", "show usage" do puts o exit end o.on "-g", "--graphviz", "dot output use 'dot -Tpng -o map.png map.dot'" o.on "-l", "--list", "list nodes" o.on "-j", "--json", "json output" o.on "-y", "--yaml", "yaml output" o.on "-a", "--hash", "hash/associative array output" o.on "-r", "--resolve", "resolve addresses to names" o.on "-p", "--purge", "remove peers not in configured CIDR" o.string "-c=", "--community", "SNMP community to use" o.bool "-d", "--debug", "turn debugging on" o.bool "-i", "--ipname", "use rev(ip) name instead of discovered name" o.on "-v", "--version", "print the version" do puts Slop::VERSION exit end end [opts.arguments, opts] end end end