json_object={
"ip"=> "127.0.0.1",
"ports"=> '80,135',
"data"=>{"port"=>22,"item"=>["22","open","tcp","","ssh"]}
}
puts "json_object:#{ json_object.to_json}"
write_log("nmapresult.log",json_object.to_json)
Rails.logger.info("#{Time.now.strftime('%Y-%m-%d %H:%M:%S')} str:#{json_object.to_json}")
# file_name 文件名称 foreign_ips.txt
# data 要写入的数据 str
def write_log(file_name,data)
# /media/haima/34E401CC64DD0E28/site/go/src/ruby/fofapro/public/download
log_dir = File.expand_path(File.join(Rails.root.to_s, 'log'))
puts "write log success , logPath:#{log_dir}"
FileUtils.mkdir_p(download_dir,:mode=>2750) unless File.exist?(log_dir)
# /media/haima/34E401CC64DD0E28/site/go/src/ruby/rails_demo/log/file_name
file_path = File.expand_path(File.join(log_dir, file_name))
# 判断文件不存在创建,存在打开
if !File.exist?(file_path)
#读写模式。如果文件存在,则重写已存在的文件。如果文件不存在,则创建一个新文件用于读写。
foreign_ip_file = File.new(file_path, "w+")
else
#读写模式。如果文件存在,则文件指针被放置在文件的末尾。也就是说,文件是追加模式。如果文件不存在,则创建一个新文件用于读写。
foreign_ip_file = File.open(file_path, "a+")
end
foreign_ip_file.puts(data)
foreign_ip_file.close
end
end
解析json
json='{"ip":"127.0.0.1","ports":"80,135","data":{"port":22,"item":["22","open","tcp","","ssh"]}}'
str22 = JSON.parse(json)
puts "str22 #{str22}"
puts "str23 #{str22['ports']}"
输入结果
str22 {"ip"=>"127.0.0.1", "ports"=>"80,135", "data"=>[{"port"=>22, "item"=>["22", "open", "tcp", "", "ssh"]}]}
str23 80,135