Lua脚本报错:尝试索引nil全局变量'nmap'问题求助
问题分析
报错lua: discovery_n.lua:12: attempt to index a nil value (global 'nmap')的核心原因是:你直接用Lua解释器运行脚本,但nmap.registry是Nmap脚本引擎(NSE)专属API,只有当脚本被Nmap调用执行时才会加载这些全局变量,直接跑Lua脚本自然找不到nmap对象。
修复方案
1. 替换JSON解析依赖
用标准Lua的JSON库(比如dkjson)替代NSE的nmap.registry.fromJSON:
- 先通过LuaRocks安装dkjson:执行
luarocks install dkjson
2. 简化Nmap输出处理
你的需求是把Nmap扫描结果保存为XML文件,无需用NSE API解析后再转XML——直接将Nmap命令输出的原始XML内容写入文件即可,省去中间转换步骤。
修复后的完整代码
#!/usr/bin/env lua local io = require('io') local dkjson = require('dkjson') -- Read JSON file local file, err = io.open("discovery.json", "r") if not file then error("Error: " .. err .. "\nJSON file not found, please make sure the file exists and the path is correct") end local json_data = file:read("*all") file:close() -- Parse JSON data with dkjson local data, parse_err = dkjson.decode(json_data) if not data then error("Error parsing JSON: " .. parse_err) end -- Extract IP addresses local host_list = data.Detail.host_list if type(host_list) ~= "table" then error("host_list is not a table") end -- Iterate over host_list for _, host in ipairs(host_list) do local ip_v4_address = host.host.ip_v4_address if not ip_v4_address then print("Skipping host: no IPv4 address found") goto continue end -- Run nmap command and capture XML output local nmap_command = "nmap -oX - " .. ip_v4_address local nmap_handle = io.popen(nmap_command, "r") if not nmap_handle then print("Failed to run nmap command for " .. ip_v4_address) goto continue end local nmap_output = nmap_handle:read("*all") local exit_code = nmap_handle:close() if exit_code ~= 0 then print("Nmap scan for " .. ip_v4_address .. " failed with exit code: " .. exit_code) goto continue end -- Write XML output to file local output_file, file_err = io.open(ip_v4_address .. ".xml", "w") if output_file then output_file:write(nmap_output) output_file:close() print("Nmap scan for " .. ip_v4_address .. " completed, result saved to " .. ip_v4_address .. ".xml") else print("Error writing file for " .. ip_v4_address .. ": " .. file_err) end ::continue:: end
额外说明
- 如果确实需要在Lua中解析Nmap的XML输出,可以使用Lua的XML库(比如
luaexpat),但对于你的需求来说直接保存原始XML更高效。 - 确保运行脚本的用户有执行Nmap的权限,以及读写目标文件的权限。
内容的提问来源于stack exchange,提问作者Kris Armstrong
相关产品推荐
相关产品推荐

