Lua脚本模式匹配问题

时间:2010-08-11 14:13:50

标签: scripting lua nmap

首先,我一直在使用这个网站作为整个脚本编写过程的参考,并且它非常精彩。我很感激每个人都在这里有用和知识渊博。考虑到这一点,我有一个关于Lua匹配(模式匹配)的问题。我正在编写一个脚本,它基本上从文件中获取输入并将其导入表中。我正在检查文件中的特定MAC地址作为我正在查询的主机。

  if macFile then
     local file = io.open(macFile)

     if file then
    for line in file:lines() do
      local f = line
      i, j = string.find ( f, "%x+" )
      m = string.sub(f, i, j)
      table.insert( macTable, m )
    end
    file:close()
     end

这会将文件解析为我稍后将用于查询的格式。构建表之后,我运行一个模式匹配序列,通过迭代表并将模式与当前迭代匹配来尝试匹配表中的MAC:

local output = {}
t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")
for key,value in next,macTable,nil do
        a, p = string.find ( s, value )
        matchFound = string.sub(s, a, p)
        table.insert( output, matchFound )
end

这不会返回任何输出,虽然当我在Lua提示符中逐行输入时,它似乎有效。我相信变量正确传递。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

如果你的macFile使用这样的结构:

012345678900
008967452301
000000000000
ffffffffffff

以下脚本应该有效:

macFile = "./macFile.txt"
macTable = {}

if macFile then
    local hFile = io.open(macFile, "r")
    if hFile then
        for line in hFile:lines() do
            local _,_, sMac = line:find("^(%x+)")
            if sMac then
                print("Mac address matched: "..sMac)
                table.insert(macTable, sMac)
            end
        end
        hFile:close()
    end
end

local output = {}
t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")

for k,v in ipairs(macTable) do
    if s == v then
        print("Matched macTable address: "..v)
        table.insert(output, v)
    end
end

答案 1 :(得分:0)

我刚刚下班,现在无法深入了解你的问题,但接下来的两行看起来很奇怪。

t = "00:00:00:00:00:00"
s = string.gsub( t, ":", "")

基本上,您要删除字符串':'中的所有t个字符。之后,您最终s"000000000000"。这可能不是你想要的?