Ruby output format

I have the following code that works great. The problem is that I get the following output:

Device ID: SEP1C17D3415659

IP Address: 10.2.3.101

I would like to get:

SEP1C17D3415659 10.2.3.101

thanks for the help


require 'net/telnet'
require '/apps/dateformat'


@tdate = Formatdate.new.mydate

hosts = %w"SW3"


  hosts.each do |hostname|

        tn = Net::Telnet::new("Host" => "#{hostname}",
                                     "Timeout" => 10000,
                                     "Prompt" => /[$%#>] \z/n)

        tn.cmd('String' =>'user' , 'Match'=>/Password:/) { |c| puts c }
        tn.cmd('String' =>'password', 'Match'=>/#/) { |c| puts c }
        tn.cmd('String' =>'terminal length 0', 'Match'=>/#/) { |c| puts c }


        File.open("/agents/#{hostname}-#{@tdate}-agents.txt",'w') do |o|
            run=tn.cmd('String' =>'sh cd ne de | inc Device ID: | IP address:', 'Match'=>/#/) { |c| puts c }
                        run.each_line do |re|
                        mac = re.match /Device ID: ([\S]+)/
                        #ip = re.match /([\S]+) address/
                        ip = re.match /IP address: ([\S]+)/
                        o.puts mac
                        o.puts ip
                    end




        end

end
+3
source share
2 answers

You correctly specify the grouping you want for your regular expression, but you do not use it when printing it. A.

Your regex:

mac = re.match /Device ID: ([\S]+)/

and that matches the whole line Device ID: SEP1C17D3415659by putting the right part ( SEP1C17D3415659) in the group so you can get it later. However, you print it with

o.puts mac

This gives the whole match, not just the group. Instead, you want:

o.puts mac[1]

which indicates only the group.

, , puts . , , - :

o.print "#{mac[1]} #{ip[1]}\n"

.


Edit:

net/telnet , , , , , . , , , nil mac ip, "undefind method []" .

, :

o.print "#{mac[1]} #{ip[1]}\n" unless mac.nil?

, , , , . , , , :

run.each_line do |line|
  match = line.match /^Device ID: ([\S]+), IP address: ([\S]+)$/ #these are the lines we want
  next unless match #skip lines we don't want
  o.print "#{match[1]} #{match[2]}\n" #print the details we're interested in
end
+1

puts . , .

outputString = mac + " " + ip
o.puts outputString

, , , .

+3

All Articles