使用lua按主机拆分ssh配置

我想解析linux上的ssh配置文件,以获取在_$HOME/.ssh/config_中定义的每个主机的信息(主机名、用户)。我的想法是使用lua _string.gmatch_来使用Host作为分隔符拆分文件,但由于某些原因,模式匹配不起作用。下面是来自lua解释器的代码

> =x
Host h1
Hostname ip1
User root
Host h2 h3
Hostname ip2
User admin
Host *
ControlPath xyz

> for i in x:gmatch('(Host%s+.-)Host%s') do print(i) end
Host h1
Hostname ip1
User root

>

点赞
用户3375584
用户3375584

捕获由字母数字组成的主机名值,包括点、连字符和下划线。

x = [[Host h1
Hostname ip1
Host h2
Hostname ip2

Host *
ControlMaster auto]]

for i in x:gmatch("Hostname%s+([%w%.-_]+)") do
  print(i)
end
2017-10-02 12:03:30
用户3375584
用户3375584

这是对你的问题的完整解决方案。它从 STDIN 读取输入文件。像这样运行:program.lua < /path/to/.ssh/config

--SSH配置文件示例
--[[
Host h1
HostName ip1
User root
Host h2 h3
Hostname ip2
User admin
Host *
ControlPath xyz
--]]

local hostPattern = "Host%s+([%w%.-_]+)"
local hostNamePattern = "Host[Nn]ame%s+([%w%.-_]+)"
local userPattern = "User%s+([%w%.-_]+)"

local line = io.read("l")
while line do
    if line:find(hostPattern) then
        local host = line:match(hostPattern)
        local hostName, user

        line = io.read("l")
        while line do
            if line:find(hostPattern) then
                break
            elseif line:find(hostNamePattern) then
                hostName = line:match(hostNamePattern)
            elseif line:find(userPattern) then
                user = line:match(userPattern)
            end
            line = io.read("l")
        end
        io.write(string.format("%s: -> %s, %s", host, hostName, user))
    end
    io.write("\n")
end

下面是您可以期望的输出:

h1: -> ip1, root
h2: -> ip2, admin
2017-10-07 18:52:10