Commit 5c4eb808 authored by 魏灿's avatar 魏灿

hosts转json

parent f6bd70dc
[webGroup1]
192.168.0.11 ansible_ssh_host=192.168.0.11 ansible_ssh_user=root ansible_ssh_pass=123.com ansible_ssh_port=3333
192.168.0.12 ansible_ssh_host=192.168.0.12 ansible_ssh_user=root ansible_ssh_pass=1234.com ansible_ssh_port=2222
[webGroup2]
192.168.1.11 ansible_ssh_host=192.168.1.11 ansible_ssh_user=admin ansible_ssh_pass=ccc.com ansible_ssh_port=11
192.168.1.12 ansible_ssh_host=192.168.1.12 ansible_ssh_user=admin ansible_ssh_pass=111.com ansible_ssh_port=22
\ No newline at end of file
package tools
import (
"bufio"
"log"
"os"
"strings"
)
func HostsToJson() (data map[string][]string, err error) {
f, err := os.Open(`/etc/ansible/hosts`)
if err != nil {
return nil, err
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
data = make(map[string][]string)
// 以这个文件为参数,创建一个 scanner
s := bufio.NewScanner(f)
var key string
var per []string
// 扫描每行文件,按行读取
for s.Scan() {
if strings.HasPrefix(s.Text(), "[") && strings.HasSuffix(s.Text(), "]") {
key = s.Text()
per = []string{}
data[key] = per
} else {
data[key] = append(data[key], s.Text())
}
}
err = s.Err()
if err != nil {
return nil, err
}
return data, nil
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment