diff --git a/src/common/tools/hosts b/src/common/tools/hosts new file mode 100644 index 0000000000000000000000000000000000000000..81b12952c9ad48e0841de70b461213052478d95a --- /dev/null +++ b/src/common/tools/hosts @@ -0,0 +1,6 @@ +[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 diff --git a/src/common/tools/hosts.go b/src/common/tools/hosts.go new file mode 100644 index 0000000000000000000000000000000000000000..0c61c247b053df17b0d8d2bcc3f6f85090d01662 --- /dev/null +++ b/src/common/tools/hosts.go @@ -0,0 +1,40 @@ +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 +}