我想解析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
>
答案 0 :(得分:0)
捕获由字母数字组成的主机名值,包括点,连字符和下划线。
x = [[Host h1
Hostname ip1
Host h2
Hostname ip2
Host *
ControlMaster auto]]
for i in x:gmatch("Hostname%s+([%w%.-_]+)") do
print(i)
end
答案 1 :(得分:0)
这是我对您的问题的完整解决方案。它从STDIN读取输入文件。像例如program.lua < /path/to/.ssh/config
--Example of SSH config file
--[[
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