2017-10-02 2 views
0

리눅스에서 ssh 설정 파일을 구문 분석하여 $ HOME/.ssh/config에 정의 된 각 호스트에 대한 정보 (호스트 이름, 사용자)를 가져 오려고합니다. 내 아이디어는 string.gmatch을 사용하여 호스트를 구분 기호로 사용하여 파일을 분할하지만 어떤 이유로 인해 패턴 일치가 작동하지 않습니다. 여기에 호스트 이름 값이 점, 하이픈 및 밑줄을 포함하여 알파벳과 숫자로 구성된 루아 인터프리터lua를 사용하여 호스트 별 ssh 설정을 분할

> =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

분할하는 방법 '에 대한 I에서 X : GSUB ('%의 F [^ %의 Z \ 없음] –

답변

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 
+0

ssh 설정에 호스트와 사용자가 모두 포함되어 있습니다. 내 예는 사용자를 표시하지 않지만 ... 내 의도는 호스트 이름과 호스트 이름을 모두 캡처하는 것입니다. 호스트 % s ','\ 0 % 0 ' 단일 호스트에 대한 사용자 솔루션이 호스트가 아니라 호스트를 캡처합니다. –

+0

내 솔루션을 사용해 보셨습니까? 그것은 반드시 호스트 값을 캡처하고 호스트 이름은 캡처하지 않습니다. 또는 Host 또는 User로 Hostname을 대체하십시오. – MrksKwsnck

+0

호스트와 정보 간의 매핑이 필요합니다. h1 -> ip1, root 및 h2 -> ip2, admin. 질문에서 예제를 업데이트했습니다. –

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 
관련 문제