2006/11/16, Kathy Simmons <kathys39 / hotmail.com>:
> Here's the full code - I'm reading in nmap output in scanfile.xml and
> want to put the data in a mysql db:
>
> #! /usr/bin/ruby
>
> require 'rexml/document'
> require "mysql"
> require "dbi"
> include REXML
> scanfile = File.new('scanfile.xml')
> doc = Document.new(scanfile)
> root = doc.root
>
> doc.elements.each("nmaprun") { |element|
>         puts element.attributes["args"]
>         args = element.attributes["args"]
>         puts element.attributes["startstr"]
>         timeofscan = element.attributes["startstr"]
>         puts element.attributes["version"]
>         version = element.attributes["version"]   }
>
> doc.elements.each("nmaprun/scaninfo") { |element|
>         puts element.attributes["type"]
>         scantype = element.attributes["type"]
>         puts element.attributes["protocol"]
>         protocol = element.attributes["protocol"]
>         puts element.attributes["numservices"]
>         numservices = element.attributes["numservices"]
> #       puts element.attributes["services"]
>         services = element.attributes["services"]   }
>
> doc.elements.each("nmaprun/scaninfo/host") { |element|
>         puts element.attributes["status state"] }
>
> # database insert
> dbname="nmap"
> m = Mysql.new("localhost", "root", "")
> dbh=DBI.connect("dbi:Mysql:nmap:localhost", "root", "")
> m.select_db(dbname)
> sth=dbh.prepare("INSERT INTO rawdata
> (file,tool,arguments,startime,version) VALUES (?,?,?,?,?)")
> sth.execute("scanfile.xml", "nmap", "${args}", "#{timeofscan}",
> "${version}"")

You have a scoping problem: you set timeofscan etc. inside the block
when traversing the XML document.  But they are not visible outside
the block and thus you likely get a NameError.

If you want to insert multiple values into the DB you need to traverse
the XML doc and then execute for each iteration.

I'd also use the block forms of your DB connection methods and file
handling in order to make sure connections are properly closed etc.
It's good to start that habit early. :-)

Sample:

doc = File.open('scanfile.xml', 'rb') {|scanfile| Document.new(scanfile) }

Kind regards

robert